TheYuchen commited on
Commit
75184f5
·
1 Parent(s): 0584fbb

Wave J: uncertainty-in-provenance (evidence-mass lineage, pooled CIs)

Browse files

Provenance views stop pretending states are deterministic — lineage
nodes ARE distributions, so the timeline now shows how certainty
accumulated over the session. Minimal honest version, one task per
mark:

* evidence mass (marker `evidence-mass`): lineage dot AREA propto
sqrt(executed shots), radius 3-7px against a fixed 2048-shot
reference; early-stopped runs are visibly lighter. Ring / slash /
edges / hover target track the radius; tooltip gains "N shots of
evidence".
* replicate-band certainty funnel: pooled Wilson CI half-width at
each row (counts summed oldest->newest; valid within a config
group: same underlying p), mirrored polylines around the lane
spine, narrowing upward ~1/sqrt(N) — Wave I's funnel motif, second
context. Tooltip: "pooled +/-X.Xpp after n runs / N shots".
* lib/stats.ts (new): wilson95 ported from
app/services/stats.py::wilson_interval with unit-anchor comments;
runEvidence / poolEvidence helpers.
* Multiverse cards: "pooled mu x.x% +/-y.ypp over N shots" + filled
pooled band on the 0-1 strip (distinct mark from single-draw
dots); Delta vs baseline compares POOLED means when both sides
have pools; "(n small)" keys on >=2048 pooled shots per side
(worst-case Wilson half-width <= +/-2.2pp).
* ReplicateStrip (fidelity card): same pooled summary line.

tsc + build + VITE_ANON=1 build clean; 77 backend tests green; F2/F4
scenario expectations updated/reviewed.

docs/EVIDENCE_WORKBENCH.md CHANGED
@@ -172,16 +172,15 @@ test_gate_diff 14, test_workflow_helpers 11, test_seed_coverage 8).
172
  .py preserves run_ids/lineage/created_at, swaps responses;
173
  RESUMABLE — walks records, caching each via the pinned step cache,
174
  exits on a per-record timeout so the sandbox's ~40 s process cap
175
- can't truncate a long batch). Migration status at this commit:
176
- 14/17 done (all bell_state 512+2048, the same-seed replay pair);
177
- the 3 vqc_2q_small records (QuCAD → sampled) still carry the old
178
- single-draw numbers — their sampled step lacks `trace`, so the
179
- loader simply omits the funnel and keeps the CI bar (verified
180
- graceful). Finish them with the script when the Space is idle:
181
- QuCAD's per-request noise-model build outlives a 40 s client
182
- window, so it needs an uninterrupted long-lived request. This is
183
- demo scaffolding, not a feature dependency — the live-run
184
- assertions below hold on the deployed build regardless.
185
  20. **SSE progress protocol** — during a sampled step the stream
186
  interleaves `{"step_progress": {node_id, batch_i, n_batches,
187
  shots_done, successes, point, ci95}}` events between StepResults
@@ -250,6 +249,61 @@ at 512/2048 shots (2/8 batches, half-width 0.0430 ≤ 0.05, point
250
  and the identical batch trace — optional stopping is bit-exactly
251
  replayable.
252
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
253
  ## Not done yet (ordered backlog)
254
 
255
  * **Phase 3.5 leftovers** — pick-which-fidelity-node in comparison,
@@ -295,10 +349,11 @@ genuinely unnamed ideas; both DEEPEN the existing narrative
295
  optional stopping a visual interaction. Sequential-analysis
296
  steering has no prior art in VIS. Pinned replay stays bit-exact via
297
  per-batch seeds derived from node_seed.
298
- * **Wave J — Uncertainty-in-provenance** (next session): lineage nodes
299
- ARE distributions; encode evidence mass (node weight) and its
300
- split/accumulation across forks. Minimal honest version only — no
301
- decoration without a task.
 
302
  * Wave K (paper discussion, not build): difference-of-differences
303
  ("did more shots help bell more than vqc?") as future work.
304
 
@@ -383,5 +438,5 @@ here. Reviewers are vis people, not quantum people. Status per item:
383
  surfaces (canvas+ribbons, multiverse, funnel, lineage, compare,
384
  share/export) each back a claim.
385
 
386
- Still open from before Wave P: rerecord_demo_archive.py for the 3
387
- vqc records; Wave J (uncertainty-in-provenance).
 
172
  .py preserves run_ids/lineage/created_at, swaps responses;
173
  RESUMABLE — walks records, caching each via the pinned step cache,
174
  exits on a per-record timeout so the sandbox's ~40 s process cap
175
+ can't truncate a long batch). Migration status: COMPLETE
176
+ (Wave J session, 2026-07-05) — the 3 vqc_2q_small records were
177
+ finished with the fire-and-repoll pattern (first request warms the
178
+ now-memoized noise model server-side and times out client-side;
179
+ the re-request hits the pinned step cache instantly). All 17
180
+ records now carry per-batch traces (bell 512 → 4 batches, bell
181
+ 2048 / vqc 1024 → 8), every trace's last frame equals the
182
+ distribution totals, and the same-seed replay pair is bit-
183
+ identical. Archive 110 KB.
 
184
  20. **SSE progress protocol** — during a sampled step the stream
185
  interleaves `{"step_progress": {node_id, batch_i, n_batches,
186
  shots_done, successes, point, ci95}}` events between StepResults
 
249
  and the identical batch trace — optional stopping is bit-exactly
250
  replayable.
251
 
252
+ ## Shipped, seventh push (Wave J — uncertainty-in-provenance)
253
+
254
+ Premise: provenance visualizations everywhere assume deterministic
255
+ states; our lineage nodes ARE distributions. Wave J makes the archive
256
+ views answer "how did certainty accumulate over the session?" —
257
+ minimal honest version, no decoration without a task.
258
+
259
+ 24. **Evidence mass in the lineage** (marker/class `evidence-mass`,
260
+ RunHistory.tsx) — node dot AREA ∝ √(total shots the run's
261
+ stochastic steps actually EXECUTED), radius 3–7 px against a
262
+ FIXED 2048-shot reference (not view-normalized, same stability
263
+ argument as the hash→hue mapping: a run keeps its weight across
264
+ sessions and figures). Area not radius because dots read as
265
+ quantities; √shots so one 4096-shot run cannot visually swallow
266
+ eight 512s; runs with no sampled step keep the 3 px floor
267
+ (absence of evidence, not zero size). Because
268
+ `distribution.shots` records EXECUTED shots, an early-stopped run
269
+ is automatically lighter than a full one — optional stopping is
270
+ now legible in the provenance record itself. Ring (pinned),
271
+ hollow+slash (error), fork-edge endpoints and the hover target
272
+ all track the radius. Tooltip gains "N shots of evidence".
273
+ 25. **Replicate-group certainty funnel** (RunHistory.tsx) — alongside
274
+ each contiguous replicate band, two thin polylines mirrored
275
+ around the lane spine: at each run's row, the POOLED Wilson CI
276
+ half-width of the band's binomial counts accumulated up to and
277
+ including that run (oldest at the bottom ⇒ the funnel narrows
278
+ upward ≈ 1/√N). Pooling = Σsuccesses/Σshots + one Wilson
279
+ interval, valid because a config_hash group is replicates of ONE
280
+ configuration ⇒ same underlying p (rationale comment in
281
+ lib/stats.ts). Normalized per group (widest row → ±10 px): the
282
+ task is the SHAPE of across-run accumulation; absolute numbers
283
+ live in the tooltip ("pooled ±X.Xpp after n runs / N shots").
284
+ Deliberately the same visual vocabulary as Wave I's within-run
285
+ evidence funnel — one motif, two contexts: shots accumulating
286
+ inside a run, runs accumulating inside a group. Only drawn when
287
+ the band has ≥2 binomial runs.
288
+ 26. **Pooled intervals where replicates aggregate** (lib/stats.ts new;
289
+ MultiverseBoard.tsx, results/cards.tsx ReplicateStrip) —
290
+ `wilson95` is a cited port of the backend's
291
+ app/services/stats.py::wilson_interval (unit-anchor comments pin
292
+ it to the live-regression numbers, e.g. wilson95(238,512) →
293
+ ±0.0430); `runEvidence` sums a run's binomial payloads;
294
+ `poolEvidence` pools runs. Multiverse cards with ≥2 binomial runs
295
+ show "pooled μ x.x% ±y.ypp over N shots" plus a FILLED BAND on
296
+ the 0-1 outcome strip — a deliberately different mark than the
297
+ per-run dots (dots = single draws, band = the interval the pooled
298
+ counts support). The Δ-vs-baseline line switches to comparing
299
+ POOLED means when both sides have pools, and the "(n small)"
300
+ suffix keys on pooled shots: ≥2048 on BOTH sides (worst-case
301
+ Wilson half-width ≤ ±2.2pp = one full default budget per side) ⇒
302
+ suffix off; otherwise the old replicate-count heuristic stands.
303
+ The fidelity card's across-runs ReplicateStrip carries the same
304
+ pooled summary line. Frontend-only: no server change, archived
305
+ responses already carry the counts.
306
+
307
  ## Not done yet (ordered backlog)
308
 
309
  * **Phase 3.5 leftovers** — pick-which-fidelity-node in comparison,
 
349
  optional stopping a visual interaction. Sequential-analysis
350
  steering has no prior art in VIS. Pinned replay stays bit-exact via
351
  per-batch seeds derived from node_seed.
352
+ * **Wave J — Uncertainty-in-provenance** (SHIPPED — see items 24-26):
353
+ lineage nodes ARE distributions; evidence mass as node weight,
354
+ pooled-certainty funnels along replicate bands, pooled Wilson
355
+ intervals wherever replicates aggregate. Minimal honest version —
356
+ no decoration without a task.
357
  * Wave K (paper discussion, not build): difference-of-differences
358
  ("did more shots help bell more than vqc?") as future work.
359
 
 
438
  surfaces (canvas+ribbons, multiverse, funnel, lineage, compare,
439
  share/export) each back a claim.
440
 
441
+ Both leftovers from before Wave P are now closed: the demo archive
442
+ re-record is complete (see item 19) and Wave J shipped (items 24-26).
frontend/src/components/MultiverseBoard.tsx CHANGED
@@ -24,6 +24,13 @@
24
  // * Δmean vs baseline is stated in percentage points and flagged
25
  // "(n small)" below 3 replicates on either side — a difference
26
  // built on one draw is not evidence, and the UI says so.
 
 
 
 
 
 
 
27
 
28
  import { useEffect, useMemo, useRef, useState } from "react";
29
  import { GitCompare, RotateCcw, Workflow } from "lucide-react";
@@ -33,6 +40,13 @@ import type { SharePayload, ShareNode } from "../lib/share";
33
  import { resolveNodeSpec, type NodeSpec } from "../lib/nodeCatalog";
34
  import type { PluginManifest } from "../lib/api";
35
  import { hashHue, hueCss } from "../lib/hues";
 
 
 
 
 
 
 
36
  import { WorkspaceToggle } from "./WorkspaceToggle";
37
  import { DemoArchiveBanner } from "./DemoArchiveBanner";
38
  import { FigureExportButton } from "./FigureExportButton";
@@ -51,6 +65,11 @@ interface ConfigGroup {
51
  /** Headline values of ok runs, chronological (latest last). */
52
  values: number[];
53
  mean: number | null;
 
 
 
 
 
54
  nErr: number;
55
  circuitTag: string;
56
  /** Representative graph: latest ok run's, else latest run's. */
@@ -73,6 +92,9 @@ function buildGroups(runs: RunRecord[]): ConfigGroup[] {
73
  const values = oks
74
  .filter((r) => r.headline_value != null)
75
  .map((r) => Math.min(1, Math.max(0, r.headline_value as number)));
 
 
 
76
  groups.push({
77
  hash,
78
  hue: hashHue(hash),
@@ -84,6 +106,7 @@ function buildGroups(runs: RunRecord[]): ConfigGroup[] {
84
  values.length > 0
85
  ? values.reduce((a, b) => a + b, 0) / values.length
86
  : null,
 
87
  nErr: sorted.filter((r) => !r.ok).length,
88
  circuitTag:
89
  latest.sample_key ?? latest.circuit_name ?? "uploaded circuit",
@@ -253,7 +276,15 @@ function PipelineStrip({
253
 
254
  // --- outcome distribution ---------------------------------------------------
255
 
256
- function OutcomeStrip({ values, hue }: { values: number[]; hue: number }) {
 
 
 
 
 
 
 
 
257
  const W = 220;
258
  const H = 26;
259
  const X0 = 8;
@@ -267,8 +298,25 @@ function OutcomeStrip({ values, hue }: { values: number[]; hue: number }) {
267
  height={H}
268
  preserveAspectRatio="xMidYMid meet"
269
  role="img"
270
- aria-label={`${values.length} replicates, mean ${(mean * 100).toFixed(1)}%`}
271
  >
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
272
  <line x1={X0} x2={X1} y1={H / 2} y2={H / 2} stroke="rgb(var(--color-edge))" strokeWidth={1} />
273
  <line x1={X0} x2={X0} y1={H / 2 - 3} y2={H / 2 + 3} stroke="rgb(var(--color-edge))" strokeWidth={1} />
274
  <line x1={X1} x2={X1} y1={H / 2 - 3} y2={H / 2 + 3} stroke="rgb(var(--color-edge))" strokeWidth={1} />
@@ -433,11 +481,26 @@ export function MultiverseBoard() {
433
  baseline != null && !isBaseline
434
  ? diffKinds(g.graph, baseline.graph)
435
  : null;
436
- const nSmall =
437
- baseline != null &&
438
- (g.values.length < 3 || baseline.values.length < 3);
439
- const delta =
440
- !isBaseline && g.mean != null && baseline?.mean != null
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
441
  ? (g.mean - baseline.mean) * 100
442
  : null;
443
  const abSelected =
@@ -486,7 +549,17 @@ export function MultiverseBoard() {
486
  {/* outcome distribution */}
487
  {g.values.length >= 2 ? (
488
  <>
489
- <OutcomeStrip values={g.values} hue={g.hue} />
 
 
 
 
 
 
 
 
 
 
490
  <div className="flex items-center gap-2 text-[10px] text-mute">
491
  <span className="tabular-nums">
492
  μ={((g.mean as number) * 100).toFixed(1)}%
@@ -495,7 +568,11 @@ export function MultiverseBoard() {
495
  {delta != null && (
496
  <span
497
  className={`tabular-nums ${delta >= 0 ? "text-ok" : "text-warn"}`}
498
- title="Difference of mean headline metric vs the baseline configuration, in percentage points."
 
 
 
 
499
  >
500
  Δ {delta >= 0 ? "+" : ""}
501
  {delta.toFixed(1)}pp vs baseline
 
24
  // * Δmean vs baseline is stated in percentage points and flagged
25
  // "(n small)" below 3 replicates on either side — a difference
26
  // built on one draw is not evidence, and the UI says so.
27
+ // * POOLED BAND (Wave J) = when ≥2 runs carry binomial payloads,
28
+ // their counts pool (Σsuccesses/Σshots, one Wilson interval — see
29
+ // lib/stats.ts for why that is valid within a configuration) into
30
+ // a filled band on the same 0-1 strip: a deliberately DIFFERENT
31
+ // mark than the per-run dots, because dots are single draws and
32
+ // the band is the interval the pooled evidence supports. The Δ
33
+ // line compares pooled means when both sides have pools.
34
 
35
  import { useEffect, useMemo, useRef, useState } from "react";
36
  import { GitCompare, RotateCcw, Workflow } from "lucide-react";
 
40
  import { resolveNodeSpec, type NodeSpec } from "../lib/nodeCatalog";
41
  import type { PluginManifest } from "../lib/api";
42
  import { hashHue, hueCss } from "../lib/hues";
43
+ import {
44
+ POOLED_SMALL_N_SHOTS,
45
+ poolEvidence,
46
+ runEvidence,
47
+ type Evidence,
48
+ type PooledEvidence,
49
+ } from "../lib/stats";
50
  import { WorkspaceToggle } from "./WorkspaceToggle";
51
  import { DemoArchiveBanner } from "./DemoArchiveBanner";
52
  import { FigureExportButton } from "./FigureExportButton";
 
65
  /** Headline values of ok runs, chronological (latest last). */
66
  values: number[];
67
  mean: number | null;
68
+ /** Wilson interval over the group's pooled binomial counts; null
69
+ * unless ≥2 ok runs carry binomial payloads (a pool of one is
70
+ * just that run's own interval — the fidelity card already shows
71
+ * it). */
72
+ pooled: PooledEvidence | null;
73
  nErr: number;
74
  circuitTag: string;
75
  /** Representative graph: latest ok run's, else latest run's. */
 
92
  const values = oks
93
  .filter((r) => r.headline_value != null)
94
  .map((r) => Math.min(1, Math.max(0, r.headline_value as number)));
95
+ const evs = oks
96
+ .map((r) => runEvidence(r.response))
97
+ .filter((e): e is Evidence => e != null);
98
  groups.push({
99
  hash,
100
  hue: hashHue(hash),
 
106
  values.length > 0
107
  ? values.reduce((a, b) => a + b, 0) / values.length
108
  : null,
109
+ pooled: evs.length >= 2 ? poolEvidence(evs) : null,
110
  nErr: sorted.filter((r) => !r.ok).length,
111
  circuitTag:
112
  latest.sample_key ?? latest.circuit_name ?? "uploaded circuit",
 
276
 
277
  // --- outcome distribution ---------------------------------------------------
278
 
279
+ function OutcomeStrip({
280
+ values,
281
+ hue,
282
+ pooled,
283
+ }: {
284
+ values: number[];
285
+ hue: number;
286
+ pooled?: PooledEvidence | null;
287
+ }) {
288
  const W = 220;
289
  const H = 26;
290
  const X0 = 8;
 
298
  height={H}
299
  preserveAspectRatio="xMidYMid meet"
300
  role="img"
301
+ aria-label={`${values.length} replicates, mean ${(mean * 100).toFixed(1)}%${pooled ? `, pooled ${(pooled.point * 100).toFixed(1)}% ±${(pooled.halfWidth * 100).toFixed(1)}pp over ${pooled.shots} shots` : ""}`}
302
  >
303
+ {/* Pooled Wilson interval (Wave J): a filled band UNDER the dot
304
+ line — a different mark than the dots on purpose (dots =
305
+ single draws, band = what the pooled counts support). */}
306
+ {pooled && (
307
+ <rect
308
+ x={px(pooled.ci95[0])}
309
+ y={H / 2 + 6}
310
+ width={Math.max(1.5, px(pooled.ci95[1]) - px(pooled.ci95[0]))}
311
+ height={4}
312
+ rx={2}
313
+ fill={hueCss(hue, 0.3)}
314
+ stroke={hueCss(hue, 0.6)}
315
+ strokeWidth={0.75}
316
+ >
317
+ <title>{`pooled 95% interval: ${(pooled.ci95[0] * 100).toFixed(1)}–${(pooled.ci95[1] * 100).toFixed(1)}% (${pooled.successes}/${pooled.shots} pooled counts over ${pooled.nRuns} runs)`}</title>
318
+ </rect>
319
+ )}
320
  <line x1={X0} x2={X1} y1={H / 2} y2={H / 2} stroke="rgb(var(--color-edge))" strokeWidth={1} />
321
  <line x1={X0} x2={X0} y1={H / 2 - 3} y2={H / 2 + 3} stroke="rgb(var(--color-edge))" strokeWidth={1} />
322
  <line x1={X1} x2={X1} y1={H / 2 - 3} y2={H / 2 + 3} stroke="rgb(var(--color-edge))" strokeWidth={1} />
 
481
  baseline != null && !isBaseline
482
  ? diffKinds(g.graph, baseline.graph)
483
  : null;
484
+ // Wave J: when BOTH sides carry pooled binomial counts,
485
+ // Δ compares POOLED means (shot-weighted, the honest
486
+ // estimator) instead of unweighted per-run means, and
487
+ // the "(n small)" suffix keys on pooled SHOTS: ≥2048 on
488
+ // both sides ⇒ worst-case Wilson half-width ≤ ±2.2pp,
489
+ // so a multi-pp Δ is signal, not shot noise (threshold
490
+ // rationale in lib/stats.ts). Without pools the old
491
+ // replicate-count heuristic stands.
492
+ const pooledBoth =
493
+ !isBaseline && g.pooled != null && baseline?.pooled != null;
494
+ const nSmall = pooledBoth
495
+ ? (g.pooled as PooledEvidence).shots < POOLED_SMALL_N_SHOTS ||
496
+ (baseline?.pooled as PooledEvidence).shots < POOLED_SMALL_N_SHOTS
497
+ : baseline != null &&
498
+ (g.values.length < 3 || baseline.values.length < 3);
499
+ const delta = pooledBoth
500
+ ? ((g.pooled as PooledEvidence).point -
501
+ (baseline?.pooled as PooledEvidence).point) *
502
+ 100
503
+ : !isBaseline && g.mean != null && baseline?.mean != null
504
  ? (g.mean - baseline.mean) * 100
505
  : null;
506
  const abSelected =
 
549
  {/* outcome distribution */}
550
  {g.values.length >= 2 ? (
551
  <>
552
+ <OutcomeStrip values={g.values} hue={g.hue} pooled={g.pooled} />
553
+ {g.pooled && (
554
+ <div
555
+ className="text-[10px] text-mute tabular-nums"
556
+ title={`All ${g.pooled.nRuns} runs' measurement counts pooled (valid within one configuration: same underlying probability), then one Wilson interval — the filled band on the strip above.`}
557
+ >
558
+ pooled μ {(g.pooled.point * 100).toFixed(1)}% ±
559
+ {(g.pooled.halfWidth * 100).toFixed(1)}pp over{" "}
560
+ {g.pooled.shots} shots
561
+ </div>
562
+ )}
563
  <div className="flex items-center gap-2 text-[10px] text-mute">
564
  <span className="tabular-nums">
565
  μ={((g.mean as number) * 100).toFixed(1)}%
 
568
  {delta != null && (
569
  <span
570
  className={`tabular-nums ${delta >= 0 ? "text-ok" : "text-warn"}`}
571
+ title={
572
+ pooledBoth
573
+ ? "Difference of POOLED means (shot-weighted, Wilson-pooled counts) vs the baseline configuration, in percentage points."
574
+ : "Difference of mean headline metric vs the baseline configuration, in percentage points."
575
+ }
576
  >
577
  Δ {delta >= 0 ? "+" : ""}
578
  {delta.toFixed(1)}pp vs baseline
frontend/src/components/RunHistory.tsx CHANGED
@@ -21,8 +21,24 @@
21
  // headline values archived up to that moment, so older strips
22
  // have fewer dots.
23
  //
24
- // Node size is deliberately constant — magnitude lives in the strip,
25
- // not the graph, so the lineage stays comparable dot-to-dot.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
  //
27
  // All list behaviors are preserved: restore / replay(pin seed) /
28
  // delete per run, compare checkboxes (max 2, wired to useApp), the
@@ -35,6 +51,7 @@ import { History, Play, RotateCcw, Trash2 } from "lucide-react";
35
  import { useApp } from "../lib/store";
36
  import { deleteRun, listRuns, type RunRecord } from "../lib/runStore";
37
  import { hashHue, hueCss } from "../lib/hues";
 
38
  import { DemoArchiveBanner } from "./DemoArchiveBanner";
39
 
40
  // --- layout constants (px) --------------------------------------------------
@@ -46,8 +63,21 @@ const STRIP_H = 20; // height of a group distribution-strip row
46
  const LANE_X0 = 13; // x of lane 0 inside the gutter
47
  const LANE_DX = 11; // horizontal distance between lanes
48
  const N_LANES = 4; // lanes cycle mod 4 — enough separation for edges to read
49
- const R_NODE = 4; // constant node radius (size is intentionally NOT a channel)
50
- const R_RING = 6.5; // pinned-seed ring radius
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  const STRIP_W = 92; // width of the 0-1 distribution mini strip
52
 
53
  function timeLabel(ts: number): string {
@@ -60,6 +90,7 @@ function timeLabel(ts: number): string {
60
 
61
  /** Multi-line native tooltip carrying the full provenance detail. */
62
  function nodeTitle(r: RunRecord): string {
 
63
  const lines = [
64
  `run ${r.run_id}`,
65
  new Date(r.created_at).toLocaleString(),
@@ -71,6 +102,9 @@ function nodeTitle(r: RunRecord): string {
71
  ? `${r.headline_label ?? "metric"} = ${(r.headline_value * 100).toFixed(2)}%`
72
  : "no headline metric",
73
  `${r.n_steps} steps · ${r.ok ? "completed" : "errored"}`,
 
 
 
74
  ];
75
  if (r.forked_from) lines.push(`forked from run ${r.forked_from}`);
76
  return lines.join("\n");
@@ -78,13 +112,18 @@ function nodeTitle(r: RunRecord): string {
78
 
79
  /** Cubic bezier from a child run down to its ancestor. Same-lane edges
80
  * bow left so they separate from the straight lane spine. */
81
- function edgePath(c: { x: number; y: number }, p: { x: number; y: number }): string {
 
 
 
 
 
82
  const dy = p.y - c.y;
83
  if (c.x === p.x) {
84
  const bow = c.x - 8;
85
- return `M ${c.x} ${c.y + R_NODE} C ${bow} ${c.y + dy * 0.3} ${bow} ${p.y - dy * 0.3} ${p.x} ${p.y - R_NODE}`;
86
  }
87
- return `M ${c.x} ${c.y + R_NODE} C ${c.x} ${c.y + dy * 0.5} ${p.x} ${p.y - dy * 0.5} ${p.x} ${p.y - R_NODE}`;
88
  }
89
 
90
  // --- layout model -------------------------------------------------------
@@ -115,6 +154,16 @@ interface Layout {
115
  /** Children whose ancestor fell outside the visible window. */
116
  stubs: { childId: string }[];
117
  spines: { x: number; y0: number; y1: number; hue: number; ids: string[] }[];
 
 
 
 
 
 
 
 
 
 
118
  parentOf: Map<string, string | null>;
119
  }
120
 
@@ -141,6 +190,12 @@ function computeLayout(records: RunRecord[]): Layout {
141
  const rows: Row[] = [];
142
  const nodeAt = new Map<string, NodePos>();
143
  const spines: Layout["spines"] = [];
 
 
 
 
 
 
144
  let y = 0;
145
 
146
  for (const sec of sections) {
@@ -179,8 +234,36 @@ function computeLayout(records: RunRecord[]): Layout {
179
  nodeAt.set(rec.run_id, { x, y: y + RUN_H / 2 });
180
  y += RUN_H;
181
  }
182
- if (sec.length >= 2)
183
  spines.push({ x, y0, y1: y - RUN_H / 2, hue, ids: sec.map((r) => r.run_id) });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
184
  }
185
 
186
  const edges: Layout["edges"] = [];
@@ -199,6 +282,8 @@ function computeLayout(records: RunRecord[]): Layout {
199
  edges,
200
  stubs,
201
  spines,
 
 
202
  parentOf: new Map(records.map((r) => [r.run_id, r.forked_from])),
203
  };
204
  }
@@ -484,12 +569,12 @@ export function RunHistory({ embedded = false }: { embedded?: boolean } = {}) {
484
  above the row hover background; pointer events off except
485
  on the node hit-targets (tooltips + hover-highlight). */}
486
  <svg
487
- className="absolute top-0 left-0"
488
  width={GUTTER_W}
489
  height={layout.totalH}
490
  style={{ pointerEvents: "none" }}
491
  role="img"
492
- aria-label="Run lineage graph: dots are runs colored by configuration, rings mark pinned seeds, curved edges link forked runs to their ancestors"
493
  >
494
  {/* replicate bands + spines (background layer) */}
495
  {layout.spines.map((s, i) => {
@@ -508,6 +593,53 @@ export function RunHistory({ embedded = false }: { embedded?: boolean } = {}) {
508
  </g>
509
  );
510
  })}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
511
  {/* fork edges: child -> ancestor, in the child's hue */}
512
  {layout.edges.map((e) => {
513
  const c = layout.nodeAt.get(e.childId);
@@ -518,7 +650,12 @@ export function RunHistory({ embedded = false }: { embedded?: boolean } = {}) {
518
  return (
519
  <path
520
  key={`edge-${e.childId}`}
521
- d={edgePath(c, p)}
 
 
 
 
 
522
  fill="none"
523
  stroke={hueCss(e.hue, 0.55)}
524
  strokeWidth={related != null && lit ? 1.8 : 1.2}
@@ -531,10 +668,11 @@ export function RunHistory({ embedded = false }: { embedded?: boolean } = {}) {
531
  {layout.stubs.map((s) => {
532
  const c = layout.nodeAt.get(s.childId);
533
  if (!c) return null;
 
534
  return (
535
  <path
536
  key={`stub-${s.childId}`}
537
- d={`M ${c.x} ${c.y + R_NODE} C ${c.x - 5} ${c.y + 8} ${c.x - 6} ${c.y + 12} ${c.x - 6} ${c.y + 16}`}
538
  fill="none"
539
  stroke="rgb(var(--color-mute))"
540
  strokeWidth={1.2}
@@ -549,28 +687,32 @@ export function RunHistory({ embedded = false }: { embedded?: boolean } = {}) {
549
  if (!pos) return null;
550
  const hue = hashHue(rec.config_hash);
551
  const dimmed = related != null && !related.has(rec.run_id);
 
 
 
 
552
  return (
553
  <g key={rec.run_id} className="transition-opacity" style={{ opacity: dimmed ? 0.2 : 1 }}>
554
  {rec.seed_mode === "pinned" && (
555
- <circle cx={pos.x} cy={pos.y} r={R_RING} fill="none" stroke={hueCss(hue, 0.9)} strokeWidth={1.3} />
556
  )}
557
  {rec.ok ? (
558
  <circle
559
  cx={pos.x}
560
  cy={pos.y}
561
- r={R_NODE}
562
  fill={hueCss(hue, 0.95)}
563
  stroke={`hsl(${hue} 60% 38%)`}
564
  strokeWidth={0.8}
565
  />
566
  ) : (
567
  <>
568
- <circle cx={pos.x} cy={pos.y} r={R_NODE} fill="none" stroke={hueCss(hue, 0.9)} strokeWidth={1.2} />
569
  <line
570
- x1={pos.x - R_NODE - 1}
571
- y1={pos.y + R_NODE + 1}
572
- x2={pos.x + R_NODE + 1}
573
- y2={pos.y - R_NODE - 1}
574
  stroke="rgb(var(--color-danger))"
575
  strokeWidth={1.3}
576
  />
@@ -580,7 +722,7 @@ export function RunHistory({ embedded = false }: { embedded?: boolean } = {}) {
580
  <circle
581
  cx={pos.x}
582
  cy={pos.y}
583
- r={R_RING + 2.5}
584
  fill="transparent"
585
  style={{ pointerEvents: "auto" }}
586
  onMouseEnter={() => enter(rec.run_id)}
@@ -597,10 +739,12 @@ export function RunHistory({ embedded = false }: { embedded?: boolean } = {}) {
597
  {/* legend: one line, doubles as the figure caption key */}
598
  <div className="px-3 py-1 border-t border-edge/60 flex flex-wrap items-center gap-x-3 gap-y-0.5 text-[9px] text-mute">
599
  <span>hue = configuration</span>
 
600
  <span>ring = pinned seed</span>
601
  <span>slash = error</span>
602
  <span>curve = forked from</span>
603
  <span>strip = replicate metrics (0–1)</span>
 
604
  </div>
605
  </>
606
  )}
 
21
  // headline values archived up to that moment, so older strips
22
  // have fewer dots.
23
  //
24
+ // * node AREA (Wave J) = evidence mass: dot area ∝ √(total shots
25
+ // the run's stochastic steps actually EXECUTED). Provenance
26
+ // usually pretends every state is equally solid; here a run IS a
27
+ // distribution, and how much evidence backs it is part of the
28
+ // record — an early-stopped run renders visibly lighter than a
29
+ // full one, so optional stopping stays legible in the timeline.
30
+ // Area (not radius) because dots read as quantities; √shots (not
31
+ // shots) so a 4096-shot run cannot visually swallow eight 512s.
32
+ // Runs with no sampled step keep the minimum radius: absence of
33
+ // evidence, not zero size.
34
+ // * group FUNNEL (Wave J) = two thin symmetric polylines around a
35
+ // replicate band's spine: at each run's row, the POOLED Wilson CI
36
+ // half-width of the group's binomial counts accumulated up to and
37
+ // including that run (oldest at the bottom, so the funnel narrows
38
+ // upward ≈ 1/√N). Same visual vocabulary as the within-run
39
+ // evidence funnel on the fidelity card — one motif, two contexts:
40
+ // shots accumulating inside a run, runs accumulating inside a
41
+ // group. Pooled numbers live in the funnel tooltip.
42
  //
43
  // All list behaviors are preserved: restore / replay(pin seed) /
44
  // delete per run, compare checkboxes (max 2, wired to useApp), the
 
51
  import { useApp } from "../lib/store";
52
  import { deleteRun, listRuns, type RunRecord } from "../lib/runStore";
53
  import { hashHue, hueCss } from "../lib/hues";
54
+ import { runEvidence, wilson95 } from "../lib/stats";
55
  import { DemoArchiveBanner } from "./DemoArchiveBanner";
56
 
57
  // --- layout constants (px) --------------------------------------------------
 
63
  const LANE_X0 = 13; // x of lane 0 inside the gutter
64
  const LANE_DX = 11; // horizontal distance between lanes
65
  const N_LANES = 4; // lanes cycle mod 4 — enough separation for edges to read
66
+ const R_MIN = 3; // node radius floor (runs with no sampled evidence)
67
+ const R_MAX = 7; // node radius cap
68
+ const SHOTS_REF = 2048; // shots that earn R_MAX = the app's default full budget
69
+ const RING_PAD = 2.5; // pinned-seed ring sits this far outside the dot
70
+ const FUNNEL_MAX_PX = 10; // widest half-width of a group certainty funnel
71
+
72
+ /** Wave J evidence mass: dot AREA ∝ √shots ⇒ radius ∝ shots^(1/4),
73
+ * against a FIXED 2048-shot reference (not view-normalized) so the
74
+ * same run keeps the same weight across sessions and figures — the
75
+ * same stability argument as the hash→hue mapping. 512 shots ≈ 5px,
76
+ * 2048 ≈ 7px; an early stop at 512 of 2048 is plainly lighter. */
77
+ function evidenceRadius(shots: number): number {
78
+ if (!(shots > 0)) return R_MIN;
79
+ return Math.max(R_MIN, Math.min(R_MAX, R_MAX * Math.pow(shots / SHOTS_REF, 0.25)));
80
+ }
81
  const STRIP_W = 92; // width of the 0-1 distribution mini strip
82
 
83
  function timeLabel(ts: number): string {
 
90
 
91
  /** Multi-line native tooltip carrying the full provenance detail. */
92
  function nodeTitle(r: RunRecord): string {
93
+ const ev = runEvidence(r.response);
94
  const lines = [
95
  `run ${r.run_id}`,
96
  new Date(r.created_at).toLocaleString(),
 
102
  ? `${r.headline_label ?? "metric"} = ${(r.headline_value * 100).toFixed(2)}%`
103
  : "no headline metric",
104
  `${r.n_steps} steps · ${r.ok ? "completed" : "errored"}`,
105
+ ev
106
+ ? `${ev.shots} shots of evidence (dot area)`
107
+ : "no sampled evidence (deterministic steps only)",
108
  ];
109
  if (r.forked_from) lines.push(`forked from run ${r.forked_from}`);
110
  return lines.join("\n");
 
112
 
113
  /** Cubic bezier from a child run down to its ancestor. Same-lane edges
114
  * bow left so they separate from the straight lane spine. */
115
+ function edgePath(
116
+ c: { x: number; y: number },
117
+ p: { x: number; y: number },
118
+ rc: number,
119
+ rp: number,
120
+ ): string {
121
  const dy = p.y - c.y;
122
  if (c.x === p.x) {
123
  const bow = c.x - 8;
124
+ return `M ${c.x} ${c.y + rc} C ${bow} ${c.y + dy * 0.3} ${bow} ${p.y - dy * 0.3} ${p.x} ${p.y - rp}`;
125
  }
126
+ return `M ${c.x} ${c.y + rc} C ${c.x} ${c.y + dy * 0.5} ${p.x} ${p.y - dy * 0.5} ${p.x} ${p.y - rp}`;
127
  }
128
 
129
  // --- layout model -------------------------------------------------------
 
154
  /** Children whose ancestor fell outside the visible window. */
155
  stubs: { childId: string }[];
156
  spines: { x: number; y0: number; y1: number; hue: number; ids: string[] }[];
157
+ /** Wave J: per-run node radius (evidence mass). */
158
+ radius: Map<string, number>;
159
+ /** Wave J: one cumulative-certainty funnel per replicate band with
160
+ * ≥2 binomial runs. `pts` run oldest (widest) → newest. */
161
+ funnels: {
162
+ x: number;
163
+ hue: number;
164
+ ids: string[];
165
+ pts: { y: number; hw: number; nRuns: number; shots: number }[];
166
+ }[];
167
  parentOf: Map<string, string | null>;
168
  }
169
 
 
190
  const rows: Row[] = [];
191
  const nodeAt = new Map<string, NodePos>();
192
  const spines: Layout["spines"] = [];
193
+ const funnels: Layout["funnels"] = [];
194
+ // Evidence mass per run, computed once (records carry full responses).
195
+ const evidence = new Map(records.map((r) => [r.run_id, runEvidence(r.response)]));
196
+ const radius = new Map(
197
+ records.map((r) => [r.run_id, evidenceRadius(evidence.get(r.run_id)?.shots ?? 0)]),
198
+ );
199
  let y = 0;
200
 
201
  for (const sec of sections) {
 
234
  nodeAt.set(rec.run_id, { x, y: y + RUN_H / 2 });
235
  y += RUN_H;
236
  }
237
+ if (sec.length >= 2) {
238
  spines.push({ x, y0, y1: y - RUN_H / 2, hue, ids: sec.map((r) => r.run_id) });
239
+ // Wave J — cumulative certainty funnel for this replicate band.
240
+ // Pooling (Σsuccesses / Σshots + one Wilson interval) is valid
241
+ // because the band holds replicates of ONE configuration — same
242
+ // circuit, same backend snapshot, same params — so every run
243
+ // draws from the same underlying success probability p; summed
244
+ // counts are the sufficient statistic (full rationale in
245
+ // lib/stats.ts). Walked oldest → newest so each row carries the
246
+ // pooled half-width of everything up to and including it.
247
+ const pts: Layout["funnels"][number]["pts"] = [];
248
+ let cSucc = 0;
249
+ let cShots = 0;
250
+ let cRuns = 0;
251
+ for (let i = sec.length - 1; i >= 0; i--) {
252
+ const ev = evidence.get(sec[i].run_id);
253
+ if (!ev) continue; // non-binomial runs neither widen nor narrow the pool
254
+ cSucc += ev.successes;
255
+ cShots += ev.shots;
256
+ cRuns += 1;
257
+ const [lo, hi] = wilson95(cSucc, cShots);
258
+ pts.push({
259
+ y: nodeAt.get(sec[i].run_id)?.y ?? 0,
260
+ hw: (hi - lo) / 2,
261
+ nRuns: cRuns,
262
+ shots: cShots,
263
+ });
264
+ }
265
+ if (pts.length >= 2) funnels.push({ x, hue, ids: sec.map((r) => r.run_id), pts });
266
+ }
267
  }
268
 
269
  const edges: Layout["edges"] = [];
 
282
  edges,
283
  stubs,
284
  spines,
285
+ radius,
286
+ funnels,
287
  parentOf: new Map(records.map((r) => [r.run_id, r.forked_from])),
288
  };
289
  }
 
569
  above the row hover background; pointer events off except
570
  on the node hit-targets (tooltips + hover-highlight). */}
571
  <svg
572
+ className="evidence-mass absolute top-0 left-0"
573
  width={GUTTER_W}
574
  height={layout.totalH}
575
  style={{ pointerEvents: "none" }}
576
  role="img"
577
+ aria-label="Run lineage graph: dots are runs colored by configuration and sized by shots of evidence, rings mark pinned seeds, curved edges link forked runs to their ancestors, funnels show pooled certainty accumulating across replicates"
578
  >
579
  {/* replicate bands + spines (background layer) */}
580
  {layout.spines.map((s, i) => {
 
593
  </g>
594
  );
595
  })}
596
+ {/* Wave J — group certainty funnels: pooled Wilson CI
597
+ half-width at each replicate row, drawn as two thin
598
+ polylines mirrored around the band spine. Normalized
599
+ per group (widest row → ±FUNNEL_MAX_PX): the task is
600
+ the SHAPE of accumulation (≈1/√N narrowing upward,
601
+ echoing the fidelity card's within-run funnel);
602
+ absolute pooled numbers live in the tooltip. */}
603
+ {layout.funnels.map((f, i) => {
604
+ const dimmed = related != null && !f.ids.some((id) => related.has(id));
605
+ const maxHw = Math.max(...f.pts.map((pt) => pt.hw));
606
+ const off = (hw: number) =>
607
+ maxHw > 0 ? (FUNNEL_MAX_PX * hw) / maxHw : 0;
608
+ const left = f.pts.map((pt) => `${f.x - off(pt.hw)},${pt.y}`);
609
+ const right = f.pts.map((pt) => `${f.x + off(pt.hw)},${pt.y}`);
610
+ const newest = f.pts[f.pts.length - 1];
611
+ return (
612
+ <g
613
+ key={`funnel-${i}`}
614
+ className="transition-opacity"
615
+ style={{ opacity: dimmed ? 0.15 : 1 }}
616
+ >
617
+ <polyline
618
+ points={left.join(" ")}
619
+ fill="none"
620
+ stroke={hueCss(f.hue, 0.6)}
621
+ strokeWidth={1}
622
+ />
623
+ <polyline
624
+ points={right.join(" ")}
625
+ fill="none"
626
+ stroke={hueCss(f.hue, 0.6)}
627
+ strokeWidth={1}
628
+ />
629
+ {/* invisible hit area carrying the pooled numbers */}
630
+ <polygon
631
+ points={[...left, ...right.slice().reverse()].join(" ")}
632
+ fill="transparent"
633
+ style={{ pointerEvents: "auto" }}
634
+ >
635
+ <title>
636
+ {`pooled ±${(newest.hw * 100).toFixed(1)}pp after ${newest.nRuns} runs / ${newest.shots} shots
637
+ cumulative Wilson CI half-width of this configuration's pooled counts, widest (oldest) row scaled to ${FUNNEL_MAX_PX}px — the funnel narrowing upward is certainty accumulating across replicates`}
638
+ </title>
639
+ </polygon>
640
+ </g>
641
+ );
642
+ })}
643
  {/* fork edges: child -> ancestor, in the child's hue */}
644
  {layout.edges.map((e) => {
645
  const c = layout.nodeAt.get(e.childId);
 
650
  return (
651
  <path
652
  key={`edge-${e.childId}`}
653
+ d={edgePath(
654
+ c,
655
+ p,
656
+ layout.radius.get(e.childId) ?? R_MIN,
657
+ layout.radius.get(e.parentId) ?? R_MIN,
658
+ )}
659
  fill="none"
660
  stroke={hueCss(e.hue, 0.55)}
661
  strokeWidth={related != null && lit ? 1.8 : 1.2}
 
668
  {layout.stubs.map((s) => {
669
  const c = layout.nodeAt.get(s.childId);
670
  if (!c) return null;
671
+ const rs = layout.radius.get(s.childId) ?? R_MIN;
672
  return (
673
  <path
674
  key={`stub-${s.childId}`}
675
+ d={`M ${c.x} ${c.y + rs} C ${c.x - 5} ${c.y + rs + 4} ${c.x - 6} ${c.y + rs + 8} ${c.x - 6} ${c.y + rs + 12}`}
676
  fill="none"
677
  stroke="rgb(var(--color-mute))"
678
  strokeWidth={1.2}
 
687
  if (!pos) return null;
688
  const hue = hashHue(rec.config_hash);
689
  const dimmed = related != null && !related.has(rec.run_id);
690
+ // Wave J: dot area = evidence mass; ring/slash/hit
691
+ // geometry all track the radius so the pinned ring,
692
+ // error slash and hover target stay legible at 3-7px.
693
+ const rad = layout.radius.get(rec.run_id) ?? R_MIN;
694
  return (
695
  <g key={rec.run_id} className="transition-opacity" style={{ opacity: dimmed ? 0.2 : 1 }}>
696
  {rec.seed_mode === "pinned" && (
697
+ <circle cx={pos.x} cy={pos.y} r={rad + RING_PAD} fill="none" stroke={hueCss(hue, 0.9)} strokeWidth={1.3} />
698
  )}
699
  {rec.ok ? (
700
  <circle
701
  cx={pos.x}
702
  cy={pos.y}
703
+ r={rad}
704
  fill={hueCss(hue, 0.95)}
705
  stroke={`hsl(${hue} 60% 38%)`}
706
  strokeWidth={0.8}
707
  />
708
  ) : (
709
  <>
710
+ <circle cx={pos.x} cy={pos.y} r={rad} fill="none" stroke={hueCss(hue, 0.9)} strokeWidth={1.2} />
711
  <line
712
+ x1={pos.x - rad - 1}
713
+ y1={pos.y + rad + 1}
714
+ x2={pos.x + rad + 1}
715
+ y2={pos.y - rad - 1}
716
  stroke="rgb(var(--color-danger))"
717
  strokeWidth={1.3}
718
  />
 
722
  <circle
723
  cx={pos.x}
724
  cy={pos.y}
725
+ r={Math.max(9, rad + RING_PAD + 2.5)}
726
  fill="transparent"
727
  style={{ pointerEvents: "auto" }}
728
  onMouseEnter={() => enter(rec.run_id)}
 
739
  {/* legend: one line, doubles as the figure caption key */}
740
  <div className="px-3 py-1 border-t border-edge/60 flex flex-wrap items-center gap-x-3 gap-y-0.5 text-[9px] text-mute">
741
  <span>hue = configuration</span>
742
+ <span>area = shots of evidence</span>
743
  <span>ring = pinned seed</span>
744
  <span>slash = error</span>
745
  <span>curve = forked from</span>
746
  <span>strip = replicate metrics (0–1)</span>
747
+ <span>funnel = pooled CI narrowing</span>
748
  </div>
749
  </>
750
  )}
frontend/src/components/results/cards.tsx CHANGED
@@ -10,6 +10,12 @@ import type { StepResult } from "../../lib/api";
10
  import { useApp } from "../../lib/store";
11
  import { listRunsByConfig } from "../../lib/runStore";
12
  import { GLOSSARY } from "../../lib/glossary";
 
 
 
 
 
 
13
  import {
14
  Caption,
15
  DepthCompare,
@@ -547,6 +553,7 @@ function ReplicateStrip({ currentPoint }: { currentPoint: number }) {
547
  const historyVersion = useApp((st) => st.historyVersion);
548
  const configHash = useApp((st) => st.lastConfigHash);
549
  const [points, setPoints] = useState<number[]>([]);
 
550
 
551
  useEffect(() => {
552
  if (!configHash) return;
@@ -559,6 +566,15 @@ function ReplicateStrip({ currentPoint }: { currentPoint: number }) {
559
  .filter((r) => r.headline_label === "fidelity" && r.headline_value != null)
560
  .map((r) => r.headline_value as number),
561
  );
 
 
 
 
 
 
 
 
 
562
  })
563
  .catch(() => {});
564
  return () => {
@@ -587,6 +603,16 @@ function ReplicateStrip({ currentPoint }: { currentPoint: number }) {
587
  />
588
  ))}
589
  </div>
 
 
 
 
 
 
 
 
 
 
590
  </div>
591
  );
592
  }
 
10
  import { useApp } from "../../lib/store";
11
  import { listRunsByConfig } from "../../lib/runStore";
12
  import { GLOSSARY } from "../../lib/glossary";
13
+ import {
14
+ poolEvidence,
15
+ runEvidence,
16
+ type Evidence,
17
+ type PooledEvidence,
18
+ } from "../../lib/stats";
19
  import {
20
  Caption,
21
  DepthCompare,
 
553
  const historyVersion = useApp((st) => st.historyVersion);
554
  const configHash = useApp((st) => st.lastConfigHash);
555
  const [points, setPoints] = useState<number[]>([]);
556
+ const [pooled, setPooled] = useState<PooledEvidence | null>(null);
557
 
558
  useEffect(() => {
559
  if (!configHash) return;
 
566
  .filter((r) => r.headline_label === "fidelity" && r.headline_value != null)
567
  .map((r) => r.headline_value as number),
568
  );
569
+ // Wave J: pool the archived replicates' binomial counts —
570
+ // valid within one configuration (same underlying p; see
571
+ // lib/stats.ts) — so the across-runs answer carries a real
572
+ // interval, not just a scatter of points.
573
+ const evs = rs
574
+ .filter((r) => r.ok)
575
+ .map((r) => runEvidence(r.response))
576
+ .filter((e): e is Evidence => e != null);
577
+ setPooled(evs.length >= 2 ? poolEvidence(evs) : null);
578
  })
579
  .catch(() => {});
580
  return () => {
 
603
  />
604
  ))}
605
  </div>
606
+ {pooled && (
607
+ <div
608
+ className="text-[10px] text-mute tabular-nums"
609
+ title={`All ${pooled.nRuns} archived replicates' measurement counts pooled (${pooled.successes}/${pooled.shots}), one Wilson interval over the pooled counts — same math as the Multiverse card's pooled band.`}
610
+ >
611
+ pooled μ {(pooled.point * 100).toFixed(1)}% ±
612
+ {(pooled.halfWidth * 100).toFixed(1)}pp over {pooled.shots} shots (
613
+ {pooled.nRuns} runs)
614
+ </div>
615
+ )}
616
  </div>
617
  );
618
  }
frontend/src/lib/scenarios.ts CHANGED
@@ -111,11 +111,14 @@ export const SCENARIOS: Record<string, Scenario> = {
111
  },
112
  // F2 — multiverse board: one card per configuration (bell fidelity
113
  // ×14, vqc+QuCAD ×3), shared-scale outcome strips, baseline chip,
114
- // Δpp vs baseline with the honesty "(n small)" tag on the vqc card.
 
 
 
115
  F2: {
116
  key: "F2",
117
  expect:
118
- "Multiverse board over the bundled archive: small multiples, baseline Δ, (n small) tag.",
119
  workspaceMode: "multiverse",
120
  needsArchive: true,
121
  },
 
111
  },
112
  // F2 — multiverse board: one card per configuration (bell fidelity
113
  // ×14, vqc+QuCAD ×3), shared-scale outcome strips, baseline chip,
114
+ // Δpp vs baseline. Since Wave J every archive card carries ≥2048
115
+ // pooled shots, so the Δ compares POOLED means and the "(n small)"
116
+ // honesty tag stays off — the pooled band + "over N shots" line say
117
+ // how much evidence backs each card instead.
118
  F2: {
119
  key: "F2",
120
  expect:
121
+ "Multiverse board over the bundled archive: small multiples, pooled bands, baseline Δ of pooled means.",
122
  workspaceMode: "multiverse",
123
  needsArchive: true,
124
  },
frontend/src/lib/stats.ts ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Frontend statistics for pooled replicate evidence (Wave J).
2
+ //
3
+ // Pooling rationale: a config_hash group holds replicates of the SAME
4
+ // configuration — same circuit, same backend snapshot, same graph
5
+ // params (that is precisely what the structural hash canonicalizes) —
6
+ // so every run's sampled-fidelity step draws from the same underlying
7
+ // success probability p. Independent binomial draws with a common p
8
+ // pool losslessly: summed successes over summed shots is the
9
+ // sufficient statistic, and ONE Wilson interval over the pooled counts
10
+ // is the tightest honest cross-run summary. Averaging per-run points
11
+ // would throw away the shot counts (a 512-shot draw would outvote its
12
+ // evidence); averaging per-run intervals is simply wrong.
13
+
14
+ import type { RunResponse } from "./api";
15
+
16
+ /** 95% Wilson score interval for a binomial proportion.
17
+ *
18
+ * Port of backend/app/services/stats.py::wilson_interval (same z,
19
+ * same [0,1] clamping); the backend additionally carries a pinned
20
+ * duplicate in qlib/qiskit_utils.py::wilson_interval_95 — see the
21
+ * layering note there (qlib must not import app.*). Wilson over the
22
+ * naive normal approximation because sampled fidelities routinely sit
23
+ * near 0 or 1, where the normal interval collapses to zero width or
24
+ * escapes [0, 1].
25
+ *
26
+ * Unit anchors (match the backend's live regression numbers):
27
+ * wilson95(238, 512) → [0.4221, 0.5081] point 0.4648, half ±0.0430
28
+ * wilson95(256, 512) → half-width ≈ 0.0431 (widest case, p = 0.5)
29
+ * wilson95(0, 0) → [0, 1] no evidence = full unknown
30
+ */
31
+ export function wilson95(successes: number, n: number): [number, number] {
32
+ const z = 1.959963984540054;
33
+ if (n <= 0) return [0, 1];
34
+ const k = Math.max(0, Math.min(Math.round(successes), Math.round(n)));
35
+ const p = k / n;
36
+ const z2 = z * z;
37
+ const denom = 1 + z2 / n;
38
+ const centre = (p + z2 / (2 * n)) / denom;
39
+ const half = (z / denom) * Math.sqrt((p * (1 - p)) / n + z2 / (4 * n * n));
40
+ return [Math.max(0, centre - half), Math.min(1, centre + half)];
41
+ }
42
+
43
+ /** Binomial evidence carried by one run: raw pooled counts. */
44
+ export interface Evidence {
45
+ successes: number;
46
+ shots: number;
47
+ }
48
+
49
+ /** Total binomial evidence a run actually EXECUTED: successes/shots
50
+ * summed over every step carrying a binomial distribution payload.
51
+ * null when the run has none (deterministic pipeline, error before
52
+ * the sampled step, pre-provenance record). `distribution.shots` is
53
+ * shots executed — not requested — so an early-stopped run weighs
54
+ * exactly the evidence it paid for. */
55
+ export function runEvidence(
56
+ response: RunResponse | null | undefined,
57
+ ): Evidence | null {
58
+ if (!response?.steps) return null;
59
+ let shots = 0;
60
+ let successes = 0;
61
+ let found = false;
62
+ for (const step of response.steps) {
63
+ const d = step.distribution as
64
+ | { kind?: unknown; shots?: unknown; successes?: unknown }
65
+ | null
66
+ | undefined;
67
+ if (
68
+ d?.kind === "binomial" &&
69
+ typeof d.shots === "number" &&
70
+ Number.isFinite(d.shots) &&
71
+ d.shots > 0 &&
72
+ typeof d.successes === "number" &&
73
+ Number.isFinite(d.successes)
74
+ ) {
75
+ shots += d.shots;
76
+ successes += d.successes;
77
+ found = true;
78
+ }
79
+ }
80
+ return found ? { successes, shots } : null;
81
+ }
82
+
83
+ export interface PooledEvidence extends Evidence {
84
+ /** How many runs contributed counts. */
85
+ nRuns: number;
86
+ /** Pooled point estimate: Σsuccesses / Σshots. */
87
+ point: number;
88
+ ci95: [number, number];
89
+ /** (hi − lo) / 2. Defined from the interval, not z·SE, because
90
+ * Wilson is asymmetric near 0 and 1. */
91
+ halfWidth: number;
92
+ }
93
+
94
+ /** Pool runs' binomial evidence (see module comment for why summing
95
+ * counts is valid within one configuration).
96
+ *
97
+ * Unit anchor: eight 512-shot runs at p ≈ 0.46 pool to 4096 shots
98
+ * with half-width ≈ ±0.0153 — the 1/√N narrowing the lineage funnel
99
+ * draws (√8 ≈ 2.8× tighter than one run's ±0.0430). */
100
+ export function poolEvidence(runs: Evidence[]): PooledEvidence | null {
101
+ if (runs.length === 0) return null;
102
+ let shots = 0;
103
+ let successes = 0;
104
+ for (const r of runs) {
105
+ shots += r.shots;
106
+ successes += r.successes;
107
+ }
108
+ if (shots <= 0) return null;
109
+ const ci95 = wilson95(successes, shots);
110
+ return {
111
+ successes,
112
+ shots,
113
+ nRuns: runs.length,
114
+ point: successes / shots,
115
+ ci95,
116
+ halfWidth: (ci95[1] - ci95[0]) / 2,
117
+ };
118
+ }
119
+
120
+ /** Pooled-shots threshold below which a Δ-vs-baseline keeps the
121
+ * "(n small)" honesty suffix. Rationale: at 2048 shots the
122
+ * worst-case (p = 0.5) Wilson half-width is ±2.2pp, so once BOTH
123
+ * sides carry ≥2048 pooled shots a multi-pp Δ is signal, not shot
124
+ * noise; 2048 is also the app's default full shot budget — "at
125
+ * least one full run's worth of evidence on each side". */
126
+ export const POOLED_SMALL_N_SHOTS = 2048;