TheYuchen commited on
Commit
d105dc7
·
1 Parent(s): f956d64

Composition comparison: two archived runs side by side, CIs not scalars

Browse files

Phase 3 (minimal viable) of the evidence-workbench rework. Pick any
two runs in the history panel (checkboxes, keep-latest-two) and a
comparison panel renders:

* configuration diff — params matched structurally by (kind,
occurrence) exactly like configHash, so node ids and layout don't
matter; circuit swaps surface as a "circuit" row;
* same-configuration detection — when the config hashes match the
panel says so explicitly ("differences are noise"), because that
changes how any metric gap must be read;
* fidelity compared as intervals — both Wilson CIs on one 0-1 scale
with the Δ in percentage points, and an explicit "intervals
overlap: not evidence" callout when the difference is within
run-to-run noise at these shot counts;
* step-by-step alignment with each side's transformation signature.

frontend/src/components/CompareView.tsx ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Composition comparison — two archived runs side by side.
2
+ //
3
+ // This answers the cross-composition question ("A vs B, what actually
4
+ // differs and what did it buy me?") that single-run cards cannot:
5
+ // * configuration diff — which node params differ between the two
6
+ // graphs (computed structurally, not by node id);
7
+ // * step-by-step alignment with each side's transformation
8
+ // signature and headline metric;
9
+ // * fidelity deltas as INTERVALS, not scalars — when both sides
10
+ // carry a sampled distribution the two Wilson CIs render on one
11
+ // 0-1 scale, and overlap is called out, because "0.462 < 0.475"
12
+ // is not evidence when both intervals span the difference.
13
+
14
+ import { useEffect, useState } from "react";
15
+ import { X } from "lucide-react";
16
+ import type { StepResult } from "../lib/api";
17
+ import { useApp } from "../lib/store";
18
+ import { getRun, type RunRecord } from "../lib/runStore";
19
+ import { transformationOf } from "./TransformationSignature";
20
+
21
+ function sigText(step: StepResult | undefined): string {
22
+ const t = transformationOf(step);
23
+ if (!t || !t.changed) return "·";
24
+ const parts: string[] = [];
25
+ const d = t.delta;
26
+ if (d.num_qubits) parts.push(`Q${d.num_qubits > 0 ? "+" : ""}${d.num_qubits}`);
27
+ if (d.depth) parts.push(`D${d.depth > 0 ? "+" : ""}${d.depth}`);
28
+ if (d.size) parts.push(`G${d.size > 0 ? "+" : ""}${d.size}`);
29
+ if (d.num_parameters) parts.push(`P${d.num_parameters > 0 ? "+" : ""}${d.num_parameters}`);
30
+ return parts.join(" ") || "·";
31
+ }
32
+
33
+ function fidelityStep(r: RunRecord): StepResult | undefined {
34
+ for (let i = r.response.steps.length - 1; i >= 0; i--) {
35
+ const s = r.response.steps[i];
36
+ if (s.node_type === "fidelity" && s.status === "ok") return s;
37
+ }
38
+ return undefined;
39
+ }
40
+
41
+ /** Structural param diff between the two graphs: nodes are matched by
42
+ * (kind, occurrence index in a canonically sorted list), the same
43
+ * convention configHash uses, so layout and node ids don't matter. */
44
+ function paramDiff(a: RunRecord, b: RunRecord): Array<{ where: string; left: string; right: string }> {
45
+ const canon = (r: RunRecord) =>
46
+ [...r.graph.n]
47
+ .map((n) => ({ kind: n.k, params: n.p ?? {} }))
48
+ .sort((x, y) => {
49
+ const kx = `${x.kind}|${JSON.stringify(x.params)}`;
50
+ const ky = `${y.kind}|${JSON.stringify(y.params)}`;
51
+ return kx < ky ? -1 : kx > ky ? 1 : 0;
52
+ });
53
+ const A = canon(a);
54
+ const B = canon(b);
55
+ const out: Array<{ where: string; left: string; right: string }> = [];
56
+ const byKind = (list: typeof A) => {
57
+ const m = new Map<string, Array<Record<string, unknown>>>();
58
+ list.forEach((n) => {
59
+ const arr = m.get(n.kind) ?? [];
60
+ arr.push(n.params);
61
+ m.set(n.kind, arr);
62
+ });
63
+ return m;
64
+ };
65
+ const mA = byKind(A);
66
+ const mB = byKind(B);
67
+ const kinds = new Set([...mA.keys(), ...mB.keys()]);
68
+ kinds.forEach((kind) => {
69
+ const la = mA.get(kind) ?? [];
70
+ const lb = mB.get(kind) ?? [];
71
+ const n = Math.max(la.length, lb.length);
72
+ for (let i = 0; i < n; i++) {
73
+ const pa = la[i];
74
+ const pb = lb[i];
75
+ if (pa === undefined || pb === undefined) {
76
+ out.push({
77
+ where: kind,
78
+ left: pa === undefined ? "(absent)" : "(present)",
79
+ right: pb === undefined ? "(absent)" : "(present)",
80
+ });
81
+ continue;
82
+ }
83
+ const keys = new Set([...Object.keys(pa), ...Object.keys(pb)]);
84
+ keys.forEach((k) => {
85
+ const va = JSON.stringify(pa[k] ?? null);
86
+ const vb = JSON.stringify(pb[k] ?? null);
87
+ if (va !== vb) out.push({ where: `${kind}.${k}`, left: va, right: vb });
88
+ });
89
+ }
90
+ });
91
+ if (a.sample_key !== b.sample_key) {
92
+ out.unshift({
93
+ where: "circuit",
94
+ left: a.sample_key ?? a.circuit_name ?? "upload",
95
+ right: b.sample_key ?? b.circuit_name ?? "upload",
96
+ });
97
+ }
98
+ return out;
99
+ }
100
+
101
+ function ciOf(s: StepResult | undefined): [number, number] | null {
102
+ const d = s?.distribution as { ci95?: [number, number] } | null | undefined;
103
+ return d?.ci95 ?? null;
104
+ }
105
+
106
+ export function CompareView() {
107
+ const compareIds = useApp((s) => s.compareIds);
108
+ const clearCompare = useApp((s) => s.clearCompare);
109
+ const [recs, setRecs] = useState<[RunRecord, RunRecord] | null>(null);
110
+
111
+ useEffect(() => {
112
+ if (compareIds.length !== 2) {
113
+ setRecs(null);
114
+ return;
115
+ }
116
+ let cancelled = false;
117
+ Promise.all([getRun(compareIds[0]), getRun(compareIds[1])]).then(([a, b]) => {
118
+ if (!cancelled && a && b) setRecs([a, b]);
119
+ });
120
+ return () => {
121
+ cancelled = true;
122
+ };
123
+ }, [compareIds]);
124
+
125
+ if (compareIds.length !== 2 || !recs) return null;
126
+ const [A, B] = recs;
127
+ const diffs = paramDiff(A, B);
128
+ const fa = fidelityStep(A);
129
+ const fb = fidelityStep(B);
130
+ const va = A.headline_value;
131
+ const vb = B.headline_value;
132
+ const ciA = ciOf(fa);
133
+ const ciB = ciOf(fb);
134
+ const overlap =
135
+ ciA && ciB ? Math.max(0, Math.min(ciA[1], ciB[1]) - Math.max(ciA[0], ciB[0])) > 0 : null;
136
+
137
+ const n = Math.max(A.response.steps.length, B.response.steps.length);
138
+ const rows = Array.from({ length: n }, (_, i) => ({
139
+ a: A.response.steps[i],
140
+ b: B.response.steps[i],
141
+ }));
142
+
143
+ return (
144
+ <div className="panel-alt p-3 space-y-2 border !border-accent/40">
145
+ <div className="flex items-center gap-2">
146
+ <span className="text-xs font-semibold text-ink">Comparing two runs</span>
147
+ <span className="chip">A · {new Date(A.created_at).toLocaleTimeString()}</span>
148
+ <span className="chip">B · {new Date(B.created_at).toLocaleTimeString()}</span>
149
+ {A.config_hash === B.config_hash ? (
150
+ <span className="chip !border-ok/40 !text-ok" title="Identical circuit + graph + params — any metric difference is run-to-run variation (shot noise, training stochasticity).">
151
+ same configuration — differences are noise
152
+ </span>
153
+ ) : (
154
+ <span className="chip !border-warn/40 !text-warn">
155
+ {diffs.length} setting{diffs.length === 1 ? "" : "s"} differ
156
+ </span>
157
+ )}
158
+ <button
159
+ type="button"
160
+ className="ml-auto p-0.5 text-mute hover:text-ink rounded hover:bg-surfaceAlt"
161
+ onClick={clearCompare}
162
+ aria-label="Close comparison"
163
+ >
164
+ <X className="w-3.5 h-3.5" />
165
+ </button>
166
+ </div>
167
+
168
+ {diffs.length > 0 && (
169
+ <div className="space-y-0.5">
170
+ {diffs.slice(0, 8).map((d, i) => (
171
+ <div key={i} className="text-[10px] font-mono flex gap-2">
172
+ <span className="text-mute w-32 truncate" title={d.where}>{d.where}</span>
173
+ <span className="text-ink truncate" title={d.left}>{d.left}</span>
174
+ <span className="text-mute">→</span>
175
+ <span className="text-accent truncate" title={d.right}>{d.right}</span>
176
+ </div>
177
+ ))}
178
+ {diffs.length > 8 && (
179
+ <div className="text-[10px] text-mute">…and {diffs.length - 8} more</div>
180
+ )}
181
+ </div>
182
+ )}
183
+
184
+ {/* Fidelity: intervals, not scalars */}
185
+ {va != null && vb != null && (
186
+ <div className="space-y-1">
187
+ <div className="text-[10px] uppercase tracking-wider text-mute">fidelity</div>
188
+ <div className="relative h-6 rounded bg-surfaceAlt" aria-hidden>
189
+ {ciA && (
190
+ <div className="absolute top-1 h-1.5 bg-accent/30 rounded"
191
+ style={{ left: `${ciA[0] * 100}%`, width: `${Math.max(0.5, (ciA[1] - ciA[0]) * 100)}%` }} />
192
+ )}
193
+ <div className="absolute top-0.5 h-2.5 w-0.5 bg-accent" style={{ left: `${va * 100}%` }} title={`A: ${(va * 100).toFixed(2)}%`} />
194
+ {ciB && (
195
+ <div className="absolute bottom-1 h-1.5 bg-warn/30 rounded"
196
+ style={{ left: `${ciB[0] * 100}%`, width: `${Math.max(0.5, (ciB[1] - ciB[0]) * 100)}%` }} />
197
+ )}
198
+ <div className="absolute bottom-0.5 h-2.5 w-0.5 bg-warn" style={{ left: `${vb * 100}%` }} title={`B: ${(vb * 100).toFixed(2)}%`} />
199
+ </div>
200
+ <div className="text-[10px] text-mute font-mono">
201
+ A {(va * 100).toFixed(2)}% · B {(vb * 100).toFixed(2)}% · Δ(B−A){" "}
202
+ {((vb - va) * 100).toFixed(2)}pp
203
+ {overlap === true && (
204
+ <span className="text-warn ml-1" title="The two 95% intervals overlap — this difference is within run-to-run noise at these shot counts. Run more replicates or raise shots before reading anything into it.">
205
+ — intervals overlap: not evidence
206
+ </span>
207
+ )}
208
+ {overlap === false && (
209
+ <span className="text-ok ml-1">— intervals separated</span>
210
+ )}
211
+ </div>
212
+ </div>
213
+ )}
214
+
215
+ {/* step-by-step */}
216
+ <table className="w-full text-[10px]">
217
+ <thead>
218
+ <tr className="text-mute text-left">
219
+ <th className="font-normal pb-0.5">step</th>
220
+ <th className="font-normal pb-0.5">A sig</th>
221
+ <th className="font-normal pb-0.5">B sig</th>
222
+ <th className="font-normal pb-0.5">A / B status</th>
223
+ </tr>
224
+ </thead>
225
+ <tbody>
226
+ {rows.map((r, i) => (
227
+ <tr key={i} className="border-t border-edge/40">
228
+ <td className="py-0.5 text-ink">
229
+ {r.a?.label ?? r.b?.label ?? "—"}
230
+ {r.a && r.b && r.a.node_type !== r.b.node_type && (
231
+ <span className="text-warn ml-1" title={`A: ${r.a.node_type}, B: ${r.b.node_type}`}>≠</span>
232
+ )}
233
+ </td>
234
+ <td className="py-0.5 font-mono text-mute">{sigText(r.a)}</td>
235
+ <td className="py-0.5 font-mono text-mute">{sigText(r.b)}</td>
236
+ <td className="py-0.5 font-mono text-mute">
237
+ {r.a?.status ?? "—"} / {r.b?.status ?? "—"}
238
+ </td>
239
+ </tr>
240
+ ))}
241
+ </tbody>
242
+ </table>
243
+ </div>
244
+ );
245
+ }
frontend/src/components/ResultsPane.tsx CHANGED
@@ -24,6 +24,7 @@ import { PluginFigures } from "./PluginFigures";
24
  import { RunStatusChips } from "./RunStatusChips";
25
  import { RunHistory } from "./RunHistory";
26
  import { SignatureCard } from "./TransformationSignature";
 
27
 
28
  export function ResultsPane({ onCollapse }: { onCollapse?: () => void } = {}) {
29
  const run = useApp((s) => s.run);
@@ -75,6 +76,7 @@ export function ResultsPane({ onCollapse }: { onCollapse?: () => void } = {}) {
75
  </div>
76
  </div>
77
  <div className="flex-1 overflow-y-auto p-3 space-y-3 min-h-0">
 
78
  <RunHistory />
79
  {!run && !running && <EmptyHint />}
80
  {running && <RunningHint />}
 
24
  import { RunStatusChips } from "./RunStatusChips";
25
  import { RunHistory } from "./RunHistory";
26
  import { SignatureCard } from "./TransformationSignature";
27
+ import { CompareView } from "./CompareView";
28
 
29
  export function ResultsPane({ onCollapse }: { onCollapse?: () => void } = {}) {
30
  const run = useApp((s) => s.run);
 
76
  </div>
77
  </div>
78
  <div className="flex-1 overflow-y-auto p-3 space-y-3 min-h-0">
79
+ <CompareView />
80
  <RunHistory />
81
  {!run && !running && <EmptyHint />}
82
  {running && <RunningHint />}
frontend/src/components/RunHistory.tsx CHANGED
@@ -34,6 +34,8 @@ function hashHue(hash: string): number {
34
  export function RunHistory() {
35
  const historyVersion = useApp((s) => s.historyVersion);
36
  const requestRestore = useApp((s) => s.requestRestore);
 
 
37
  const [records, setRecords] = useState<RunRecord[]>([]);
38
  const [open, setOpen] = useState(false);
39
 
@@ -80,6 +82,14 @@ export function RunHistory() {
80
  <ul className="max-h-64 overflow-y-auto divide-y divide-edge/60">
81
  {records.map((r) => (
82
  <li key={r.run_id} className="px-3 py-1.5 flex items-center gap-2 text-[11px]">
 
 
 
 
 
 
 
 
83
  <span
84
  className={`w-1.5 h-1.5 rounded-full shrink-0 ${r.ok ? "bg-ok" : "bg-danger"}`}
85
  title={r.ok ? "completed" : "errored"}
 
34
  export function RunHistory() {
35
  const historyVersion = useApp((s) => s.historyVersion);
36
  const requestRestore = useApp((s) => s.requestRestore);
37
+ const compareIds = useApp((s) => s.compareIds);
38
+ const toggleCompare = useApp((s) => s.toggleCompare);
39
  const [records, setRecords] = useState<RunRecord[]>([]);
40
  const [open, setOpen] = useState(false);
41
 
 
82
  <ul className="max-h-64 overflow-y-auto divide-y divide-edge/60">
83
  {records.map((r) => (
84
  <li key={r.run_id} className="px-3 py-1.5 flex items-center gap-2 text-[11px]">
85
+ <input
86
+ type="checkbox"
87
+ className="w-3 h-3 accent-current shrink-0 cursor-pointer"
88
+ checked={compareIds.includes(r.run_id)}
89
+ onChange={() => toggleCompare(r.run_id)}
90
+ title="Select for comparison (pick two runs)"
91
+ aria-label={`Select run ${r.run_id} for comparison`}
92
+ />
93
  <span
94
  className={`w-1.5 h-1.5 rounded-full shrink-0 ${r.ok ? "bg-ok" : "bg-danger"}`}
95
  title={r.ok ? "completed" : "errored"}
frontend/src/lib/store.ts CHANGED
@@ -80,6 +80,15 @@ interface AppState {
80
  restoredFrom: string | null;
81
  setRestoredFrom: (v: string | null) => void;
82
 
 
 
 
 
 
 
 
 
 
83
  health: HealthResponse | null;
84
  setHealth: (h: HealthResponse | null) => void;
85
 
@@ -195,6 +204,14 @@ export const useApp = create<AppState>((set) => ({
195
  clearRestore: () => set({ pendingRestore: null }),
196
  restoredFrom: null,
197
  setRestoredFrom: (v) => set({ restoredFrom: v }),
 
 
 
 
 
 
 
 
198
  health: null,
199
  setHealth: (h) => set({ health: h }),
200
  running: false,
 
80
  restoredFrom: string | null;
81
  setRestoredFrom: (v: string | null) => void;
82
 
83
+ /**
84
+ * Comparison selection: up to two archived run_ids. When two are
85
+ * chosen the CompareView panel renders them side by side. Toggling
86
+ * a third id replaces the older selection (keep-latest-two).
87
+ */
88
+ compareIds: string[];
89
+ toggleCompare: (runId: string) => void;
90
+ clearCompare: () => void;
91
+
92
  health: HealthResponse | null;
93
  setHealth: (h: HealthResponse | null) => void;
94
 
 
204
  clearRestore: () => set({ pendingRestore: null }),
205
  restoredFrom: null,
206
  setRestoredFrom: (v) => set({ restoredFrom: v }),
207
+ compareIds: [],
208
+ toggleCompare: (runId) =>
209
+ set((s) => {
210
+ if (s.compareIds.includes(runId))
211
+ return { compareIds: s.compareIds.filter((x) => x !== runId) };
212
+ return { compareIds: [...s.compareIds, runId].slice(-2) };
213
+ }),
214
+ clearCompare: () => set({ compareIds: [] }),
215
  health: null,
216
  setHealth: (h) => set({ health: h }),
217
  running: false,