File size: 21,496 Bytes
d105dc7 ecfb151 d105dc7 4288025 02aa1f6 d105dc7 4288025 d105dc7 4288025 f25d955 64aa288 f25d955 2e22380 f25d955 ecfb151 d105dc7 ecfb151 e200590 d105dc7 f2fb736 d105dc7 f2fb736 d105dc7 e200590 f2fb736 e200590 f2fb736 e200590 d105dc7 e200590 d105dc7 02aa1f6 f2fb736 d105dc7 f25d955 d105dc7 f25d955 64aa288 f25d955 64aa288 f25d955 d105dc7 e200590 d105dc7 64aa288 d105dc7 ecfb151 d105dc7 64aa288 d105dc7 64aa288 d105dc7 02aa1f6 d105dc7 02aa1f6 d105dc7 02aa1f6 d105dc7 f25d955 d105dc7 f25d955 64aa288 f25d955 d105dc7 | 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 500 501 502 503 504 505 506 507 508 | // 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 <span className="font-mono text-mute">·</span>;
return (
<span className="inline-block align-middle" title={sigText(step)}>
<SignatureGlyph t={t} size="tile" />
</span>
);
}
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 (
<tr className="border-t border-edge/40">
<td
className={`py-0.5 text-ink ${
divergence ? "border-l-2 border-l-accent/70 pl-1.5" : ""
}`}
>
{a?.label ?? b?.label ?? "—"}
{a && b && a.node_type !== b.node_type && (
<span className="text-warn ml-1" title={`A: ${a.node_type}, B: ${b.node_type}`}>≠</span>
)}
{divergence && (
<span
className="ml-1.5 text-[9px] uppercase tracking-wider text-accent"
title="First step where the two compositions differ (node kind, params, or transformation signature). Everything above is shared prefix."
>
divergence point
</span>
)}
</td>
<td className="py-0.5 pr-2"><SigCell step={a} /></td>
<td className="py-0.5 pr-2"><SigCell step={b} /></td>
<td className="py-0.5 font-mono text-mute">
{a?.status ?? "—"} / {b?.status ?? "—"}
</td>
</tr>
);
}
/** 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<string, Array<Record<string, unknown>>>();
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 (
<div className="panel-alt p-3 space-y-2 border !border-warn/40">
<div className="flex items-center gap-2">
<span className="text-xs font-semibold text-ink">
Comparing two runs
</span>
<button
type="button"
className="ml-auto p-0.5 text-mute hover:text-ink rounded hover:bg-surfaceAlt"
onClick={clearCompare}
aria-label="Clear comparison selection"
>
<X className="w-3.5 h-3.5" />
</button>
</div>
<p className="text-[11px] text-mute leading-relaxed">
The selected runs are no longer archived — they were deleted or
removed with the demo data. Tick two runs in the{" "}
<span className="text-ink">“This configuration”</span> tab to
start a new comparison.
</p>
</div>
);
}
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 (
<div className="panel-alt p-3 space-y-2 border !border-accent/40">
{/* 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. */}
<div className="flex flex-wrap items-center gap-2 gap-y-1">
<span className="text-xs font-semibold text-ink">Comparing two runs</span>
{/* 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. */}
<span className="chip" title={new Date(A.created_at).toLocaleString()}>
A · {fmtWhen(A.created_at)}
</span>
<span className="chip" title={new Date(B.created_at).toLocaleString()}>
B · {fmtWhen(B.created_at)}
</span>
{A.config_hash === B.config_hash ? (
<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).">
same configuration — differences are noise
</span>
) : (
<span className="chip !border-warn/40 !text-warn">
{diffs.length} setting{diffs.length === 1 ? "" : "s"} differ
</span>
)}
{/* 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) && (
<button
type="button"
data-marker="theater-overlay"
className="chip !border-accent/50 !text-accent hover:bg-accent/10 flex items-center gap-1"
title="Open the evidence theater with both runs' shot-batch funnels overlaid on one axis pair — two replays of one configuration, same rule, different draws."
onClick={() => setTheaterOverlay([A.run_id, B.run_id])}
>
<Presentation className="w-3 h-3" />
overlay in theater ↗
</button>
)}
<button
type="button"
className="ml-auto p-0.5 text-mute hover:text-ink rounded hover:bg-surfaceAlt"
onClick={clearCompare}
aria-label="Close comparison"
>
<X className="w-3.5 h-3.5" />
</button>
</div>
{diffs.length > 0 && (
<div className="space-y-0.5">
{diffs.slice(0, 8).map((d, i) => (
<div key={i} className="text-[10px] font-mono flex gap-2">
<span className="text-mute w-32 truncate" title={d.where}>{d.where}</span>
<span className="text-ink truncate" title={d.left}>{d.left}</span>
<span className="text-mute">→</span>
<span className="text-accent truncate" title={d.right}>{d.right}</span>
</div>
))}
{diffs.length > 8 && (
<div className="text-[10px] text-mute">…and {diffs.length - 8} more</div>
)}
</div>
)}
{/* Fidelity: intervals, not scalars */}
{va != null && vb != null && (
<div className="space-y-1">
<div className="text-[10px] uppercase tracking-wider text-mute">fidelity</div>
<div className="relative h-6 rounded bg-surfaceAlt" aria-hidden>
{ciA && (
<div className="absolute top-1 h-1.5 bg-accent/30 rounded"
style={{ left: `${ciA[0] * 100}%`, width: `${Math.max(0.5, (ciA[1] - ciA[0]) * 100)}%` }} />
)}
{/* 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. */}
<div className="absolute top-0 h-3.5 w-2.5 flex justify-center" style={{ left: `clamp(0px, calc(${va * 100}% - 5px), calc(100% - 10px))` }} title={`A: ${(va * 100).toFixed(2)}%`}>
<div className="h-full w-0.5 bg-accent mt-0.5" style={{ height: "10px" }} />
</div>
{ciB && (
<div className="absolute bottom-1 h-1.5 bg-warn/30 rounded"
style={{ left: `${ciB[0] * 100}%`, width: `${Math.max(0.5, (ciB[1] - ciB[0]) * 100)}%` }} />
)}
<div className="absolute bottom-0 h-3.5 w-2.5 flex items-end justify-center" style={{ left: `clamp(0px, calc(${vb * 100}% - 5px), calc(100% - 10px))` }} title={`B: ${(vb * 100).toFixed(2)}%`}>
<div className="w-0.5 bg-warn mb-0.5" style={{ height: "10px" }} />
</div>
</div>
<div className="text-[10px] text-mute font-mono">
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" ? (
<span
className="text-accent ml-1"
title="These two bars compare only the two selected runs. The difference funnel below pools every archived replicate of each configuration and puts a single 95% interval on the difference itself — that accumulating interval is the verdict to trust."
>
— see the difference funnel below: the honest verdict
accumulates across all archived replicates
</span>
) : (
<>
{overlap === true && (
<span className="text-warn ml-1" title="The two 95% intervals overlap — at these shot counts this view cannot distinguish the difference from run-to-run noise (overlap is a conservative screen, not a hypothesis test: a formal test could still detect a smaller real difference). Run more replicates or raise shots before reading anything into it.">
— intervals overlap: not evidence
</span>
)}
{overlap === false && (
<span className="text-ok ml-1">— intervals separated</span>
)}
</>
)}
</div>
</div>
)}
{/* 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). */}
<DifferenceFunnel data={diffData} />
{/* step-by-step */}
<table className="w-full text-[10px]">
<thead>
<tr className="text-mute text-left">
<th className="font-normal pb-0.5">step</th>
<th className="font-normal pb-0.5">A sig</th>
<th className="font-normal pb-0.5">B sig</th>
<th className="font-normal pb-0.5">A / B status</th>
</tr>
</thead>
<tbody>
{prefixLen > 0 && (
<tr className="border-t border-edge/40">
<td colSpan={4} className="py-0.5">
<details>
<summary className="cursor-pointer select-none text-mute hover:text-ink">
shared prefix · {prefixLen} steps
<span className="ml-1 text-mute/60">
(identical kind, params and signature on both sides)
</span>
</summary>
<table className="w-full mt-0.5">
<tbody>
{rows.slice(0, prefixLen).map((pair, i) => (
<CompareRow key={i} pair={pair} />
))}
</tbody>
</table>
</details>
</td>
</tr>
)}
{rows.slice(prefixLen).map((pair, i) => (
<CompareRow
key={prefixLen + i}
pair={pair}
// Absolute row position, not "first rendered row": with
// a 1-row unfolded prefix the divergence is row 1.
divergence={prefixLen + i === divergenceIdx}
/>
))}
</tbody>
</table>
</div>
);
}
|