Provenance core: run identity, replayable seeds, distribution payloads
Browse filesPhase 0 of the evidence-workbench rework. Every run now gets a
server-stamped provenance envelope (run_id, seed_mode, root_seed,
app_version) in both the eager and SSE routes; the SSE stream opens
with a run_meta event. Every run draws a root seed even when the
caller doesn't pin one, so any historical run is replayable later by
sending its recorded seed back.
Per-node seeds derive from sha256(root_seed, node_id) — independent
of execution order and of unrelated graph edits, keeping A/B
comparisons honest. Sampled fidelity accepts the seed
(seed_simulator) and reports a structured distribution payload:
binomial successes/shots, Wilson 95% CI, top-16 outcome histogram.
Cache semantics: seed-pinned runs live in a salted cache namespace
and may cache stochastic steps (reproducible by construction); fresh
runs keep today's namespace and the nondeterministic bypass.
Precomputed disk-cache responses are never served for pinned runs.
19 new unit tests (seed derivation, Wilson edges, salted namespaces,
schema backward-compat, pinned-draw reproducibility on Aer).
- backend/app/_version.py +8 -0
- backend/app/routes/workflow.py +56 -4
- backend/app/schemas.py +23 -0
- backend/app/services/stats.py +27 -0
- backend/app/services/workflow_service.py +76 -7
- backend/qlib/qiskit_utils.py +14 -1
- backend/tests/test_provenance_phase0.py +202 -0
- frontend/src/lib/api.ts +26 -0
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Single source of truth for the app's provenance version stamp.
|
| 2 |
+
|
| 3 |
+
Bumped manually at each milestone of the evidence-workbench rework so
|
| 4 |
+
that every RunResponse (and thus every stored run record) says which
|
| 5 |
+
build produced its numbers.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
APP_VERSION = "0.2.0-provenance-core"
|
|
@@ -3,10 +3,13 @@
|
|
| 3 |
from __future__ import annotations
|
| 4 |
|
| 5 |
import json
|
|
|
|
|
|
|
| 6 |
|
| 7 |
from fastapi import APIRouter, HTTPException, Request
|
| 8 |
from fastapi.responses import StreamingResponse
|
| 9 |
|
|
|
|
| 10 |
from app.config import get_settings
|
| 11 |
from app.schemas import RunRequest, RunResponse
|
| 12 |
from app.services import auth_service
|
|
@@ -47,6 +50,13 @@ def run_workflow(req: RunRequest, request: Request) -> RunResponse:
|
|
| 47 |
settings = get_settings()
|
| 48 |
effective_user_id = _effective_user_id(request, req.user_id)
|
| 49 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
# If caller requests live IBM but the server forbids it, refuse loudly
|
| 51 |
# (better UX than silently swapping in a fake backend for the whole run).
|
| 52 |
if req.use_live_ibm and not (settings.has_ibm_token and settings.allow_live_ibm):
|
|
@@ -64,11 +74,21 @@ def run_workflow(req: RunRequest, request: Request) -> RunResponse:
|
|
| 64 |
# Plugin runs also bypass the precomputed cache — the cache was built
|
| 65 |
# against built-in handlers only and has no idea what the user's
|
| 66 |
# plugin will do.
|
| 67 |
-
|
|
|
|
|
|
|
|
|
|
| 68 |
key = compute_cache_key(qc, req.nodes, req.edges, use_live_ibm=False)
|
| 69 |
cached = load_cached_response(key, circuit_id=req.circuit_id)
|
| 70 |
if cached is not None:
|
| 71 |
-
return cached
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
|
| 73 |
try:
|
| 74 |
steps = run_pipeline(
|
|
@@ -77,6 +97,8 @@ def run_workflow(req: RunRequest, request: Request) -> RunResponse:
|
|
| 77 |
edges=req.edges,
|
| 78 |
settings=settings,
|
| 79 |
user_id=effective_user_id,
|
|
|
|
|
|
|
| 80 |
)
|
| 81 |
except ValueError as exc:
|
| 82 |
# topological_order raises ValueError for cycles / bad graphs.
|
|
@@ -97,6 +119,10 @@ def run_workflow(req: RunRequest, request: Request) -> RunResponse:
|
|
| 97 |
from_cache=False,
|
| 98 |
steps=steps,
|
| 99 |
final_metrics=final_metrics,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
)
|
| 101 |
|
| 102 |
|
|
@@ -121,14 +147,38 @@ def run_workflow_stream(req: RunRequest, request: Request):
|
|
| 121 |
if req.use_live_ibm and not (settings.has_ibm_token and settings.allow_live_ibm):
|
| 122 |
raise HTTPException(status_code=403, detail="Live IBM execution is disabled.")
|
| 123 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
# Cache hit → emit all steps at once and close. Plugins bypass the
|
| 125 |
# precomputed cache (their behavior is user-specific).
|
| 126 |
-
if not req.use_live_ibm and not _uses_plugins(req.nodes):
|
| 127 |
key = compute_cache_key(qc, req.nodes, req.edges, use_live_ibm=False)
|
| 128 |
cached = load_cached_response(key, circuit_id=req.circuit_id)
|
| 129 |
if cached is not None:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
def cached_stream():
|
| 131 |
-
yield
|
|
|
|
| 132 |
yield "data: [CACHED]\n\n"
|
| 133 |
return StreamingResponse(cached_stream(), media_type="text/event-stream")
|
| 134 |
|
|
@@ -145,9 +195,11 @@ def run_workflow_stream(req: RunRequest, request: Request):
|
|
| 145 |
raise HTTPException(status_code=422, detail=str(exc)) from None
|
| 146 |
|
| 147 |
def step_stream():
|
|
|
|
| 148 |
for step in run_pipeline_stream(
|
| 149 |
circuit=qc, nodes=req.nodes, edges=req.edges,
|
| 150 |
settings=settings, user_id=effective_user_id,
|
|
|
|
| 151 |
):
|
| 152 |
yield f"data: {step.model_dump_json()}\n\n"
|
| 153 |
yield "data: [DONE]\n\n"
|
|
|
|
| 3 |
from __future__ import annotations
|
| 4 |
|
| 5 |
import json
|
| 6 |
+
import secrets
|
| 7 |
+
from uuid import uuid4
|
| 8 |
|
| 9 |
from fastapi import APIRouter, HTTPException, Request
|
| 10 |
from fastapi.responses import StreamingResponse
|
| 11 |
|
| 12 |
+
from app._version import APP_VERSION
|
| 13 |
from app.config import get_settings
|
| 14 |
from app.schemas import RunRequest, RunResponse
|
| 15 |
from app.services import auth_service
|
|
|
|
| 50 |
settings = get_settings()
|
| 51 |
effective_user_id = _effective_user_id(request, req.user_id)
|
| 52 |
|
| 53 |
+
# Provenance envelope: every run gets an id, and every run gets a
|
| 54 |
+
# root seed — drawn fresh unless the caller pinned one — so any
|
| 55 |
+
# historical run can be replayed exactly.
|
| 56 |
+
seed_pinned = req.seed is not None
|
| 57 |
+
root_seed = int(req.seed) if seed_pinned else secrets.randbelow(2**31)
|
| 58 |
+
run_id = uuid4().hex[:12]
|
| 59 |
+
|
| 60 |
# If caller requests live IBM but the server forbids it, refuse loudly
|
| 61 |
# (better UX than silently swapping in a fake backend for the whole run).
|
| 62 |
if req.use_live_ibm and not (settings.has_ibm_token and settings.allow_live_ibm):
|
|
|
|
| 74 |
# Plugin runs also bypass the precomputed cache — the cache was built
|
| 75 |
# against built-in handlers only and has no idea what the user's
|
| 76 |
# plugin will do.
|
| 77 |
+
# Seed-pinned runs bypass the precomputed cache: those responses
|
| 78 |
+
# were generated without the caller's seed and would misreport the
|
| 79 |
+
# provenance of any stochastic step.
|
| 80 |
+
if not req.use_live_ibm and not _uses_plugins(req.nodes) and not seed_pinned:
|
| 81 |
key = compute_cache_key(qc, req.nodes, req.edges, use_live_ibm=False)
|
| 82 |
cached = load_cached_response(key, circuit_id=req.circuit_id)
|
| 83 |
if cached is not None:
|
| 84 |
+
return cached.model_copy(update={
|
| 85 |
+
"run_id": run_id,
|
| 86 |
+
"seed_mode": "fresh",
|
| 87 |
+
# The cached numbers were not produced with this run's
|
| 88 |
+
# seed draw — advertising one would be provenance fraud.
|
| 89 |
+
"root_seed": None,
|
| 90 |
+
"app_version": APP_VERSION,
|
| 91 |
+
})
|
| 92 |
|
| 93 |
try:
|
| 94 |
steps = run_pipeline(
|
|
|
|
| 97 |
edges=req.edges,
|
| 98 |
settings=settings,
|
| 99 |
user_id=effective_user_id,
|
| 100 |
+
root_seed=root_seed,
|
| 101 |
+
seed_pinned=seed_pinned,
|
| 102 |
)
|
| 103 |
except ValueError as exc:
|
| 104 |
# topological_order raises ValueError for cycles / bad graphs.
|
|
|
|
| 119 |
from_cache=False,
|
| 120 |
steps=steps,
|
| 121 |
final_metrics=final_metrics,
|
| 122 |
+
run_id=run_id,
|
| 123 |
+
seed_mode="pinned" if seed_pinned else "fresh",
|
| 124 |
+
root_seed=root_seed,
|
| 125 |
+
app_version=APP_VERSION,
|
| 126 |
)
|
| 127 |
|
| 128 |
|
|
|
|
| 147 |
if req.use_live_ibm and not (settings.has_ibm_token and settings.allow_live_ibm):
|
| 148 |
raise HTTPException(status_code=403, detail="Live IBM execution is disabled.")
|
| 149 |
|
| 150 |
+
seed_pinned = req.seed is not None
|
| 151 |
+
root_seed = int(req.seed) if seed_pinned else secrets.randbelow(2**31)
|
| 152 |
+
run_id = uuid4().hex[:12]
|
| 153 |
+
|
| 154 |
+
def _meta_event(*, cached: bool) -> str:
|
| 155 |
+
payload = {
|
| 156 |
+
"run_meta": {
|
| 157 |
+
"run_id": run_id,
|
| 158 |
+
"seed_mode": "pinned" if seed_pinned else "fresh",
|
| 159 |
+
# A disk-cache hit predates this run's seed draw — its
|
| 160 |
+
# numbers were not produced with root_seed.
|
| 161 |
+
"root_seed": None if cached else root_seed,
|
| 162 |
+
"app_version": APP_VERSION,
|
| 163 |
+
}
|
| 164 |
+
}
|
| 165 |
+
return f"data: {json.dumps(payload)}\n\n"
|
| 166 |
+
|
| 167 |
# Cache hit → emit all steps at once and close. Plugins bypass the
|
| 168 |
# precomputed cache (their behavior is user-specific).
|
| 169 |
+
if not req.use_live_ibm and not _uses_plugins(req.nodes) and not seed_pinned:
|
| 170 |
key = compute_cache_key(qc, req.nodes, req.edges, use_live_ibm=False)
|
| 171 |
cached = load_cached_response(key, circuit_id=req.circuit_id)
|
| 172 |
if cached is not None:
|
| 173 |
+
enriched = cached.model_copy(update={
|
| 174 |
+
"run_id": run_id,
|
| 175 |
+
"seed_mode": "fresh",
|
| 176 |
+
"root_seed": None,
|
| 177 |
+
"app_version": APP_VERSION,
|
| 178 |
+
})
|
| 179 |
def cached_stream():
|
| 180 |
+
yield _meta_event(cached=True)
|
| 181 |
+
yield f"data: {enriched.model_dump_json()}\n\n"
|
| 182 |
yield "data: [CACHED]\n\n"
|
| 183 |
return StreamingResponse(cached_stream(), media_type="text/event-stream")
|
| 184 |
|
|
|
|
| 195 |
raise HTTPException(status_code=422, detail=str(exc)) from None
|
| 196 |
|
| 197 |
def step_stream():
|
| 198 |
+
yield _meta_event(cached=False)
|
| 199 |
for step in run_pipeline_stream(
|
| 200 |
circuit=qc, nodes=req.nodes, edges=req.edges,
|
| 201 |
settings=settings, user_id=effective_user_id,
|
| 202 |
+
root_seed=root_seed, seed_pinned=seed_pinned,
|
| 203 |
):
|
| 204 |
yield f"data: {step.model_dump_json()}\n\n"
|
| 205 |
yield "data: [DONE]\n\n"
|
|
@@ -70,6 +70,12 @@ class RunRequest(BaseModel):
|
|
| 70 |
# Anonymous browser-side UUID for per-user plugin lookup. None when
|
| 71 |
# the request uses only built-in blocks.
|
| 72 |
user_id: str | None = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
|
| 74 |
|
| 75 |
|
|
@@ -119,6 +125,16 @@ class StepResult(BaseModel):
|
|
| 119 |
# silent scientific bug. The frontend can also surface it as a
|
| 120 |
# "Live each run" chip so users know what to expect.
|
| 121 |
nondeterministic: bool = False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
|
| 123 |
|
| 124 |
class RunResponse(BaseModel):
|
|
@@ -127,6 +143,13 @@ class RunResponse(BaseModel):
|
|
| 127 |
from_cache: bool = False
|
| 128 |
steps: list[StepResult] = Field(default_factory=list)
|
| 129 |
final_metrics: dict[str, Any] = Field(default_factory=dict)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
|
| 131 |
|
| 132 |
# ---------- Backends ----------
|
|
|
|
| 70 |
# Anonymous browser-side UUID for per-user plugin lookup. None when
|
| 71 |
# the request uses only built-in blocks.
|
| 72 |
user_id: str | None = None
|
| 73 |
+
# Root seed for stochastic steps. None (default) → the server draws
|
| 74 |
+
# a fresh root seed and reports it back in the RunResponse, so ANY
|
| 75 |
+
# run can be replayed later by pinning that seed. Set → "pinned"
|
| 76 |
+
# replay mode: every stochastic step derives its per-node seed from
|
| 77 |
+
# this value and the run becomes exactly reproducible.
|
| 78 |
+
seed: int | None = Field(default=None, ge=0, lt=2**31)
|
| 79 |
|
| 80 |
|
| 81 |
|
|
|
|
| 125 |
# silent scientific bug. The frontend can also surface it as a
|
| 126 |
# "Live each run" chip so users know what to expect.
|
| 127 |
nondeterministic: bool = False
|
| 128 |
+
# Seed actually consumed by this step's stochastic computation.
|
| 129 |
+
# None for deterministic steps. Recording it even in "fresh" seed
|
| 130 |
+
# mode is what makes every historical run replayable.
|
| 131 |
+
seed_used: int | None = None
|
| 132 |
+
# Structured uncertainty payload for stochastic results. None for
|
| 133 |
+
# deterministic steps (the scalar in ``summary`` is the whole
|
| 134 |
+
# truth). Always carries "kind" and "point"; sampled fidelity emits
|
| 135 |
+
# {"kind": "binomial", "shots", "successes", "point", "ci95",
|
| 136 |
+
# "counts_top", "distinct_outcomes"}.
|
| 137 |
+
distribution: dict[str, Any] | None = None
|
| 138 |
|
| 139 |
|
| 140 |
class RunResponse(BaseModel):
|
|
|
|
| 143 |
from_cache: bool = False
|
| 144 |
steps: list[StepResult] = Field(default_factory=list)
|
| 145 |
final_metrics: dict[str, Any] = Field(default_factory=dict)
|
| 146 |
+
# ---- Provenance envelope. run_id is a server-generated opaque
|
| 147 |
+
# handle; seed_mode/root_seed let the client replay this exact run
|
| 148 |
+
# later; app_version stamps which build produced the numbers.
|
| 149 |
+
run_id: str | None = None
|
| 150 |
+
seed_mode: Literal["fresh", "pinned"] | None = None
|
| 151 |
+
root_seed: int | None = None
|
| 152 |
+
app_version: str | None = None
|
| 153 |
|
| 154 |
|
| 155 |
# ---------- Backends ----------
|
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Small, dependency-free statistics helpers shared by handlers."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import math
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def wilson_interval(
|
| 9 |
+
successes: int, n: int, z: float = 1.959963984540054,
|
| 10 |
+
) -> tuple[float, float]:
|
| 11 |
+
"""95% Wilson score interval for a binomial proportion.
|
| 12 |
+
|
| 13 |
+
Chosen over the naive normal approximation because sampled-fidelity
|
| 14 |
+
estimates routinely sit near 0 or 1 (Bell on a clean backend →
|
| 15 |
+
p ≈ 0.5, deep circuits on a noisy one → p ≈ 0.02), where the normal
|
| 16 |
+
interval collapses to zero width or escapes [0, 1]. Wilson stays
|
| 17 |
+
honest at the edges and for small shot counts.
|
| 18 |
+
"""
|
| 19 |
+
if n <= 0:
|
| 20 |
+
return (0.0, 1.0)
|
| 21 |
+
k = max(0, min(int(successes), int(n)))
|
| 22 |
+
p = k / n
|
| 23 |
+
z2 = z * z
|
| 24 |
+
denom = 1.0 + z2 / n
|
| 25 |
+
centre = (p + z2 / (2 * n)) / denom
|
| 26 |
+
half = (z / denom) * math.sqrt(p * (1 - p) / n + z2 / (4 * n * n))
|
| 27 |
+
return (max(0.0, centre - half), min(1.0, centre + half))
|
|
@@ -30,6 +30,7 @@ from qiskit import QuantumCircuit, qpy, transpile
|
|
| 30 |
from app.config import Settings, ibm_history_cache_path
|
| 31 |
from app.schemas import FlowEdge, FlowNode, StepResult
|
| 32 |
from app.services.run_cache import qpy_dump_bytes
|
|
|
|
| 33 |
|
| 34 |
logger = logging.getLogger(__name__)
|
| 35 |
|
|
@@ -71,6 +72,20 @@ def _now() -> float:
|
|
| 71 |
return time.time()
|
| 72 |
|
| 73 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
# ---- Per-node intermediate result cache --------------------------------
|
| 75 |
#
|
| 76 |
# After each step, we snapshot the StepResult + the ctx dict (shallow
|
|
@@ -87,12 +102,18 @@ _step_cache: OrderedDict[str, tuple[StepResult, dict]] = OrderedDict()
|
|
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
-
def _prefix_hash(circuit_qpy: bytes, nodes_so_far: list[FlowNode]) -> str:
|
| 91 |
"""Hash the pipeline prefix up to and including the last node in
|
| 92 |
``nodes_so_far``. Two runs with the same circuit + same node
|
| 93 |
sequence (types and params) will produce the same prefix hash at
|
| 94 |
each step, enabling cache hits for unchanged prefixes."""
|
| 95 |
h = hashlib.sha256(circuit_qpy)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
for n in nodes_so_far:
|
| 97 |
h.update(
|
| 98 |
json.dumps(
|
|
@@ -173,6 +194,8 @@ def _make_step(
|
|
| 173 |
label: str | None = None,
|
| 174 |
figures: list[dict] | None = None,
|
| 175 |
circuit_shape: dict | None = None,
|
|
|
|
|
|
|
| 176 |
) -> StepResult:
|
| 177 |
t0 = started_at if started_at is not None else _now()
|
| 178 |
return StepResult(
|
|
@@ -186,6 +209,8 @@ def _make_step(
|
|
| 186 |
message=message,
|
| 187 |
figures=figures,
|
| 188 |
circuit_shape=circuit_shape, # type: ignore[arg-type]
|
|
|
|
|
|
|
| 189 |
)
|
| 190 |
|
| 191 |
|
|
@@ -719,9 +744,11 @@ def _handle_fidelity(node: FlowNode, ctx: dict, _settings: Settings) -> StepResu
|
|
| 719 |
if method == "sampled":
|
| 720 |
backend = ctx.get("backend")
|
| 721 |
shots = int(ctx.get("shots", 1024))
|
|
|
|
| 722 |
fid, meta = sampledFidelityEstimator(
|
| 723 |
ctx["circuit"], backend, shots,
|
| 724 |
unbound_param_policy=unbound_policy,
|
|
|
|
| 725 |
)
|
| 726 |
else:
|
| 727 |
fid, meta = simpleFidelityEstimator(
|
|
@@ -745,10 +772,37 @@ def _handle_fidelity(node: FlowNode, ctx: dict, _settings: Settings) -> StepResu
|
|
| 745 |
|
| 746 |
ctx["fidelity"] = float(fid)
|
| 747 |
summary: dict = {"fidelity": float(fid), **meta}
|
| 748 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 749 |
# Sampled fidelity draws fresh shots every run — caching one draw
|
| 750 |
# and replaying it would silently lie about the noise variance.
|
| 751 |
-
#
|
|
|
|
| 752 |
if method == "sampled":
|
| 753 |
step = step.model_copy(update={"nondeterministic": True})
|
| 754 |
return step
|
|
@@ -1034,6 +1088,8 @@ def _execute_pipeline(
|
|
| 1034 |
edges: list[FlowEdge],
|
| 1035 |
settings: Settings,
|
| 1036 |
user_id: str | None,
|
|
|
|
|
|
|
| 1037 |
) -> Generator[StepResult, None, None]:
|
| 1038 |
"""Single execution loop for a pipeline graph.
|
| 1039 |
|
|
@@ -1063,10 +1119,11 @@ def _execute_pipeline(
|
|
| 1063 |
circuit_qpy = qpy_dump_bytes(circuit) # expensive; reuse across prefixes
|
| 1064 |
nodes_so_far: list[FlowNode] = []
|
| 1065 |
cache_disabled = False
|
|
|
|
| 1066 |
|
| 1067 |
for node in ordered:
|
| 1068 |
nodes_so_far.append(node)
|
| 1069 |
-
prefix_key = _prefix_hash(circuit_qpy, nodes_so_far)
|
| 1070 |
prefix_types = {n.type for n in nodes_so_far}
|
| 1071 |
|
| 1072 |
# Cache hit path. A nondeterministic cached entry MUST NEVER
|
|
@@ -1074,7 +1131,7 @@ def _execute_pipeline(
|
|
| 1074 |
# actively evicted so they can't haunt future runs).
|
| 1075 |
if not cache_disabled and prefix_key in _step_cache:
|
| 1076 |
cached_result, cached_ctx = _step_cache[prefix_key]
|
| 1077 |
-
if cached_result.nondeterministic:
|
| 1078 |
del _step_cache[prefix_key]
|
| 1079 |
_step_cache_node_types.pop(prefix_key, None)
|
| 1080 |
cache_disabled = True
|
|
@@ -1085,8 +1142,14 @@ def _execute_pipeline(
|
|
| 1085 |
yield cached_result.model_copy(update={"from_step_cache": True})
|
| 1086 |
continue
|
| 1087 |
|
| 1088 |
-
# Cache miss: actually run the node.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1089 |
result = _dispatch_one_node(node, ctx, circuit, settings, user_id)
|
|
|
|
| 1090 |
|
| 1091 |
# Stamp the post-step circuit shape onto successful results so
|
| 1092 |
# the canvas can draw data-flow labels on outgoing edges.
|
|
@@ -1098,7 +1161,7 @@ def _execute_pipeline(
|
|
| 1098 |
# Disable cache forward of the first nondeterministic step.
|
| 1099 |
# Set the flag BEFORE _cache_put so this step itself isn't
|
| 1100 |
# written — otherwise a single shot draw would get cached.
|
| 1101 |
-
if result.nondeterministic:
|
| 1102 |
cache_disabled = True
|
| 1103 |
if not cache_disabled and result.status in ("ok", "skipped"):
|
| 1104 |
_cache_put(prefix_key, result, ctx, prefix_types)
|
|
@@ -1119,11 +1182,14 @@ def run_pipeline(
|
|
| 1119 |
edges: list[FlowEdge],
|
| 1120 |
settings: Settings,
|
| 1121 |
user_id: str | None = None,
|
|
|
|
|
|
|
| 1122 |
) -> list[StepResult]:
|
| 1123 |
"""Eager wrapper: run the pipeline and collect StepResults."""
|
| 1124 |
return list(_execute_pipeline(
|
| 1125 |
circuit=circuit, nodes=nodes, edges=edges,
|
| 1126 |
settings=settings, user_id=user_id,
|
|
|
|
| 1127 |
))
|
| 1128 |
|
| 1129 |
|
|
@@ -1134,10 +1200,13 @@ def run_pipeline_stream(
|
|
| 1134 |
edges: list[FlowEdge],
|
| 1135 |
settings: Settings,
|
| 1136 |
user_id: str | None = None,
|
|
|
|
|
|
|
| 1137 |
) -> Generator[StepResult, None, None]:
|
| 1138 |
"""Streaming wrapper for the SSE route. Yields each StepResult as
|
| 1139 |
soon as it completes so the UI can show progressive output."""
|
| 1140 |
yield from _execute_pipeline(
|
| 1141 |
circuit=circuit, nodes=nodes, edges=edges,
|
| 1142 |
settings=settings, user_id=user_id,
|
|
|
|
| 1143 |
)
|
|
|
|
| 30 |
from app.config import Settings, ibm_history_cache_path
|
| 31 |
from app.schemas import FlowEdge, FlowNode, StepResult
|
| 32 |
from app.services.run_cache import qpy_dump_bytes
|
| 33 |
+
from app.services.stats import wilson_interval
|
| 34 |
|
| 35 |
logger = logging.getLogger(__name__)
|
| 36 |
|
|
|
|
| 72 |
return time.time()
|
| 73 |
|
| 74 |
|
| 75 |
+
def derive_node_seed(root_seed: int, node_id: str) -> int:
|
| 76 |
+
"""Per-node seed derived from the run's root seed and the node id.
|
| 77 |
+
|
| 78 |
+
Deterministic and independent of both execution order and the rest
|
| 79 |
+
of the graph: adding or removing an unrelated node never changes
|
| 80 |
+
this node's draw under the same root seed, which keeps A/B
|
| 81 |
+
comparisons honest (the only thing that varies is what the user
|
| 82 |
+
actually changed). 31-bit so it fits every simulator seed
|
| 83 |
+
parameter we feed it to.
|
| 84 |
+
"""
|
| 85 |
+
digest = hashlib.sha256(f"{root_seed}:{node_id}".encode()).digest()
|
| 86 |
+
return int.from_bytes(digest[:4], "big") % (2**31)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
# ---- Per-node intermediate result cache --------------------------------
|
| 90 |
#
|
| 91 |
# After each step, we snapshot the StepResult + the ctx dict (shallow
|
|
|
|
| 102 |
|
| 103 |
|
| 104 |
|
| 105 |
+
def _prefix_hash(circuit_qpy: bytes, nodes_so_far: list[FlowNode], salt: str = "") -> str:
|
| 106 |
"""Hash the pipeline prefix up to and including the last node in
|
| 107 |
``nodes_so_far``. Two runs with the same circuit + same node
|
| 108 |
sequence (types and params) will produce the same prefix hash at
|
| 109 |
each step, enabling cache hits for unchanged prefixes."""
|
| 110 |
h = hashlib.sha256(circuit_qpy)
|
| 111 |
+
if salt:
|
| 112 |
+
# Seed-pinned runs get their own cache namespace: a stochastic
|
| 113 |
+
# step's cached result is only valid for the exact seed that
|
| 114 |
+
# produced it. Unsalted (fresh) runs keep today's namespace so
|
| 115 |
+
# precomputed/prewarmed entries stay reachable.
|
| 116 |
+
h.update(salt.encode())
|
| 117 |
for n in nodes_so_far:
|
| 118 |
h.update(
|
| 119 |
json.dumps(
|
|
|
|
| 194 |
label: str | None = None,
|
| 195 |
figures: list[dict] | None = None,
|
| 196 |
circuit_shape: dict | None = None,
|
| 197 |
+
distribution: dict | None = None,
|
| 198 |
+
seed_used: int | None = None,
|
| 199 |
) -> StepResult:
|
| 200 |
t0 = started_at if started_at is not None else _now()
|
| 201 |
return StepResult(
|
|
|
|
| 209 |
message=message,
|
| 210 |
figures=figures,
|
| 211 |
circuit_shape=circuit_shape, # type: ignore[arg-type]
|
| 212 |
+
distribution=distribution,
|
| 213 |
+
seed_used=seed_used,
|
| 214 |
)
|
| 215 |
|
| 216 |
|
|
|
|
| 744 |
if method == "sampled":
|
| 745 |
backend = ctx.get("backend")
|
| 746 |
shots = int(ctx.get("shots", 1024))
|
| 747 |
+
node_seed = ctx.get("node_seed")
|
| 748 |
fid, meta = sampledFidelityEstimator(
|
| 749 |
ctx["circuit"], backend, shots,
|
| 750 |
unbound_param_policy=unbound_policy,
|
| 751 |
+
seed=node_seed,
|
| 752 |
)
|
| 753 |
else:
|
| 754 |
fid, meta = simpleFidelityEstimator(
|
|
|
|
| 772 |
|
| 773 |
ctx["fidelity"] = float(fid)
|
| 774 |
summary: dict = {"fidelity": float(fid), **meta}
|
| 775 |
+
|
| 776 |
+
distribution: dict | None = None
|
| 777 |
+
seed_used: int | None = None
|
| 778 |
+
if method == "sampled":
|
| 779 |
+
# Structured uncertainty payload: the point estimate is a
|
| 780 |
+
# binomial proportion (|0…0⟩ successes over shots), so we
|
| 781 |
+
# report a Wilson interval alongside the raw histogram
|
| 782 |
+
# material. This is what the frontend renders as a
|
| 783 |
+
# distribution instead of a bare scalar.
|
| 784 |
+
shots_n = int(meta.get("shots", 0)) or 1
|
| 785 |
+
successes = int(meta.get("observed_zero_counts", 0))
|
| 786 |
+
lo, hi = wilson_interval(successes, shots_n)
|
| 787 |
+
distribution = {
|
| 788 |
+
"kind": "binomial",
|
| 789 |
+
"shots": shots_n,
|
| 790 |
+
"successes": successes,
|
| 791 |
+
"point": float(fid),
|
| 792 |
+
"ci95": [lo, hi],
|
| 793 |
+
"counts_top": meta.get("counts_top", {}),
|
| 794 |
+
"distinct_outcomes": meta.get("distinct_outcomes"),
|
| 795 |
+
}
|
| 796 |
+
seed_used = meta.get("seed")
|
| 797 |
+
|
| 798 |
+
step = _make_step(
|
| 799 |
+
node, "ok", started_at=t0, summary=summary,
|
| 800 |
+
distribution=distribution, seed_used=seed_used,
|
| 801 |
+
)
|
| 802 |
# Sampled fidelity draws fresh shots every run — caching one draw
|
| 803 |
# and replaying it would silently lie about the noise variance.
|
| 804 |
+
# (Under a pinned seed the executor re-enables caching: the draw
|
| 805 |
+
# is then reproducible by construction.)
|
| 806 |
if method == "sampled":
|
| 807 |
step = step.model_copy(update={"nondeterministic": True})
|
| 808 |
return step
|
|
|
|
| 1088 |
edges: list[FlowEdge],
|
| 1089 |
settings: Settings,
|
| 1090 |
user_id: str | None,
|
| 1091 |
+
root_seed: int | None = None,
|
| 1092 |
+
seed_pinned: bool = False,
|
| 1093 |
) -> Generator[StepResult, None, None]:
|
| 1094 |
"""Single execution loop for a pipeline graph.
|
| 1095 |
|
|
|
|
| 1119 |
circuit_qpy = qpy_dump_bytes(circuit) # expensive; reuse across prefixes
|
| 1120 |
nodes_so_far: list[FlowNode] = []
|
| 1121 |
cache_disabled = False
|
| 1122 |
+
cache_salt = f"seed:{root_seed}" if seed_pinned else ""
|
| 1123 |
|
| 1124 |
for node in ordered:
|
| 1125 |
nodes_so_far.append(node)
|
| 1126 |
+
prefix_key = _prefix_hash(circuit_qpy, nodes_so_far, salt=cache_salt)
|
| 1127 |
prefix_types = {n.type for n in nodes_so_far}
|
| 1128 |
|
| 1129 |
# Cache hit path. A nondeterministic cached entry MUST NEVER
|
|
|
|
| 1131 |
# actively evicted so they can't haunt future runs).
|
| 1132 |
if not cache_disabled and prefix_key in _step_cache:
|
| 1133 |
cached_result, cached_ctx = _step_cache[prefix_key]
|
| 1134 |
+
if cached_result.nondeterministic and not seed_pinned:
|
| 1135 |
del _step_cache[prefix_key]
|
| 1136 |
_step_cache_node_types.pop(prefix_key, None)
|
| 1137 |
cache_disabled = True
|
|
|
|
| 1142 |
yield cached_result.model_copy(update={"from_step_cache": True})
|
| 1143 |
continue
|
| 1144 |
|
| 1145 |
+
# Cache miss: actually run the node. Stochastic handlers read
|
| 1146 |
+
# their per-node seed from ctx; it is injected just for the
|
| 1147 |
+
# dispatch and popped right after, so it never leaks into the
|
| 1148 |
+
# cached ctx snapshots.
|
| 1149 |
+
if root_seed is not None:
|
| 1150 |
+
ctx["node_seed"] = derive_node_seed(root_seed, node.id)
|
| 1151 |
result = _dispatch_one_node(node, ctx, circuit, settings, user_id)
|
| 1152 |
+
ctx.pop("node_seed", None)
|
| 1153 |
|
| 1154 |
# Stamp the post-step circuit shape onto successful results so
|
| 1155 |
# the canvas can draw data-flow labels on outgoing edges.
|
|
|
|
| 1161 |
# Disable cache forward of the first nondeterministic step.
|
| 1162 |
# Set the flag BEFORE _cache_put so this step itself isn't
|
| 1163 |
# written — otherwise a single shot draw would get cached.
|
| 1164 |
+
if result.nondeterministic and not seed_pinned:
|
| 1165 |
cache_disabled = True
|
| 1166 |
if not cache_disabled and result.status in ("ok", "skipped"):
|
| 1167 |
_cache_put(prefix_key, result, ctx, prefix_types)
|
|
|
|
| 1182 |
edges: list[FlowEdge],
|
| 1183 |
settings: Settings,
|
| 1184 |
user_id: str | None = None,
|
| 1185 |
+
root_seed: int | None = None,
|
| 1186 |
+
seed_pinned: bool = False,
|
| 1187 |
) -> list[StepResult]:
|
| 1188 |
"""Eager wrapper: run the pipeline and collect StepResults."""
|
| 1189 |
return list(_execute_pipeline(
|
| 1190 |
circuit=circuit, nodes=nodes, edges=edges,
|
| 1191 |
settings=settings, user_id=user_id,
|
| 1192 |
+
root_seed=root_seed, seed_pinned=seed_pinned,
|
| 1193 |
))
|
| 1194 |
|
| 1195 |
|
|
|
|
| 1200 |
edges: list[FlowEdge],
|
| 1201 |
settings: Settings,
|
| 1202 |
user_id: str | None = None,
|
| 1203 |
+
root_seed: int | None = None,
|
| 1204 |
+
seed_pinned: bool = False,
|
| 1205 |
) -> Generator[StepResult, None, None]:
|
| 1206 |
"""Streaming wrapper for the SSE route. Yields each StepResult as
|
| 1207 |
soon as it completes so the UI can show progressive output."""
|
| 1208 |
yield from _execute_pipeline(
|
| 1209 |
circuit=circuit, nodes=nodes, edges=edges,
|
| 1210 |
settings=settings, user_id=user_id,
|
| 1211 |
+
root_seed=root_seed, seed_pinned=seed_pinned,
|
| 1212 |
)
|
|
@@ -100,6 +100,7 @@ def sampledFidelityEstimator(
|
|
| 100 |
shots: int,
|
| 101 |
*,
|
| 102 |
unbound_param_policy: str = "bind_zero",
|
|
|
|
| 103 |
) -> tuple[float, dict]:
|
| 104 |
"""Run the circuit on ``backend`` (which carries the noise model)
|
| 105 |
with ``shots`` measurements, return the observed |0…0⟩
|
|
@@ -154,7 +155,13 @@ def sampledFidelityEstimator(
|
|
| 154 |
meta["backend_fallback"] = True
|
| 155 |
|
| 156 |
transpiled = transpile(qc, sim, optimization_level=0)
|
| 157 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
|
| 159 |
# 5. Observed |0…0⟩ probability. Qiskit reports bits as a string
|
| 160 |
# with classical-bit indexing; the all-zeros string is the
|
|
@@ -163,5 +170,11 @@ def sampledFidelityEstimator(
|
|
| 163 |
n_zero = counts.get(zero_key, 0)
|
| 164 |
fidelity = float(n_zero) / float(int(shots))
|
| 165 |
meta["observed_zero_counts"] = int(n_zero)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 166 |
logger.debug("sampledFidelityEstimator: fidelity=%.6f meta=%s", fidelity, meta)
|
| 167 |
return fidelity, meta
|
|
|
|
| 100 |
shots: int,
|
| 101 |
*,
|
| 102 |
unbound_param_policy: str = "bind_zero",
|
| 103 |
+
seed: int | None = None,
|
| 104 |
) -> tuple[float, dict]:
|
| 105 |
"""Run the circuit on ``backend`` (which carries the noise model)
|
| 106 |
with ``shots`` measurements, return the observed |0…0⟩
|
|
|
|
| 155 |
meta["backend_fallback"] = True
|
| 156 |
|
| 157 |
transpiled = transpile(qc, sim, optimization_level=0)
|
| 158 |
+
run_kwargs: dict = {"shots": int(shots)}
|
| 159 |
+
if seed is not None:
|
| 160 |
+
# Pinning the simulator seed makes this draw exactly
|
| 161 |
+
# reproducible — the backbone of "replay this historical run".
|
| 162 |
+
run_kwargs["seed_simulator"] = int(seed)
|
| 163 |
+
meta["seed"] = int(seed)
|
| 164 |
+
counts = sim.run(transpiled, **run_kwargs).result().get_counts()
|
| 165 |
|
| 166 |
# 5. Observed |0…0⟩ probability. Qiskit reports bits as a string
|
| 167 |
# with classical-bit indexing; the all-zeros string is the
|
|
|
|
| 170 |
n_zero = counts.get(zero_key, 0)
|
| 171 |
fidelity = float(n_zero) / float(int(shots))
|
| 172 |
meta["observed_zero_counts"] = int(n_zero)
|
| 173 |
+
# Compact histogram material for the frontend's distribution view:
|
| 174 |
+
# top outcomes by count (capped so the payload stays small even for
|
| 175 |
+
# wide circuits) plus how many distinct outcomes were observed.
|
| 176 |
+
top = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))[:16]
|
| 177 |
+
meta["counts_top"] = {k: int(v) for k, v in top}
|
| 178 |
+
meta["distinct_outcomes"] = len(counts)
|
| 179 |
logger.debug("sampledFidelityEstimator: fidelity=%.6f meta=%s", fidelity, meta)
|
| 180 |
return fidelity, meta
|
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Unit tests for the Phase-0 provenance core: per-node seed
|
| 2 |
+
derivation, the Wilson interval helper, seed-salted cache namespaces,
|
| 3 |
+
schema backward-compatibility, and (when qiskit-aer is importable)
|
| 4 |
+
pinned-seed reproducibility of the sampled fidelity estimator.
|
| 5 |
+
|
| 6 |
+
Runnable directly (``python3 tests/test_provenance_phase0.py`` from
|
| 7 |
+
``backend/``) or via pytest.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import sys
|
| 13 |
+
import unittest
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
ROOT = Path(__file__).resolve().parent.parent
|
| 17 |
+
if str(ROOT) not in sys.path:
|
| 18 |
+
sys.path.insert(0, str(ROOT))
|
| 19 |
+
|
| 20 |
+
from app.schemas import FlowNode, StepResult # noqa: E402
|
| 21 |
+
from app.services import workflow_service as ws # noqa: E402
|
| 22 |
+
from app.services.stats import wilson_interval # noqa: E402
|
| 23 |
+
|
| 24 |
+
try: # heavy optional dep — integration tests skip without it
|
| 25 |
+
import qiskit_aer # noqa: F401
|
| 26 |
+
HAVE_AER = True
|
| 27 |
+
except Exception:
|
| 28 |
+
HAVE_AER = False
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class DeriveNodeSeedTests(unittest.TestCase):
|
| 32 |
+
"""derive_node_seed must be stable, 31-bit, and sensitive to both
|
| 33 |
+
the root seed and the node id — but to nothing else."""
|
| 34 |
+
|
| 35 |
+
def test_stable(self) -> None:
|
| 36 |
+
self.assertEqual(
|
| 37 |
+
ws.derive_node_seed(12345, "n3"),
|
| 38 |
+
ws.derive_node_seed(12345, "n3"),
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
def test_range_31bit(self) -> None:
|
| 42 |
+
for root in (0, 1, 2**31 - 1):
|
| 43 |
+
for nid in ("n1", "fidelity-2", ""):
|
| 44 |
+
s = ws.derive_node_seed(root, nid)
|
| 45 |
+
self.assertGreaterEqual(s, 0)
|
| 46 |
+
self.assertLess(s, 2**31)
|
| 47 |
+
|
| 48 |
+
def test_sensitive_to_node_id(self) -> None:
|
| 49 |
+
self.assertNotEqual(
|
| 50 |
+
ws.derive_node_seed(7, "n1"), ws.derive_node_seed(7, "n2"),
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
def test_sensitive_to_root_seed(self) -> None:
|
| 54 |
+
self.assertNotEqual(
|
| 55 |
+
ws.derive_node_seed(7, "n1"), ws.derive_node_seed(8, "n1"),
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
def test_no_separator_collision(self) -> None:
|
| 59 |
+
# "1:23" vs "12:3" style collisions must not happen because the
|
| 60 |
+
# root seed is an int and the separator is fixed.
|
| 61 |
+
self.assertNotEqual(
|
| 62 |
+
ws.derive_node_seed(1, "23"), ws.derive_node_seed(12, "3"),
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class WilsonIntervalTests(unittest.TestCase):
|
| 67 |
+
def test_degenerate_n_zero(self) -> None:
|
| 68 |
+
self.assertEqual(wilson_interval(0, 0), (0.0, 1.0))
|
| 69 |
+
|
| 70 |
+
def test_all_failures_lower_edge(self) -> None:
|
| 71 |
+
lo, hi = wilson_interval(0, 100)
|
| 72 |
+
self.assertLess(lo, 1e-12) # 0 up to float residue
|
| 73 |
+
self.assertLess(hi, 0.05)
|
| 74 |
+
|
| 75 |
+
def test_all_successes_upper_edge(self) -> None:
|
| 76 |
+
lo, hi = wilson_interval(100, 100)
|
| 77 |
+
self.assertGreater(lo, 0.95)
|
| 78 |
+
self.assertAlmostEqual(hi, 1.0, places=6)
|
| 79 |
+
|
| 80 |
+
def test_midpoint_symmetric(self) -> None:
|
| 81 |
+
lo, hi = wilson_interval(500, 1000)
|
| 82 |
+
self.assertAlmostEqual((lo + hi) / 2, 0.5, places=6)
|
| 83 |
+
self.assertAlmostEqual(hi - lo, 0.0619, places=3)
|
| 84 |
+
|
| 85 |
+
def test_monotone_in_successes(self) -> None:
|
| 86 |
+
prev_lo = -1.0
|
| 87 |
+
for k in (0, 10, 50, 90, 100):
|
| 88 |
+
lo, _ = wilson_interval(k, 100)
|
| 89 |
+
self.assertGreaterEqual(lo, prev_lo)
|
| 90 |
+
prev_lo = lo
|
| 91 |
+
|
| 92 |
+
def test_clamps_out_of_range_successes(self) -> None:
|
| 93 |
+
self.assertEqual(wilson_interval(200, 100), wilson_interval(100, 100))
|
| 94 |
+
self.assertEqual(wilson_interval(-5, 100), wilson_interval(0, 100))
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class SeedSaltedPrefixTests(unittest.TestCase):
|
| 98 |
+
"""Seed-pinned runs must live in their own cache namespace; fresh
|
| 99 |
+
runs must keep the legacy (unsalted) one so precomputed entries
|
| 100 |
+
stay reachable."""
|
| 101 |
+
|
| 102 |
+
NODES = [FlowNode(id="n1", type="fake_backend", data={"name": "FakeFez"})]
|
| 103 |
+
|
| 104 |
+
def test_salt_changes_hash(self) -> None:
|
| 105 |
+
base = ws._prefix_hash(b"qpy", self.NODES)
|
| 106 |
+
salted = ws._prefix_hash(b"qpy", self.NODES, salt="seed:42")
|
| 107 |
+
self.assertNotEqual(base, salted)
|
| 108 |
+
|
| 109 |
+
def test_empty_salt_is_legacy(self) -> None:
|
| 110 |
+
self.assertEqual(
|
| 111 |
+
ws._prefix_hash(b"qpy", self.NODES),
|
| 112 |
+
ws._prefix_hash(b"qpy", self.NODES, salt=""),
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
def test_distinct_seeds_distinct_namespaces(self) -> None:
|
| 116 |
+
self.assertNotEqual(
|
| 117 |
+
ws._prefix_hash(b"qpy", self.NODES, salt="seed:1"),
|
| 118 |
+
ws._prefix_hash(b"qpy", self.NODES, salt="seed:2"),
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
class SchemaBackwardCompatTests(unittest.TestCase):
|
| 123 |
+
"""Old cached JSON responses (precomputed_runs/*.json) predate the
|
| 124 |
+
provenance fields; pydantic must default them, not reject them."""
|
| 125 |
+
|
| 126 |
+
LEGACY = {
|
| 127 |
+
"node_id": "n1", "node_type": "fidelity", "label": "Fidelity",
|
| 128 |
+
"status": "ok", "started_at": 1.0, "finished_at": 2.0,
|
| 129 |
+
"summary": {"fidelity": 0.5},
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
def test_legacy_step_parses(self) -> None:
|
| 133 |
+
step = StepResult.model_validate(self.LEGACY)
|
| 134 |
+
self.assertIsNone(step.seed_used)
|
| 135 |
+
self.assertIsNone(step.distribution)
|
| 136 |
+
self.assertFalse(step.nondeterministic)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
@unittest.skipUnless(HAVE_AER, "qiskit-aer not installed")
|
| 140 |
+
class SampledReproducibilityTests(unittest.TestCase):
|
| 141 |
+
"""The scientific core of Phase 0: a pinned seed makes the sampled
|
| 142 |
+
fidelity draw exactly reproducible; a fresh (None) seed leaves it
|
| 143 |
+
stochastic; the handler surfaces the distribution payload."""
|
| 144 |
+
|
| 145 |
+
def _bell(self):
|
| 146 |
+
from qiskit import QuantumCircuit
|
| 147 |
+
qc = QuantumCircuit(2)
|
| 148 |
+
qc.h(0)
|
| 149 |
+
qc.cx(0, 1)
|
| 150 |
+
return qc
|
| 151 |
+
|
| 152 |
+
def test_same_seed_same_draw(self) -> None:
|
| 153 |
+
from qlib.qiskit_utils import sampledFidelityEstimator
|
| 154 |
+
f1, m1 = sampledFidelityEstimator(self._bell(), None, 256, seed=42)
|
| 155 |
+
f2, m2 = sampledFidelityEstimator(self._bell(), None, 256, seed=42)
|
| 156 |
+
self.assertEqual(f1, f2)
|
| 157 |
+
self.assertEqual(m1["counts_top"], m2["counts_top"])
|
| 158 |
+
self.assertEqual(m1["seed"], 42)
|
| 159 |
+
|
| 160 |
+
def test_meta_carries_histogram_material(self) -> None:
|
| 161 |
+
from qlib.qiskit_utils import sampledFidelityEstimator
|
| 162 |
+
_, meta = sampledFidelityEstimator(self._bell(), None, 256, seed=7)
|
| 163 |
+
self.assertIn("counts_top", meta)
|
| 164 |
+
self.assertIn("distinct_outcomes", meta)
|
| 165 |
+
self.assertEqual(
|
| 166 |
+
sum(meta["counts_top"].values()) if meta["distinct_outcomes"] <= 16 else 256,
|
| 167 |
+
256,
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
def test_handler_distribution_payload(self) -> None:
|
| 171 |
+
# shots comes from the upstream backend node via ctx (that is
|
| 172 |
+
# where _set_backend_ctx puts it), not from the fidelity node.
|
| 173 |
+
node = FlowNode(id="f1", type="fidelity", data={"method": "sampled"})
|
| 174 |
+
ctx = {"circuit": self._bell(), "node_seed": 42, "shots": 256}
|
| 175 |
+
step = ws._handle_fidelity(node, ctx, None)
|
| 176 |
+
self.assertEqual(step.status, "ok")
|
| 177 |
+
self.assertTrue(step.nondeterministic)
|
| 178 |
+
self.assertEqual(step.seed_used, 42)
|
| 179 |
+
d = step.distribution
|
| 180 |
+
self.assertIsNotNone(d)
|
| 181 |
+
assert d is not None
|
| 182 |
+
self.assertEqual(d["kind"], "binomial")
|
| 183 |
+
self.assertEqual(d["shots"], 256)
|
| 184 |
+
lo, hi = d["ci95"]
|
| 185 |
+
self.assertLessEqual(lo, d["point"])
|
| 186 |
+
self.assertGreaterEqual(hi, d["point"])
|
| 187 |
+
# Bell |00⟩ probability is 0.5 — the CI must straddle it.
|
| 188 |
+
self.assertLess(lo, 0.62)
|
| 189 |
+
self.assertGreater(hi, 0.38)
|
| 190 |
+
|
| 191 |
+
def test_handler_statevector_stays_deterministic(self) -> None:
|
| 192 |
+
node = FlowNode(id="f2", type="fidelity", data={})
|
| 193 |
+
ctx = {"circuit": self._bell(), "node_seed": 42}
|
| 194 |
+
step = ws._handle_fidelity(node, ctx, None)
|
| 195 |
+
self.assertEqual(step.status, "ok")
|
| 196 |
+
self.assertFalse(step.nondeterministic)
|
| 197 |
+
self.assertIsNone(step.seed_used)
|
| 198 |
+
self.assertIsNone(step.distribution)
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
if __name__ == "__main__":
|
| 202 |
+
unittest.main(verbosity=2)
|
|
@@ -84,6 +84,14 @@ export interface StepResult {
|
|
| 84 |
* refuses to cache the result, and the UI can surface a small
|
| 85 |
* "Live each run" chip so users know what to expect. */
|
| 86 |
nondeterministic?: boolean;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
}
|
| 88 |
|
| 89 |
export interface RunResponse {
|
|
@@ -92,6 +100,13 @@ export interface RunResponse {
|
|
| 92 |
from_cache: boolean;
|
| 93 |
steps: StepResult[];
|
| 94 |
final_metrics: Record<string, unknown>;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
}
|
| 96 |
|
| 97 |
export interface FlowNodePayload {
|
|
@@ -122,6 +137,10 @@ export interface RunRequest {
|
|
| 122 |
* up the right user's uploaded plugins when dispatching nodes
|
| 123 |
* whose `type` isn't a built-in kind. */
|
| 124 |
user_id?: string;
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
}
|
| 126 |
|
| 127 |
/** /api/auth/status — public capability probe. The frontend uses
|
|
@@ -331,6 +350,7 @@ export const api = {
|
|
| 331 |
let buffer = "";
|
| 332 |
const steps: StepResult[] = [];
|
| 333 |
let cachedResponse: RunResponse | null = null;
|
|
|
|
| 334 |
|
| 335 |
while (true) {
|
| 336 |
const { done, value } = await reader.read();
|
|
@@ -346,6 +366,11 @@ export const api = {
|
|
| 346 |
if (payload === "[DONE]" || payload === "[CACHED]") continue;
|
| 347 |
try {
|
| 348 |
const parsed = JSON.parse(payload);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 349 |
// Cache hit sends a full RunResponse object (has .steps array)
|
| 350 |
if (Array.isArray(parsed.steps)) {
|
| 351 |
cachedResponse = parsed as RunResponse;
|
|
@@ -380,6 +405,7 @@ export const api = {
|
|
| 380 |
from_cache: false,
|
| 381 |
steps,
|
| 382 |
final_metrics: finalMetrics,
|
|
|
|
| 383 |
});
|
| 384 |
} catch (err) {
|
| 385 |
onError(err instanceof Error ? err : new Error(String(err)));
|
|
|
|
| 84 |
* refuses to cache the result, and the UI can surface a small
|
| 85 |
* "Live each run" chip so users know what to expect. */
|
| 86 |
nondeterministic?: boolean;
|
| 87 |
+
/** Seed actually consumed by this step's stochastic computation.
|
| 88 |
+
* null/absent for deterministic steps. Recorded even in "fresh"
|
| 89 |
+
* seed mode, which is what makes every historical run replayable. */
|
| 90 |
+
seed_used?: number | null;
|
| 91 |
+
/** Structured uncertainty payload for stochastic results. null for
|
| 92 |
+
* deterministic steps. Sampled fidelity: {kind: "binomial", shots,
|
| 93 |
+
* successes, point, ci95: [lo, hi], counts_top, distinct_outcomes}. */
|
| 94 |
+
distribution?: Record<string, unknown> | null;
|
| 95 |
}
|
| 96 |
|
| 97 |
export interface RunResponse {
|
|
|
|
| 100 |
from_cache: boolean;
|
| 101 |
steps: StepResult[];
|
| 102 |
final_metrics: Record<string, unknown>;
|
| 103 |
+
/** Provenance envelope (server-stamped). run_id is an opaque handle;
|
| 104 |
+
* seed_mode/root_seed let the client replay this exact run later;
|
| 105 |
+
* app_version records which build produced the numbers. */
|
| 106 |
+
run_id?: string | null;
|
| 107 |
+
seed_mode?: "fresh" | "pinned" | null;
|
| 108 |
+
root_seed?: number | null;
|
| 109 |
+
app_version?: string | null;
|
| 110 |
}
|
| 111 |
|
| 112 |
export interface FlowNodePayload {
|
|
|
|
| 137 |
* up the right user's uploaded plugins when dispatching nodes
|
| 138 |
* whose `type` isn't a built-in kind. */
|
| 139 |
user_id?: string;
|
| 140 |
+
/** Pin the run's root seed to replay a historical run exactly.
|
| 141 |
+
* Omit for a fresh draw — the server reports the drawn seed back
|
| 142 |
+
* in RunResponse.root_seed either way. */
|
| 143 |
+
seed?: number | null;
|
| 144 |
}
|
| 145 |
|
| 146 |
/** /api/auth/status — public capability probe. The frontend uses
|
|
|
|
| 350 |
let buffer = "";
|
| 351 |
const steps: StepResult[] = [];
|
| 352 |
let cachedResponse: RunResponse | null = null;
|
| 353 |
+
let runMeta: Partial<RunResponse> | null = null;
|
| 354 |
|
| 355 |
while (true) {
|
| 356 |
const { done, value } = await reader.read();
|
|
|
|
| 366 |
if (payload === "[DONE]" || payload === "[CACHED]") continue;
|
| 367 |
try {
|
| 368 |
const parsed = JSON.parse(payload);
|
| 369 |
+
// Run-level provenance envelope, sent as the first event.
|
| 370 |
+
if (parsed.run_meta) {
|
| 371 |
+
runMeta = parsed.run_meta as Partial<RunResponse>;
|
| 372 |
+
continue;
|
| 373 |
+
}
|
| 374 |
// Cache hit sends a full RunResponse object (has .steps array)
|
| 375 |
if (Array.isArray(parsed.steps)) {
|
| 376 |
cachedResponse = parsed as RunResponse;
|
|
|
|
| 405 |
from_cache: false,
|
| 406 |
steps,
|
| 407 |
final_metrics: finalMetrics,
|
| 408 |
+
...(runMeta ?? {}),
|
| 409 |
});
|
| 410 |
} catch (err) {
|
| 411 |
onError(err instanceof Error ? err : new Error(String(err)));
|