Polish pass: dedupe pipeline runners, shared chip component, emitter map
Browse filesThree concrete refactors that reduce surface area for future bugs and
make the codebase easier to maintain by hand or by LLM.
1. backend/app/services/workflow_service.py — run_pipeline and
run_pipeline_stream used to be two 100+ line copies of the same
dispatch loop. Extract a single _execute_pipeline generator and
make both functions thin wrappers (one collects into a list, the
other yields). Per-node dispatch (input / built-in / plugin /
skipped) and the post-step circuit_shape stamping are factored
into _dispatch_one_node. Plugin hydration becomes a named helper
instead of an inline block duplicated on both paths.
Also pulled out _clamp_shots and _set_backend_ctx so the two
backend handlers share their shots-clamping and ctx-writing
patterns; _cache_put's prefix_types argument becomes required
(all call sites pass it; the dead 'None means skip sidecar'
branch is gone); the run_cache.qpy_dump_bytes import moves to
the top of the file with the other module-level imports.
2. frontend/src/components/RunStatusChips.tsx — QNode and
ResultsPane both rendered cached/live chips with the same
conditional logic and similar markup; extract one component
with a 'tile' | 'card' variant. Adding a future chip (queued,
stale, dry-run, ...) is now one file.
3. frontend/src/lib/exportPython.ts — the per-node-kind switch
block was ~200 lines of repeated 'lines.push(...)' calls.
Refactor to one Emitter per kind in an EMITTERS lookup table,
so the main loop is six lines and adding a new node-kind block
is one map entry. Local asStr / asNum helpers replace the
String/Number coercion pattern that was duplicated per case.
Verified the generated script byte-for-byte against a sample
input (ry_chain + FakeFez + QuBound threshold + sampled
fidelity) and confirmed it still compiles with python3.
Net diff: -82 LOC in workflow_service.py (1221 → 1139, then minor
helpers brought it to 1143); -139 lines after counting QNode +
ResultsPane chip extraction; exportPython went from ~320 LOC of
repetitive switch to ~340 LOC of named emitters (slight LOC
increase, big drop in cyclomatic complexity).
11 unit tests still green; frontend tsc clean; generated Python
script compiles.
|
@@ -29,6 +29,7 @@ from qiskit import QuantumCircuit, qpy, transpile
|
|
| 29 |
|
| 30 |
from app.config import Settings, ibm_history_cache_path
|
| 31 |
from app.schemas import FlowEdge, FlowNode, StepResult
|
|
|
|
| 32 |
|
| 33 |
logger = logging.getLogger(__name__)
|
| 34 |
|
|
@@ -85,11 +86,6 @@ _STEP_CACHE_MAX = 200
|
|
| 85 |
_step_cache: OrderedDict[str, tuple[StepResult, dict]] = OrderedDict()
|
| 86 |
|
| 87 |
|
| 88 |
-
# Re-export under the old name so other call sites in this module
|
| 89 |
-
# don't have to change. The canonical implementation lives in
|
| 90 |
-
# run_cache so cache-hash + plugin-payload use identical bytes.
|
| 91 |
-
from app.services.run_cache import qpy_dump_bytes as _qpy_bytes_for_hash # noqa: E402
|
| 92 |
-
|
| 93 |
|
| 94 |
def _prefix_hash(circuit_qpy: bytes, nodes_so_far: list[FlowNode]) -> str:
|
| 95 |
"""Hash the pipeline prefix up to and including the last node in
|
|
@@ -142,27 +138,27 @@ def _cache_put(
|
|
| 142 |
key: str,
|
| 143 |
result: StepResult,
|
| 144 |
ctx: dict,
|
| 145 |
-
prefix_types: set[str]
|
| 146 |
) -> None:
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
snapshot
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
_step_cache[key] = (result, snapshot)
|
| 159 |
_step_cache.move_to_end(key)
|
| 160 |
-
|
| 161 |
-
# can surgically invalidate only the affected entries. None means
|
| 162 |
-
# 'caller didn't supply' — the entry is still cached but won't be
|
| 163 |
-
# invalidated by node-type lookup.
|
| 164 |
-
if prefix_types is not None:
|
| 165 |
-
_step_cache_node_types[key] = set(prefix_types)
|
| 166 |
while len(_step_cache) > _STEP_CACHE_MAX:
|
| 167 |
old_key, _ = _step_cache.popitem(last=False)
|
| 168 |
_step_cache_node_types.pop(old_key, None)
|
|
@@ -260,6 +256,30 @@ def _load_fake_backend(name: str):
|
|
| 260 |
}.get(name, FakeFez)()
|
| 261 |
|
| 262 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 263 |
# ---------- Per-node handlers ----------
|
| 264 |
|
| 265 |
def _handle_fake_backend(node: FlowNode, ctx: dict, _settings: Settings) -> StepResult:
|
|
@@ -270,9 +290,8 @@ def _handle_fake_backend(node: FlowNode, ctx: dict, _settings: Settings) -> Step
|
|
| 270 |
t0 = _now()
|
| 271 |
name_raw = node.data.get("backend_name", "FakeFez")
|
| 272 |
# Refuse empty / unknown names with a clear message instead of
|
| 273 |
-
# silently picking FakeFez
|
| 274 |
-
#
|
| 275 |
-
# FakeFez results.
|
| 276 |
if not isinstance(name_raw, str) or not name_raw:
|
| 277 |
return _make_step(
|
| 278 |
node, "error", started_at=t0,
|
|
@@ -289,21 +308,13 @@ def _handle_fake_backend(node: FlowNode, ctx: dict, _settings: Settings) -> Step
|
|
| 289 |
f"Choose one of: {', '.join(_FAKE_BACKENDS_AVAILABLE)}."
|
| 290 |
),
|
| 291 |
)
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
shots = int(shots_raw) if isinstance(shots_raw, (int, float)) else 1024
|
| 296 |
-
shots = max(1, min(shots, 65536))
|
| 297 |
-
backend = _load_fake_backend(name)
|
| 298 |
-
ctx["backend"] = backend
|
| 299 |
-
ctx["backend_is_live"] = False
|
| 300 |
-
ctx["shots"] = shots
|
| 301 |
return _make_step(
|
| 302 |
-
node,
|
| 303 |
-
"ok",
|
| 304 |
-
started_at=t0,
|
| 305 |
summary={
|
| 306 |
-
"backend_name":
|
| 307 |
"num_qubits": backend.configuration().n_qubits,
|
| 308 |
"shots": shots,
|
| 309 |
},
|
|
@@ -312,22 +323,19 @@ def _handle_fake_backend(node: FlowNode, ctx: dict, _settings: Settings) -> Step
|
|
| 312 |
|
| 313 |
def _handle_ibm_backend(node: FlowNode, ctx: dict, settings: Settings) -> StepResult:
|
| 314 |
t0 = _now()
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
|
|
|
| 318 |
if not settings.has_ibm_token or not settings.allow_live_ibm:
|
| 319 |
-
# Silently downgrade to fake so the rest of the pipeline still runs.
|
| 320 |
fallback = _load_fake_backend(node.data.get("fallback_backend", "FakeFez"))
|
| 321 |
-
ctx
|
| 322 |
-
ctx["backend_is_live"] = False
|
| 323 |
-
ctx["shots"] = shots
|
| 324 |
return _make_step(
|
| 325 |
-
node,
|
| 326 |
-
"skipped",
|
| 327 |
-
started_at=t0,
|
| 328 |
message="Live IBM call disabled; falling back to FakeFez.",
|
| 329 |
summary={"fallback": "FakeFez", "shots": shots},
|
| 330 |
)
|
|
|
|
| 331 |
# Validate the requested backend name up front. IBM's set of live
|
| 332 |
# backends is dynamic (depends on the user's plan and IBM's current
|
| 333 |
# roster), so we can't enumerate them like the fake backends. The
|
|
@@ -364,13 +372,9 @@ def _handle_ibm_backend(node: FlowNode, ctx: dict, settings: Settings) -> StepRe
|
|
| 364 |
f"{_format_exception_for_user(exc)}"
|
| 365 |
),
|
| 366 |
)
|
| 367 |
-
ctx
|
| 368 |
-
ctx["backend_is_live"] = True
|
| 369 |
-
ctx["shots"] = shots
|
| 370 |
return _make_step(
|
| 371 |
-
node,
|
| 372 |
-
"ok",
|
| 373 |
-
started_at=t0,
|
| 374 |
summary={"backend_name": name, "live": True, "shots": shots},
|
| 375 |
)
|
| 376 |
|
|
@@ -812,7 +816,7 @@ def _handle_plugin(
|
|
| 812 |
# circuit serialized to QPY.
|
| 813 |
inputs: dict = {"scalars": {}, "backend_name": None}
|
| 814 |
if "circuit" in ctx:
|
| 815 |
-
inputs["circuit_qpy_bytes"] =
|
| 816 |
if "backend" in ctx and ctx["backend"] is not None:
|
| 817 |
# The Qiskit FakeBackend objects have a `.name` attribute the
|
| 818 |
# plugin can use; live IBM backends also have one. We pass it
|
|
@@ -946,276 +950,194 @@ def topological_order(nodes: list[FlowNode], edges: list[FlowEdge]) -> list[Flow
|
|
| 946 |
|
| 947 |
# ---------- Public entry ----------
|
| 948 |
|
| 949 |
-
def
|
| 950 |
-
|
|
|
|
| 951 |
circuit: QuantumCircuit,
|
| 952 |
-
nodes: list[FlowNode],
|
| 953 |
-
edges: list[FlowEdge],
|
| 954 |
settings: Settings,
|
| 955 |
-
user_id: str | None
|
| 956 |
-
) ->
|
| 957 |
-
"""
|
| 958 |
-
|
| 959 |
-
|
| 960 |
-
|
| 961 |
-
|
| 962 |
-
|
| 963 |
-
|
| 964 |
-
|
| 965 |
-
|
| 966 |
-
|
| 967 |
-
|
| 968 |
-
|
| 969 |
-
|
| 970 |
-
|
| 971 |
-
|
| 972 |
-
|
|
|
|
|
|
|
|
|
|
| 973 |
|
| 974 |
-
|
| 975 |
-
|
| 976 |
-
|
| 977 |
-
|
| 978 |
-
|
| 979 |
-
|
| 980 |
-
|
| 981 |
-
|
| 982 |
-
|
| 983 |
-
|
| 984 |
-
|
| 985 |
-
}
|
| 986 |
-
|
| 987 |
-
)
|
| 988 |
)
|
| 989 |
-
continue
|
| 990 |
|
| 991 |
-
|
| 992 |
-
|
| 993 |
-
|
| 994 |
-
step = handler(node, ctx, settings)
|
| 995 |
-
# Snapshot the circuit's current shape onto the step.
|
| 996 |
-
# Handlers don't bother setting this themselves —
|
| 997 |
-
# they just mutate ctx, and we read it here.
|
| 998 |
-
if step.status == "ok" and "circuit" in ctx:
|
| 999 |
-
step = step.model_copy(
|
| 1000 |
-
update={"circuit_shape": _shape_of(ctx["circuit"])},
|
| 1001 |
-
)
|
| 1002 |
-
steps.append(step)
|
| 1003 |
-
# A handler that returned status="error" (e.g. QuCAD
|
| 1004 |
-
# raised "needs a backend upstream") must stop the
|
| 1005 |
-
# chain — downstream steps would otherwise execute on
|
| 1006 |
-
# whatever ctx['circuit'] the upstream handed in,
|
| 1007 |
-
# silently producing misleading results. status="skipped"
|
| 1008 |
-
# is fine to continue past (the user is told the block
|
| 1009 |
-
# didn't run, and ctx remains valid).
|
| 1010 |
-
if step.status == "error":
|
| 1011 |
-
break
|
| 1012 |
-
except Exception as exc:
|
| 1013 |
-
# Log the full traceback server-side; surface the
|
| 1014 |
-
# exception class + first line of str(exc) to the
|
| 1015 |
-
# user so they can self-diagnose without server log
|
| 1016 |
-
# access (a Space deployment has no log surface for
|
| 1017 |
-
# end users). We deliberately keep it to one line —
|
| 1018 |
-
# full tracebacks may contain file paths.
|
| 1019 |
-
logger.exception(
|
| 1020 |
-
"Built-in handler %s crashed for node %s",
|
| 1021 |
-
node.type, node.id,
|
| 1022 |
-
)
|
| 1023 |
-
detail = _format_exception_for_user(exc)
|
| 1024 |
-
steps.append(_make_step(
|
| 1025 |
-
node, "error",
|
| 1026 |
-
message=(
|
| 1027 |
-
f"The {node.type} block hit an unexpected error: {detail}"
|
| 1028 |
-
),
|
| 1029 |
-
))
|
| 1030 |
-
break
|
| 1031 |
-
continue
|
| 1032 |
|
| 1033 |
-
|
| 1034 |
-
|
| 1035 |
-
|
| 1036 |
-
|
| 1037 |
-
step = step.model_copy(
|
| 1038 |
-
update={"circuit_shape": _shape_of(ctx["circuit"])},
|
| 1039 |
-
)
|
| 1040 |
-
steps.append(step)
|
| 1041 |
-
if step.status == "error":
|
| 1042 |
-
break
|
| 1043 |
-
continue
|
| 1044 |
|
| 1045 |
-
steps.append(_make_step(
|
| 1046 |
-
node, "skipped",
|
| 1047 |
-
message=f"No handler for node type {node.type!r}",
|
| 1048 |
-
))
|
| 1049 |
|
| 1050 |
-
|
|
|
|
| 1051 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1052 |
|
| 1053 |
-
|
|
|
|
| 1054 |
*,
|
| 1055 |
circuit: QuantumCircuit,
|
| 1056 |
nodes: list[FlowNode],
|
| 1057 |
edges: list[FlowEdge],
|
| 1058 |
settings: Settings,
|
| 1059 |
-
user_id: str | None
|
| 1060 |
) -> Generator[StepResult, None, None]:
|
| 1061 |
-
"""
|
| 1062 |
-
|
| 1063 |
-
|
| 1064 |
-
|
| 1065 |
-
|
| 1066 |
-
|
| 1067 |
-
|
| 1068 |
-
|
| 1069 |
-
|
| 1070 |
-
|
| 1071 |
-
|
| 1072 |
-
|
| 1073 |
-
|
| 1074 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1075 |
"""
|
| 1076 |
ctx: dict = {"circuit": circuit}
|
| 1077 |
ordered = topological_order(nodes, edges)
|
|
|
|
| 1078 |
|
| 1079 |
-
|
| 1080 |
-
# running a pipeline on a freshly-restarted Space or on the OTHER
|
| 1081 |
-
# mirror Space would see "plugin not found" even though it sits
|
| 1082 |
-
# in their HF Datasets backing store.
|
| 1083 |
-
if user_id and any(n.type not in _HANDLERS and n.type != "input_circuit" for n in nodes):
|
| 1084 |
-
from app.services import plugin_service
|
| 1085 |
-
try:
|
| 1086 |
-
plugin_service.hydrate_from_dataset_if_needed(user_id)
|
| 1087 |
-
except Exception:
|
| 1088 |
-
logger.exception("Pre-stream plugin hydration failed for %s (continuing)", user_id)
|
| 1089 |
-
|
| 1090 |
-
# Compute the circuit's QPY hash once (expensive) — reused for
|
| 1091 |
-
# every prefix hash in this run.
|
| 1092 |
-
circuit_qpy = _qpy_bytes_for_hash(circuit)
|
| 1093 |
nodes_so_far: list[FlowNode] = []
|
| 1094 |
-
|
| 1095 |
-
# sampled fidelity), the in-memory prefix cache must stop
|
| 1096 |
-
# participating for the rest of the run. Reasons:
|
| 1097 |
-
# * THIS step's result is fresh-each-run by design; caching it
|
| 1098 |
-
# would freeze a single shot draw and replay it.
|
| 1099 |
-
# * EVERY downstream step's prefix hash would match a previous
|
| 1100 |
-
# run's, but the ctx it depends on (e.g. ctx['fidelity']) is
|
| 1101 |
-
# stale, so a lookup hit would restore a contradictory state.
|
| 1102 |
-
cache_disabled_for_tail = False
|
| 1103 |
|
| 1104 |
for node in ordered:
|
| 1105 |
nodes_so_far.append(node)
|
| 1106 |
prefix_key = _prefix_hash(circuit_qpy, nodes_so_far)
|
| 1107 |
prefix_types = {n.type for n in nodes_so_far}
|
| 1108 |
|
| 1109 |
-
#
|
| 1110 |
-
#
|
| 1111 |
-
#
|
| 1112 |
-
|
| 1113 |
-
# fix, and (b) any future handler that retroactively flips
|
| 1114 |
-
# nondeterministic on. We evict and re-execute.
|
| 1115 |
-
if not cache_disabled_for_tail and prefix_key in _step_cache:
|
| 1116 |
cached_result, cached_ctx = _step_cache[prefix_key]
|
| 1117 |
if cached_result.nondeterministic:
|
| 1118 |
-
logger.debug(
|
| 1119 |
-
"Step cache EVICT (nondet legacy) %s (%s)",
|
| 1120 |
-
node.type, prefix_key[:8],
|
| 1121 |
-
)
|
| 1122 |
del _step_cache[prefix_key]
|
| 1123 |
-
|
| 1124 |
-
|
|
|
|
| 1125 |
else:
|
| 1126 |
ctx.update(cached_ctx)
|
| 1127 |
-
_step_cache.move_to_end(prefix_key) #
|
| 1128 |
-
logger.debug("Step cache HIT for %s (%s)", node.type, prefix_key[:8])
|
| 1129 |
yield cached_result.model_copy(update={"from_step_cache": True})
|
| 1130 |
continue
|
| 1131 |
|
| 1132 |
-
#
|
| 1133 |
-
|
| 1134 |
-
|
| 1135 |
-
if node.type == "input_circuit":
|
| 1136 |
-
result = _make_step(
|
| 1137 |
-
node,
|
| 1138 |
-
"ok",
|
| 1139 |
-
summary={
|
| 1140 |
-
"num_qubits": circuit.num_qubits,
|
| 1141 |
-
"depth": circuit.depth(),
|
| 1142 |
-
"num_parameters": circuit.num_parameters,
|
| 1143 |
-
},
|
| 1144 |
-
circuit_shape=_shape_of(circuit),
|
| 1145 |
-
)
|
| 1146 |
-
if not cache_disabled_for_tail:
|
| 1147 |
-
_cache_put(prefix_key, result, ctx, prefix_types)
|
| 1148 |
-
yield result
|
| 1149 |
-
continue
|
| 1150 |
-
|
| 1151 |
-
handler = _HANDLERS.get(node.type)
|
| 1152 |
-
if handler is not None:
|
| 1153 |
-
try:
|
| 1154 |
-
result = handler(node, ctx, settings)
|
| 1155 |
-
if result.status == "ok" and "circuit" in ctx:
|
| 1156 |
-
result = result.model_copy(
|
| 1157 |
-
update={"circuit_shape": _shape_of(ctx["circuit"])},
|
| 1158 |
-
)
|
| 1159 |
-
# A nondeterministic step (e.g. sampled fidelity) trips
|
| 1160 |
-
# the sticky flag so this step itself AND any
|
| 1161 |
-
# downstream step in the same run no longer write to
|
| 1162 |
-
# the cache, AND future runs of the same prefix won't
|
| 1163 |
-
# lookup-hit a stale draw. Crucially the flag is set
|
| 1164 |
-
# BEFORE _cache_put so the nondeterministic step's
|
| 1165 |
-
# own result is also not written.
|
| 1166 |
-
if result.nondeterministic:
|
| 1167 |
-
cache_disabled_for_tail = True
|
| 1168 |
-
if not cache_disabled_for_tail:
|
| 1169 |
-
_cache_put(prefix_key, result, ctx, prefix_types)
|
| 1170 |
-
yield result
|
| 1171 |
-
# Same break-on-error policy as run_pipeline above:
|
| 1172 |
-
# status="error" stops the chain so downstream steps
|
| 1173 |
-
# don't silently execute on stale ctx.
|
| 1174 |
-
if result.status == "error":
|
| 1175 |
-
break
|
| 1176 |
-
except Exception as exc:
|
| 1177 |
-
# Same policy as run_pipeline above: log traceback +
|
| 1178 |
-
# surface the exception class + first line of message.
|
| 1179 |
-
logger.exception(
|
| 1180 |
-
"Built-in handler %s crashed (stream) for node %s",
|
| 1181 |
-
node.type, node.id,
|
| 1182 |
-
)
|
| 1183 |
-
detail = _format_exception_for_user(exc)
|
| 1184 |
-
result = _make_step(
|
| 1185 |
-
node, "error",
|
| 1186 |
-
message=(
|
| 1187 |
-
f"The {node.type} block hit an unexpected error: {detail}"
|
| 1188 |
-
),
|
| 1189 |
-
)
|
| 1190 |
-
yield result
|
| 1191 |
-
break
|
| 1192 |
-
continue
|
| 1193 |
|
| 1194 |
-
#
|
| 1195 |
-
|
| 1196 |
-
|
| 1197 |
-
|
| 1198 |
-
|
| 1199 |
-
|
| 1200 |
-
)
|
| 1201 |
-
# Flag first so a plugin marking itself nondeterministic
|
| 1202 |
-
# is treated like sampled fidelity: its own result isn't
|
| 1203 |
-
# cached, and nothing downstream is.
|
| 1204 |
-
if result.nondeterministic:
|
| 1205 |
-
cache_disabled_for_tail = True
|
| 1206 |
-
# Only cache successful plugin runs so a transient crash
|
| 1207 |
-
# doesn't get pinned to the prefix, and respect the flag.
|
| 1208 |
-
if result.status == "ok" and not cache_disabled_for_tail:
|
| 1209 |
-
_cache_put(prefix_key, result, ctx, prefix_types)
|
| 1210 |
-
yield result
|
| 1211 |
-
if result.status == "error":
|
| 1212 |
-
break
|
| 1213 |
-
continue
|
| 1214 |
|
| 1215 |
-
|
| 1216 |
-
|
| 1217 |
-
|
| 1218 |
-
|
| 1219 |
-
|
|
|
|
| 1220 |
_cache_put(prefix_key, result, ctx, prefix_types)
|
|
|
|
| 1221 |
yield result
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 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 |
|
|
|
|
| 86 |
_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
|
|
|
|
| 138 |
key: str,
|
| 139 |
result: StepResult,
|
| 140 |
ctx: dict,
|
| 141 |
+
prefix_types: set[str],
|
| 142 |
) -> None:
|
| 143 |
+
"""Store ``result`` + a snapshot of ``ctx`` under ``key``.
|
| 144 |
+
|
| 145 |
+
QuantumCircuit objects in ctx are deep-copied so that downstream
|
| 146 |
+
handlers that mutate in-place (built-ins all defensively copy
|
| 147 |
+
now, but a future plugin author may not) can't silently corrupt
|
| 148 |
+
the cached snapshot. Other ctx values (backend, floats, lists of
|
| 149 |
+
primitives) are either immutable or cheap to share by reference.
|
| 150 |
+
|
| 151 |
+
``prefix_types`` is the set of node types covered by this prefix,
|
| 152 |
+
used by :func:`invalidate_step_cache_for_node_type` to surgically
|
| 153 |
+
evict on plugin reinstall.
|
| 154 |
+
"""
|
| 155 |
+
snapshot = {
|
| 156 |
+
k: v.copy() if isinstance(v, QuantumCircuit) else v
|
| 157 |
+
for k, v in ctx.items()
|
| 158 |
+
}
|
| 159 |
_step_cache[key] = (result, snapshot)
|
| 160 |
_step_cache.move_to_end(key)
|
| 161 |
+
_step_cache_node_types[key] = set(prefix_types)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
while len(_step_cache) > _STEP_CACHE_MAX:
|
| 163 |
old_key, _ = _step_cache.popitem(last=False)
|
| 164 |
_step_cache_node_types.pop(old_key, None)
|
|
|
|
| 256 |
}.get(name, FakeFez)()
|
| 257 |
|
| 258 |
|
| 259 |
+
# ---------- Per-handler shared helpers ----------
|
| 260 |
+
|
| 261 |
+
# Allowed shot count range. 1 shot is degenerate but legitimate (single
|
| 262 |
+
# sample); 65536 is the largest power-of-two that Aer happily runs
|
| 263 |
+
# without OOM on free HF tier. Outside the range we clamp silently —
|
| 264 |
+
# the user's intent (more / fewer shots) is honoured to the extent we
|
| 265 |
+
# can serve it.
|
| 266 |
+
_MIN_SHOTS, _MAX_SHOTS = 1, 65536
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def _clamp_shots(node: FlowNode, default: int = 1024) -> int:
|
| 270 |
+
"""Read ``shots`` off a node payload and clamp to the safe range."""
|
| 271 |
+
raw = node.data.get("shots", default)
|
| 272 |
+
shots = int(raw) if isinstance(raw, (int, float)) else default
|
| 273 |
+
return max(_MIN_SHOTS, min(shots, _MAX_SHOTS))
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def _set_backend_ctx(ctx: dict, backend, *, is_live: bool, shots: int) -> None:
|
| 277 |
+
"""Standard shape for what backend-emitting handlers write to ctx."""
|
| 278 |
+
ctx["backend"] = backend
|
| 279 |
+
ctx["backend_is_live"] = is_live
|
| 280 |
+
ctx["shots"] = shots
|
| 281 |
+
|
| 282 |
+
|
| 283 |
# ---------- Per-node handlers ----------
|
| 284 |
|
| 285 |
def _handle_fake_backend(node: FlowNode, ctx: dict, _settings: Settings) -> StepResult:
|
|
|
|
| 290 |
t0 = _now()
|
| 291 |
name_raw = node.data.get("backend_name", "FakeFez")
|
| 292 |
# Refuse empty / unknown names with a clear message instead of
|
| 293 |
+
# silently picking FakeFez. Typos like "FakeBollywood" used to
|
| 294 |
+
# match FakeFez results and confuse users about why.
|
|
|
|
| 295 |
if not isinstance(name_raw, str) or not name_raw:
|
| 296 |
return _make_step(
|
| 297 |
node, "error", started_at=t0,
|
|
|
|
| 308 |
f"Choose one of: {', '.join(_FAKE_BACKENDS_AVAILABLE)}."
|
| 309 |
),
|
| 310 |
)
|
| 311 |
+
shots = _clamp_shots(node)
|
| 312 |
+
backend = _load_fake_backend(name_raw)
|
| 313 |
+
_set_backend_ctx(ctx, backend, is_live=False, shots=shots)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 314 |
return _make_step(
|
| 315 |
+
node, "ok", started_at=t0,
|
|
|
|
|
|
|
| 316 |
summary={
|
| 317 |
+
"backend_name": name_raw,
|
| 318 |
"num_qubits": backend.configuration().n_qubits,
|
| 319 |
"shots": shots,
|
| 320 |
},
|
|
|
|
| 323 |
|
| 324 |
def _handle_ibm_backend(node: FlowNode, ctx: dict, settings: Settings) -> StepResult:
|
| 325 |
t0 = _now()
|
| 326 |
+
shots = _clamp_shots(node)
|
| 327 |
+
|
| 328 |
+
# Live IBM disabled on this deployment: silently downgrade so the
|
| 329 |
+
# rest of the pipeline still runs against the named fallback fake.
|
| 330 |
if not settings.has_ibm_token or not settings.allow_live_ibm:
|
|
|
|
| 331 |
fallback = _load_fake_backend(node.data.get("fallback_backend", "FakeFez"))
|
| 332 |
+
_set_backend_ctx(ctx, fallback, is_live=False, shots=shots)
|
|
|
|
|
|
|
| 333 |
return _make_step(
|
| 334 |
+
node, "skipped", started_at=t0,
|
|
|
|
|
|
|
| 335 |
message="Live IBM call disabled; falling back to FakeFez.",
|
| 336 |
summary={"fallback": "FakeFez", "shots": shots},
|
| 337 |
)
|
| 338 |
+
|
| 339 |
# Validate the requested backend name up front. IBM's set of live
|
| 340 |
# backends is dynamic (depends on the user's plan and IBM's current
|
| 341 |
# roster), so we can't enumerate them like the fake backends. The
|
|
|
|
| 372 |
f"{_format_exception_for_user(exc)}"
|
| 373 |
),
|
| 374 |
)
|
| 375 |
+
_set_backend_ctx(ctx, backend, is_live=True, shots=shots)
|
|
|
|
|
|
|
| 376 |
return _make_step(
|
| 377 |
+
node, "ok", started_at=t0,
|
|
|
|
|
|
|
| 378 |
summary={"backend_name": name, "live": True, "shots": shots},
|
| 379 |
)
|
| 380 |
|
|
|
|
| 816 |
# circuit serialized to QPY.
|
| 817 |
inputs: dict = {"scalars": {}, "backend_name": None}
|
| 818 |
if "circuit" in ctx:
|
| 819 |
+
inputs["circuit_qpy_bytes"] = qpy_dump_bytes(ctx["circuit"])
|
| 820 |
if "backend" in ctx and ctx["backend"] is not None:
|
| 821 |
# The Qiskit FakeBackend objects have a `.name` attribute the
|
| 822 |
# plugin can use; live IBM backends also have one. We pass it
|
|
|
|
| 950 |
|
| 951 |
# ---------- Public entry ----------
|
| 952 |
|
| 953 |
+
def _dispatch_one_node(
|
| 954 |
+
node: FlowNode,
|
| 955 |
+
ctx: dict,
|
| 956 |
circuit: QuantumCircuit,
|
|
|
|
|
|
|
| 957 |
settings: Settings,
|
| 958 |
+
user_id: str | None,
|
| 959 |
+
) -> StepResult:
|
| 960 |
+
"""Compute the StepResult for a single node, with no caching.
|
| 961 |
+
|
| 962 |
+
This is the only place that knows how to map a ``node.type`` to an
|
| 963 |
+
executor — built-in handlers, the user-plugin dispatcher, or the
|
| 964 |
+
'no handler found' skip. Exceptions from built-in handlers are
|
| 965 |
+
caught and surfaced through ``_format_exception_for_user``;
|
| 966 |
+
handlers that fail by *returning* status='error' (the common path
|
| 967 |
+
for input-validation failures) flow through unmodified.
|
| 968 |
+
"""
|
| 969 |
+
if node.type == "input_circuit":
|
| 970 |
+
return _make_step(
|
| 971 |
+
node, "ok",
|
| 972 |
+
summary={
|
| 973 |
+
"num_qubits": circuit.num_qubits,
|
| 974 |
+
"depth": circuit.depth(),
|
| 975 |
+
"num_parameters": circuit.num_parameters,
|
| 976 |
+
},
|
| 977 |
+
circuit_shape=_shape_of(circuit),
|
| 978 |
+
)
|
| 979 |
|
| 980 |
+
handler = _HANDLERS.get(node.type)
|
| 981 |
+
if handler is not None:
|
| 982 |
+
try:
|
| 983 |
+
return handler(node, ctx, settings)
|
| 984 |
+
except Exception as exc:
|
| 985 |
+
logger.exception(
|
| 986 |
+
"Built-in handler %s crashed for node %s", node.type, node.id,
|
| 987 |
+
)
|
| 988 |
+
return _make_step(
|
| 989 |
+
node, "error",
|
| 990 |
+
message=(
|
| 991 |
+
f"The {node.type} block hit an unexpected error: "
|
| 992 |
+
f"{_format_exception_for_user(exc)}"
|
| 993 |
+
),
|
| 994 |
)
|
|
|
|
| 995 |
|
| 996 |
+
# Not a built-in — try the user-plugin path if we have a user.
|
| 997 |
+
if user_id:
|
| 998 |
+
return _handle_plugin(node, ctx, settings, user_id=user_id)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 999 |
|
| 1000 |
+
return _make_step(
|
| 1001 |
+
node, "skipped",
|
| 1002 |
+
message=f"No handler for node type {node.type!r}",
|
| 1003 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1004 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1005 |
|
| 1006 |
+
def _hydrate_user_plugins_if_needed(nodes: list[FlowNode], user_id: str | None) -> None:
|
| 1007 |
+
"""Make sure the user's plugins are on disk before dispatch.
|
| 1008 |
|
| 1009 |
+
On a freshly-restarted HF Space (or the mirror Space) an
|
| 1010 |
+
authenticated user's plugins live only in HF Datasets until the
|
| 1011 |
+
first reference, so a pipeline that uses them would otherwise hit
|
| 1012 |
+
'plugin not found'. Cheap when nothing to hydrate. Failure is
|
| 1013 |
+
logged but non-fatal — dispatch continues and the missing plugin
|
| 1014 |
+
surfaces as a regular step error.
|
| 1015 |
+
"""
|
| 1016 |
+
if not user_id:
|
| 1017 |
+
return
|
| 1018 |
+
has_user_plugin = any(
|
| 1019 |
+
n.type not in _HANDLERS and n.type != "input_circuit" for n in nodes
|
| 1020 |
+
)
|
| 1021 |
+
if not has_user_plugin:
|
| 1022 |
+
return
|
| 1023 |
+
from app.services import plugin_service # local: avoid import cycle
|
| 1024 |
+
try:
|
| 1025 |
+
plugin_service.hydrate_from_dataset_if_needed(user_id)
|
| 1026 |
+
except Exception:
|
| 1027 |
+
logger.exception("Plugin hydration failed for %s (continuing)", user_id)
|
| 1028 |
|
| 1029 |
+
|
| 1030 |
+
def _execute_pipeline(
|
| 1031 |
*,
|
| 1032 |
circuit: QuantumCircuit,
|
| 1033 |
nodes: list[FlowNode],
|
| 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 |
+
|
| 1040 |
+
Both :func:`run_pipeline` (eager list) and
|
| 1041 |
+
:func:`run_pipeline_stream` (SSE generator) delegate here. This
|
| 1042 |
+
function:
|
| 1043 |
+
|
| 1044 |
+
* dispatches each node via :func:`_dispatch_one_node`,
|
| 1045 |
+
* stamps the post-step ``circuit_shape`` onto successful results
|
| 1046 |
+
(handlers don't bother — they just mutate ctx),
|
| 1047 |
+
* participates in the in-memory prefix cache,
|
| 1048 |
+
* obeys the sticky 'cache disabled' rule that the first
|
| 1049 |
+
:attr:`StepResult.nondeterministic` step trips for the rest of
|
| 1050 |
+
the run — both this step and every downstream step bypass
|
| 1051 |
+
cache lookup AND put, because caching a single shot draw and
|
| 1052 |
+
replaying it (or restoring a stale ctx that depended on one)
|
| 1053 |
+
is a silent scientific bug,
|
| 1054 |
+
* stops on ``status == 'error'`` so downstream steps don't run
|
| 1055 |
+
on inconsistent ctx,
|
| 1056 |
+
* caches only ``ok`` / ``skipped`` results — error results are
|
| 1057 |
+
often transient and shouldn't pin the prefix.
|
| 1058 |
"""
|
| 1059 |
ctx: dict = {"circuit": circuit}
|
| 1060 |
ordered = topological_order(nodes, edges)
|
| 1061 |
+
_hydrate_user_plugins_if_needed(nodes, user_id)
|
| 1062 |
|
| 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
|
| 1073 |
+
# be served (legacy entries from before this rule existed are
|
| 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
|
| 1081 |
+
# Fall through to re-execute.
|
| 1082 |
else:
|
| 1083 |
ctx.update(cached_ctx)
|
| 1084 |
+
_step_cache.move_to_end(prefix_key) # LRU refresh
|
|
|
|
| 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.
|
| 1093 |
+
if result.status == "ok" and "circuit" in ctx:
|
| 1094 |
+
result = result.model_copy(
|
| 1095 |
+
update={"circuit_shape": _shape_of(ctx["circuit"])},
|
| 1096 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1097 |
|
| 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)
|
| 1105 |
+
|
| 1106 |
yield result
|
| 1107 |
+
|
| 1108 |
+
# Error stops the chain — downstream steps would silently run
|
| 1109 |
+
# on the previous handler's stale ctx and report misleading
|
| 1110 |
+
# numbers. (skipped does NOT stop; ctx is still valid.)
|
| 1111 |
+
if result.status == "error":
|
| 1112 |
+
break
|
| 1113 |
+
|
| 1114 |
+
|
| 1115 |
+
def run_pipeline(
|
| 1116 |
+
*,
|
| 1117 |
+
circuit: QuantumCircuit,
|
| 1118 |
+
nodes: list[FlowNode],
|
| 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 |
+
|
| 1130 |
+
def run_pipeline_stream(
|
| 1131 |
+
*,
|
| 1132 |
+
circuit: QuantumCircuit,
|
| 1133 |
+
nodes: list[FlowNode],
|
| 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 |
+
)
|
|
@@ -14,6 +14,7 @@ import {
|
|
| 14 |
type PluginNodeSpec,
|
| 15 |
} from "../lib/nodeCatalog";
|
| 16 |
import { NodeParamEditor } from "./NodeParamEditor";
|
|
|
|
| 17 |
import { TipIcon } from "./TipIcon";
|
| 18 |
import { useApp } from "../lib/store";
|
| 19 |
import { FAMILY_HINTS } from "../lib/familyHints";
|
|
@@ -355,22 +356,7 @@ function RunResultStrip({
|
|
| 355 |
<div className="flex-1 text-[10px] text-ok/80">✓ ran</div>
|
| 356 |
)}
|
| 357 |
<div className="flex items-center gap-1 shrink-0">
|
| 358 |
-
{step
|
| 359 |
-
<span
|
| 360 |
-
className="text-[9px] px-1 py-0.5 rounded border border-accent/30 text-accent"
|
| 361 |
-
title="Served from per-node cache (pipeline prefix unchanged)"
|
| 362 |
-
>
|
| 363 |
-
cached
|
| 364 |
-
</span>
|
| 365 |
-
)}
|
| 366 |
-
{step.nondeterministic && !step.from_step_cache && (
|
| 367 |
-
<span
|
| 368 |
-
className="text-[9px] px-1 py-0.5 rounded border border-warn/30 text-warn"
|
| 369 |
-
title="Result is intentionally fresh each run (e.g. sampled shots). The per-node cache is bypassed for this step and every downstream step."
|
| 370 |
-
>
|
| 371 |
-
live
|
| 372 |
-
</span>
|
| 373 |
-
)}
|
| 374 |
{durationS !== null && (
|
| 375 |
<span
|
| 376 |
className={`text-[9px] px-1 py-0.5 rounded border font-mono ${durBadgeClass}`}
|
|
|
|
| 14 |
type PluginNodeSpec,
|
| 15 |
} from "../lib/nodeCatalog";
|
| 16 |
import { NodeParamEditor } from "./NodeParamEditor";
|
| 17 |
+
import { RunStatusChips } from "./RunStatusChips";
|
| 18 |
import { TipIcon } from "./TipIcon";
|
| 19 |
import { useApp } from "../lib/store";
|
| 20 |
import { FAMILY_HINTS } from "../lib/familyHints";
|
|
|
|
| 356 |
<div className="flex-1 text-[10px] text-ok/80">✓ ran</div>
|
| 357 |
)}
|
| 358 |
<div className="flex items-center gap-1 shrink-0">
|
| 359 |
+
<RunStatusChips step={step} variant="tile" />
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 360 |
{durationS !== null && (
|
| 361 |
<span
|
| 362 |
className={`text-[9px] px-1 py-0.5 rounded border font-mono ${durBadgeClass}`}
|
|
@@ -21,6 +21,7 @@ import {
|
|
| 21 |
} from "lucide-react";
|
| 22 |
import { StepBody } from "./results/cards";
|
| 23 |
import { PluginFigures } from "./PluginFigures";
|
|
|
|
| 24 |
|
| 25 |
export function ResultsPane({ onCollapse }: { onCollapse?: () => void } = {}) {
|
| 26 |
const run = useApp((s) => s.run);
|
|
@@ -175,19 +176,7 @@ function StepCard({ step }: { step: StepResult }) {
|
|
| 175 |
<span className={`chip ${statusClass}`}>
|
| 176 |
{statusIcon} {step.status}
|
| 177 |
</span>
|
| 178 |
-
{step
|
| 179 |
-
<span className="chip !border-accent/30 !text-accent text-[9px]">
|
| 180 |
-
cached
|
| 181 |
-
</span>
|
| 182 |
-
)}
|
| 183 |
-
{step.nondeterministic && !step.from_step_cache && (
|
| 184 |
-
<span
|
| 185 |
-
className="chip !border-warn/30 !text-warn text-[9px]"
|
| 186 |
-
title="Fresh each run — the per-node cache is bypassed for this step and everything downstream."
|
| 187 |
-
>
|
| 188 |
-
live
|
| 189 |
-
</span>
|
| 190 |
-
)}
|
| 191 |
</div>
|
| 192 |
<div className="text-[11px] text-mute">
|
| 193 |
{dur.toFixed(2)}s · node <span className="font-mono">{step.node_id}</span>
|
|
|
|
| 21 |
} from "lucide-react";
|
| 22 |
import { StepBody } from "./results/cards";
|
| 23 |
import { PluginFigures } from "./PluginFigures";
|
| 24 |
+
import { RunStatusChips } from "./RunStatusChips";
|
| 25 |
|
| 26 |
export function ResultsPane({ onCollapse }: { onCollapse?: () => void } = {}) {
|
| 27 |
const run = useApp((s) => s.run);
|
|
|
|
| 176 |
<span className={`chip ${statusClass}`}>
|
| 177 |
{statusIcon} {step.status}
|
| 178 |
</span>
|
| 179 |
+
<RunStatusChips step={step} variant="card" />
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
</div>
|
| 181 |
<div className="text-[11px] text-mute">
|
| 182 |
{dur.toFixed(2)}s · node <span className="font-mono">{step.node_id}</span>
|
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { StepResult } from "../lib/api";
|
| 2 |
+
|
| 3 |
+
/**
|
| 4 |
+
* The pair of contextual chips a step can carry beyond its status:
|
| 5 |
+
* * "cached" — served from the per-node prefix cache (pipeline
|
| 6 |
+
* prefix unchanged since the last run).
|
| 7 |
+
* * "live" — intentionally nondeterministic (e.g. sampled
|
| 8 |
+
* fidelity with N shots). The cache is bypassed for this step
|
| 9 |
+
* and everything downstream so the user gets a fresh shot draw
|
| 10 |
+
* each run.
|
| 11 |
+
*
|
| 12 |
+
* Two visual variants:
|
| 13 |
+
* * `tile` — compact 9px text + tight padding for the canvas tile
|
| 14 |
+
* (QNode's result strip).
|
| 15 |
+
* * `card` — the global `.chip` pill used in the right pane card
|
| 16 |
+
* (ResultsPane's step header).
|
| 17 |
+
*
|
| 18 |
+
* cached and live are mutually exclusive in practice (a cache hit
|
| 19 |
+
* can't also be flagged nondeterministic, since we never write
|
| 20 |
+
* nondeterministic results into the cache), so we render at most one.
|
| 21 |
+
*/
|
| 22 |
+
export function RunStatusChips({
|
| 23 |
+
step,
|
| 24 |
+
variant,
|
| 25 |
+
}: {
|
| 26 |
+
step: StepResult;
|
| 27 |
+
variant: "tile" | "card";
|
| 28 |
+
}) {
|
| 29 |
+
const isTile = variant === "tile";
|
| 30 |
+
const cachedClass = isTile
|
| 31 |
+
? "text-[9px] px-1 py-0.5 rounded border border-accent/30 text-accent"
|
| 32 |
+
: "chip !border-accent/30 !text-accent text-[9px]";
|
| 33 |
+
const liveClass = isTile
|
| 34 |
+
? "text-[9px] px-1 py-0.5 rounded border border-warn/30 text-warn"
|
| 35 |
+
: "chip !border-warn/30 !text-warn text-[9px]";
|
| 36 |
+
|
| 37 |
+
if (step.from_step_cache) {
|
| 38 |
+
return (
|
| 39 |
+
<span
|
| 40 |
+
className={cachedClass}
|
| 41 |
+
title="Served from per-node cache (pipeline prefix unchanged)"
|
| 42 |
+
>
|
| 43 |
+
cached
|
| 44 |
+
</span>
|
| 45 |
+
);
|
| 46 |
+
}
|
| 47 |
+
if (step.nondeterministic) {
|
| 48 |
+
return (
|
| 49 |
+
<span
|
| 50 |
+
className={liveClass}
|
| 51 |
+
title="Result is intentionally fresh each run (e.g. sampled shots). The per-node cache is bypassed for this step and every downstream step."
|
| 52 |
+
>
|
| 53 |
+
live
|
| 54 |
+
</span>
|
| 55 |
+
);
|
| 56 |
+
}
|
| 57 |
+
return null;
|
| 58 |
+
}
|
|
@@ -9,6 +9,12 @@
|
|
| 9 |
* We deliberately keep the generated code flat and readable (no
|
| 10 |
* classes, no abstractions) so someone unfamiliar with the codebase
|
| 11 |
* can follow it line by line.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
*/
|
| 13 |
|
| 14 |
import type { Node, Edge } from "@xyflow/react";
|
|
@@ -20,9 +26,18 @@ interface PipelineNode {
|
|
| 20 |
params: Record<string, unknown>;
|
| 21 |
}
|
| 22 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
/**
|
| 24 |
* Topological sort of canvas nodes using the edge list.
|
| 25 |
-
* Falls back to catalog
|
| 26 |
*/
|
| 27 |
function topoSort(nodes: Node[], edges: Edge[]): Node[] {
|
| 28 |
const adj = new Map<string, string[]>();
|
|
@@ -54,6 +69,225 @@ function topoSort(nodes: Node[], edges: Edge[]): Node[] {
|
|
| 54 |
return order.map((id) => byId.get(id)!).filter(Boolean);
|
| 55 |
}
|
| 56 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
export function generatePythonScript(
|
| 58 |
nodes: Node[],
|
| 59 |
edges: Edge[],
|
|
@@ -66,7 +300,6 @@ export function generatePythonScript(
|
|
| 66 |
}));
|
| 67 |
|
| 68 |
const lines: string[] = [];
|
| 69 |
-
const imports = new Set<string>();
|
| 70 |
|
| 71 |
// Header
|
| 72 |
lines.push(`"""`);
|
|
@@ -75,243 +308,31 @@ export function generatePythonScript(
|
|
| 75 |
lines.push(`"""`);
|
| 76 |
lines.push(``);
|
| 77 |
|
| 78 |
-
//
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
if (b.kind === "fake_backend" || b.kind === "ibm_backend") {
|
| 86 |
-
hasBackend = true;
|
| 87 |
-
}
|
| 88 |
-
}
|
| 89 |
-
|
| 90 |
-
// Imports section
|
| 91 |
if (hasBackend) {
|
| 92 |
imports.add("from qiskit_aer import AerSimulator");
|
| 93 |
imports.add("from qiskit_aer.noise import NoiseModel");
|
| 94 |
}
|
| 95 |
-
|
| 96 |
lines.push([...imports].sort().join("\n"));
|
| 97 |
lines.push(``);
|
| 98 |
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
stepNum+
|
| 103 |
-
const
|
|
|
|
| 104 |
lines.push(sep);
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
if (sampleKey) {
|
| 110 |
-
lines.push(`# Sample: ${sampleKey}`);
|
| 111 |
-
lines.push(`# Option A: Load from a .qpy file`);
|
| 112 |
-
lines.push(`# from qiskit import qpy`);
|
| 113 |
-
lines.push(`# with open("${sampleKey}.qpy", "rb") as f:`);
|
| 114 |
-
lines.push(`# qc = qpy.load(f)[0]`);
|
| 115 |
-
lines.push(``);
|
| 116 |
-
lines.push(`# Option B: Build programmatically (replace with your circuit)`);
|
| 117 |
-
} else {
|
| 118 |
-
lines.push(`# Replace with your circuit`);
|
| 119 |
-
}
|
| 120 |
-
lines.push(`qc = QuantumCircuit(4, name="my_circuit")`);
|
| 121 |
-
lines.push(`# qc.ry(0.5, 0)`);
|
| 122 |
-
lines.push(`# qc.cx(0, 1)`);
|
| 123 |
-
lines.push(`# ... add your gates here`);
|
| 124 |
-
lines.push(``);
|
| 125 |
-
break;
|
| 126 |
-
}
|
| 127 |
-
|
| 128 |
-
case "fake_backend": {
|
| 129 |
-
const name = String(b.params.backend_name ?? "FakeFez");
|
| 130 |
-
const shots = Number(b.params.shots ?? 1024);
|
| 131 |
-
lines.push(`# Step ${stepNum}: Noisy simulator (${name})`);
|
| 132 |
-
lines.push(`from qiskit.providers.fake_provider import ${name}V2`);
|
| 133 |
-
lines.push(`backend = ${name}V2()`);
|
| 134 |
-
lines.push(`noise_model = NoiseModel.from_backend(backend)`);
|
| 135 |
-
lines.push(`shots = ${shots} # user-set measurement count`);
|
| 136 |
-
lines.push(``);
|
| 137 |
-
break;
|
| 138 |
-
}
|
| 139 |
-
|
| 140 |
-
case "ibm_backend": {
|
| 141 |
-
const name = String(b.params.backend_name ?? "ibm_fez");
|
| 142 |
-
const shots = Number(b.params.shots ?? 1024);
|
| 143 |
-
lines.push(`# Step ${stepNum}: IBM live backend (${name})`);
|
| 144 |
-
lines.push(`# Requires: pip install qiskit-ibm-runtime`);
|
| 145 |
-
lines.push(`# from qiskit_ibm_runtime import QiskitRuntimeService`);
|
| 146 |
-
lines.push(`# service = QiskitRuntimeService(channel="ibm_quantum", token="YOUR_TOKEN")`);
|
| 147 |
-
lines.push(`# backend = service.backend("${name}")`);
|
| 148 |
-
lines.push(`# noise_model = NoiseModel.from_backend(backend)`);
|
| 149 |
-
lines.push(`#`);
|
| 150 |
-
lines.push(`# For now, falling back to fake backend:`);
|
| 151 |
-
lines.push(`from qiskit.providers.fake_provider import FakeFezV2`);
|
| 152 |
-
lines.push(`backend = FakeFezV2()`);
|
| 153 |
-
lines.push(`noise_model = NoiseModel.from_backend(backend)`);
|
| 154 |
-
lines.push(`shots = ${shots}`);
|
| 155 |
-
lines.push(``);
|
| 156 |
-
break;
|
| 157 |
-
}
|
| 158 |
-
|
| 159 |
-
case "qucad": {
|
| 160 |
-
const iters = Number(b.params.iterations ?? 3);
|
| 161 |
-
const lam = Number(b.params.lam ?? 0.005);
|
| 162 |
-
const rho = Number(b.params.rho ?? 500.0);
|
| 163 |
-
lines.push(`# Step ${stepNum}: QuCAD — noise-aware VQC sparsification`);
|
| 164 |
-
lines.push(`from qlib.qucad import run_qucad_training_noisy`);
|
| 165 |
-
lines.push(``);
|
| 166 |
-
lines.push(`# Bind free parameters to zero if circuit is parameterized`);
|
| 167 |
-
lines.push(`if qc.num_parameters > 0:`);
|
| 168 |
-
lines.push(` qc_bound = qc.assign_parameters([0.0] * qc.num_parameters)`);
|
| 169 |
-
lines.push(`else:`);
|
| 170 |
-
lines.push(` qc_bound = qc`);
|
| 171 |
-
lines.push(``);
|
| 172 |
-
lines.push(`theta, mask, history = run_qucad_training_noisy(`);
|
| 173 |
-
lines.push(` qc, noise_model, backend,`);
|
| 174 |
-
lines.push(` iterations=${iters}, lam=${lam}, rho=${rho},`);
|
| 175 |
-
lines.push(`)`);
|
| 176 |
-
lines.push(`qc = qc.assign_parameters(theta * (mask != 0))`);
|
| 177 |
-
lines.push(`print(f"QuCAD: kept {int((mask != 0).sum())}/{len(mask)} parameters")`);
|
| 178 |
-
lines.push(``);
|
| 179 |
-
break;
|
| 180 |
-
}
|
| 181 |
-
|
| 182 |
-
case "qubound": {
|
| 183 |
-
const cacheBackend = String(b.params.cache_backend ?? "ibm_fez");
|
| 184 |
-
const thresholdRaw = Number(b.params.threshold ?? 0);
|
| 185 |
-
// 0 / negative disables pass/fail, matching the backend's
|
| 186 |
-
// _build_summary contract.
|
| 187 |
-
const threshold = thresholdRaw > 0 ? thresholdRaw : null;
|
| 188 |
-
lines.push(`# Step ${stepNum}: QuBound — LSTM error-bound prediction`);
|
| 189 |
-
lines.push(`from qlib.qbound import call_QuBound_from_cache`);
|
| 190 |
-
lines.push(`from pathlib import Path`);
|
| 191 |
-
lines.push(``);
|
| 192 |
-
lines.push(`cache_path = Path("cache/ibm_history/${cacheBackend}.pkl")`);
|
| 193 |
-
lines.push(`if qc.num_parameters > 0:`);
|
| 194 |
-
lines.push(` qc_eval = qc.assign_parameters([0.0] * qc.num_parameters)`);
|
| 195 |
-
lines.push(`else:`);
|
| 196 |
-
lines.push(` qc_eval = qc`);
|
| 197 |
-
lines.push(``);
|
| 198 |
-
lines.push(`bound, model, meta = call_QuBound_from_cache(`);
|
| 199 |
-
lines.push(` qc_eval, cache_path, reference_backend=backend if 'backend' in dir() else None,`);
|
| 200 |
-
lines.push(`)`);
|
| 201 |
-
lines.push(`print(f"QuBound predicted error bound: {bound:.6f}")`);
|
| 202 |
-
if (threshold !== null) {
|
| 203 |
-
lines.push(`threshold = ${threshold}`);
|
| 204 |
-
lines.push(`passes = bound <= threshold`);
|
| 205 |
-
lines.push(`margin = threshold - bound`);
|
| 206 |
-
lines.push(
|
| 207 |
-
`print(f" threshold {threshold}: {'PASS' if passes else 'FAIL'} (margin {margin:+.4f})")`,
|
| 208 |
-
);
|
| 209 |
-
}
|
| 210 |
-
lines.push(``);
|
| 211 |
-
break;
|
| 212 |
-
}
|
| 213 |
-
|
| 214 |
-
case "compvqc": {
|
| 215 |
-
lines.push(`# Step ${stepNum}: CompressVQC — fold redundant gates`);
|
| 216 |
-
lines.push(`from qlib.compvqc import get_LUT, quadraticProgram_luttoqp, admmOptimizedCompVQC, resultsCompressVQC`);
|
| 217 |
-
lines.push(``);
|
| 218 |
-
lines.push(`if qc.num_parameters > 0:`);
|
| 219 |
-
lines.push(` comp_backend = backend if 'backend' in dir() else None`);
|
| 220 |
-
lines.push(` if comp_backend is None:`);
|
| 221 |
-
lines.push(` from qiskit.providers.fake_provider import FakeFezV2`);
|
| 222 |
-
lines.push(` comp_backend = FakeFezV2()`);
|
| 223 |
-
lines.push(` lut = get_LUT(qc, comp_backend)`);
|
| 224 |
-
lines.push(` if lut:`);
|
| 225 |
-
lines.push(` qp = quadraticProgram_luttoqp(qc, lut)`);
|
| 226 |
-
lines.push(` result = admmOptimizedCompVQC(qp)`);
|
| 227 |
-
lines.push(` qc = resultsCompressVQC(result, qc)`);
|
| 228 |
-
lines.push(` print(f"CompressVQC: compressed circuit depth {qc.depth()}")`);
|
| 229 |
-
lines.push(` else:`);
|
| 230 |
-
lines.push(` print("CompressVQC: no compressible pairs found")`);
|
| 231 |
-
lines.push(`else:`);
|
| 232 |
-
lines.push(` print("CompressVQC: skipped (no parameterized gates)")`);
|
| 233 |
-
lines.push(``);
|
| 234 |
-
break;
|
| 235 |
-
}
|
| 236 |
-
|
| 237 |
-
case "qshot": {
|
| 238 |
-
const snapshot = String(b.params.noise_snapshot ?? "pittsburgh_1");
|
| 239 |
-
const alpha = Number(b.params.alpha ?? 0.95);
|
| 240 |
-
lines.push(`# Step ${stepNum}: Qshot — noise-aware shot-count recommendation`);
|
| 241 |
-
lines.push(`from qlib.qshot import get_recommender, resolve_noise_snapshot`);
|
| 242 |
-
lines.push(``);
|
| 243 |
-
lines.push(`if qc.num_parameters > 0:`);
|
| 244 |
-
lines.push(` qc_shot = qc.assign_parameters([0.0] * qc.num_parameters)`);
|
| 245 |
-
lines.push(`else:`);
|
| 246 |
-
lines.push(` qc_shot = qc`);
|
| 247 |
-
lines.push(``);
|
| 248 |
-
lines.push(`noise_path = resolve_noise_snapshot("${snapshot}")`);
|
| 249 |
-
lines.push(`recommender = get_recommender()`);
|
| 250 |
-
lines.push(`result = recommender.predict(qc_shot, noise_path, alpha=${alpha})`);
|
| 251 |
-
lines.push(`if result:`);
|
| 252 |
-
lines.push(` print(f"Qshot: recommended {result['recommended_shots']} shots")`);
|
| 253 |
-
lines.push(` print(f" predicted fidelity: {result['predicted_fidelity']:.4f}")`);
|
| 254 |
-
lines.push(`else:`);
|
| 255 |
-
lines.push(` print("Qshot: could not produce recommendation")`);
|
| 256 |
-
lines.push(``);
|
| 257 |
-
break;
|
| 258 |
-
}
|
| 259 |
-
|
| 260 |
-
case "fidelity": {
|
| 261 |
-
const method = String(b.params.method ?? "statevector");
|
| 262 |
-
const policy = String(b.params.unbound_param_policy ?? "bind_zero");
|
| 263 |
-
lines.push(`# Step ${stepNum}: Fidelity estimate`);
|
| 264 |
-
if (method === "sampled") {
|
| 265 |
-
lines.push(
|
| 266 |
-
`from qlib.qiskit_utils import sampledFidelityEstimator`,
|
| 267 |
-
);
|
| 268 |
-
lines.push(``);
|
| 269 |
-
lines.push(
|
| 270 |
-
`fidelity, meta = sampledFidelityEstimator(`,
|
| 271 |
-
);
|
| 272 |
-
lines.push(` qc,`);
|
| 273 |
-
lines.push(
|
| 274 |
-
` backend if 'backend' in dir() else None,`,
|
| 275 |
-
);
|
| 276 |
-
lines.push(
|
| 277 |
-
` shots=shots if 'shots' in dir() else 1024,`,
|
| 278 |
-
);
|
| 279 |
-
lines.push(` unbound_param_policy="${policy}",`);
|
| 280 |
-
lines.push(`)`);
|
| 281 |
-
lines.push(
|
| 282 |
-
`print(f"Fidelity (sampled, shots={meta['shots']}): {fidelity:.6f}")`,
|
| 283 |
-
);
|
| 284 |
-
} else {
|
| 285 |
-
lines.push(
|
| 286 |
-
`from qlib.qiskit_utils import simpleFidelityEstimator`,
|
| 287 |
-
);
|
| 288 |
-
lines.push(``);
|
| 289 |
-
lines.push(
|
| 290 |
-
`fidelity, meta = simpleFidelityEstimator(`,
|
| 291 |
-
);
|
| 292 |
-
lines.push(
|
| 293 |
-
` qc, unbound_param_policy="${policy}",`,
|
| 294 |
-
);
|
| 295 |
-
lines.push(`)`);
|
| 296 |
-
lines.push(
|
| 297 |
-
`print(f"Fidelity (noiseless statevector): {fidelity:.6f}")`,
|
| 298 |
-
);
|
| 299 |
-
}
|
| 300 |
-
lines.push(``);
|
| 301 |
-
break;
|
| 302 |
-
}
|
| 303 |
-
|
| 304 |
-
case "output": {
|
| 305 |
-
lines.push(`# Step ${stepNum}: Output summary`);
|
| 306 |
-
lines.push(`print("\\n" + "=" * 60)`);
|
| 307 |
-
lines.push(`print(f"Final circuit: {qc.num_qubits}q, depth {qc.depth()}, {qc.size()} gates")`);
|
| 308 |
-
lines.push(`print(f"Gate counts: {dict(qc.count_ops())}")`);
|
| 309 |
-
lines.push(`print(qc.draw(output='text', fold=120))`);
|
| 310 |
-
lines.push(``);
|
| 311 |
-
break;
|
| 312 |
-
}
|
| 313 |
-
}
|
| 314 |
-
}
|
| 315 |
|
| 316 |
// Footer
|
| 317 |
lines.push(`# ${"─".repeat(60)}`);
|
|
|
|
| 9 |
* We deliberately keep the generated code flat and readable (no
|
| 10 |
* classes, no abstractions) so someone unfamiliar with the codebase
|
| 11 |
* can follow it line by line.
|
| 12 |
+
*
|
| 13 |
+
* Architecture: one ``Emitter`` per node kind. Each emitter is a pure
|
| 14 |
+
* function from (params, stepNum, ctx) to a list of source lines. The
|
| 15 |
+
* main loop walks the topo-sorted nodes, dispatches to the emitter,
|
| 16 |
+
* and concatenates. To support a new node kind, add one entry to
|
| 17 |
+
* ``EMITTERS``.
|
| 18 |
*/
|
| 19 |
|
| 20 |
import type { Node, Edge } from "@xyflow/react";
|
|
|
|
| 26 |
params: Record<string, unknown>;
|
| 27 |
}
|
| 28 |
|
| 29 |
+
interface EmitContext {
|
| 30 |
+
/** Filename suggestion for an Option A QPY load. */
|
| 31 |
+
sampleKey: string | null;
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
type Emitter = (b: PipelineNode, stepNum: number, ctx: EmitContext) => string[];
|
| 35 |
+
|
| 36 |
+
// ---- topology helper -----------------------------------------------------
|
| 37 |
+
|
| 38 |
/**
|
| 39 |
* Topological sort of canvas nodes using the edge list.
|
| 40 |
+
* Falls back to catalog order if the graph is disconnected.
|
| 41 |
*/
|
| 42 |
function topoSort(nodes: Node[], edges: Edge[]): Node[] {
|
| 43 |
const adj = new Map<string, string[]>();
|
|
|
|
| 69 |
return order.map((id) => byId.get(id)!).filter(Boolean);
|
| 70 |
}
|
| 71 |
|
| 72 |
+
// ---- emitters: one per node kind -----------------------------------------
|
| 73 |
+
//
|
| 74 |
+
// Each emitter returns ONLY the body lines for its step — the main
|
| 75 |
+
// loop handles the leading "# Step N: <title>" header and a trailing
|
| 76 |
+
// blank line. Keep each emitter self-contained so adding a new node
|
| 77 |
+
// kind is a strictly additive change.
|
| 78 |
+
|
| 79 |
+
function asStr(v: unknown, dflt: string): string {
|
| 80 |
+
return typeof v === "string" && v.length > 0 ? v : dflt;
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
function asNum(v: unknown, dflt: number): number {
|
| 84 |
+
return typeof v === "number" && Number.isFinite(v) ? v : dflt;
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
const emitInputCircuit: Emitter = (_b, _step, { sampleKey }) => {
|
| 88 |
+
const lines: string[] = [];
|
| 89 |
+
if (sampleKey) {
|
| 90 |
+
lines.push(`# Sample: ${sampleKey}`);
|
| 91 |
+
lines.push(`# Option A: Load from a .qpy file`);
|
| 92 |
+
lines.push(`# from qiskit import qpy`);
|
| 93 |
+
lines.push(`# with open("${sampleKey}.qpy", "rb") as f:`);
|
| 94 |
+
lines.push(`# qc = qpy.load(f)[0]`);
|
| 95 |
+
lines.push(``);
|
| 96 |
+
lines.push(`# Option B: Build programmatically (replace with your circuit)`);
|
| 97 |
+
} else {
|
| 98 |
+
lines.push(`# Replace with your circuit`);
|
| 99 |
+
}
|
| 100 |
+
lines.push(`qc = QuantumCircuit(4, name="my_circuit")`);
|
| 101 |
+
lines.push(`# qc.ry(0.5, 0)`);
|
| 102 |
+
lines.push(`# qc.cx(0, 1)`);
|
| 103 |
+
lines.push(`# ... add your gates here`);
|
| 104 |
+
return lines;
|
| 105 |
+
};
|
| 106 |
+
|
| 107 |
+
const emitFakeBackend: Emitter = (b) => {
|
| 108 |
+
const name = asStr(b.params.backend_name, "FakeFez");
|
| 109 |
+
const shots = asNum(b.params.shots, 1024);
|
| 110 |
+
return [
|
| 111 |
+
`from qiskit.providers.fake_provider import ${name}V2`,
|
| 112 |
+
`backend = ${name}V2()`,
|
| 113 |
+
`noise_model = NoiseModel.from_backend(backend)`,
|
| 114 |
+
`shots = ${shots} # user-set measurement count`,
|
| 115 |
+
];
|
| 116 |
+
};
|
| 117 |
+
|
| 118 |
+
const emitIbmBackend: Emitter = (b) => {
|
| 119 |
+
const name = asStr(b.params.backend_name, "ibm_fez");
|
| 120 |
+
const shots = asNum(b.params.shots, 1024);
|
| 121 |
+
return [
|
| 122 |
+
`# Requires: pip install qiskit-ibm-runtime`,
|
| 123 |
+
`# from qiskit_ibm_runtime import QiskitRuntimeService`,
|
| 124 |
+
`# service = QiskitRuntimeService(channel="ibm_quantum", token="YOUR_TOKEN")`,
|
| 125 |
+
`# backend = service.backend("${name}")`,
|
| 126 |
+
`# noise_model = NoiseModel.from_backend(backend)`,
|
| 127 |
+
`#`,
|
| 128 |
+
`# For now, falling back to fake backend:`,
|
| 129 |
+
`from qiskit.providers.fake_provider import FakeFezV2`,
|
| 130 |
+
`backend = FakeFezV2()`,
|
| 131 |
+
`noise_model = NoiseModel.from_backend(backend)`,
|
| 132 |
+
`shots = ${shots}`,
|
| 133 |
+
];
|
| 134 |
+
};
|
| 135 |
+
|
| 136 |
+
const emitQucad: Emitter = (b) => {
|
| 137 |
+
const iters = asNum(b.params.iterations, 3);
|
| 138 |
+
const lam = asNum(b.params.lam, 0.005);
|
| 139 |
+
const rho = asNum(b.params.rho, 500.0);
|
| 140 |
+
return [
|
| 141 |
+
`from qlib.qucad import run_qucad_training_noisy`,
|
| 142 |
+
``,
|
| 143 |
+
`# Bind free parameters to zero if circuit is parameterized`,
|
| 144 |
+
`if qc.num_parameters > 0:`,
|
| 145 |
+
` qc_bound = qc.assign_parameters([0.0] * qc.num_parameters)`,
|
| 146 |
+
`else:`,
|
| 147 |
+
` qc_bound = qc`,
|
| 148 |
+
``,
|
| 149 |
+
`theta, mask, history = run_qucad_training_noisy(`,
|
| 150 |
+
` qc, noise_model, backend,`,
|
| 151 |
+
` iterations=${iters}, lam=${lam}, rho=${rho},`,
|
| 152 |
+
`)`,
|
| 153 |
+
`qc = qc.assign_parameters(theta * (mask != 0))`,
|
| 154 |
+
`print(f"QuCAD: kept {int((mask != 0).sum())}/{len(mask)} parameters")`,
|
| 155 |
+
];
|
| 156 |
+
};
|
| 157 |
+
|
| 158 |
+
const emitQubound: Emitter = (b) => {
|
| 159 |
+
const cacheBackend = asStr(b.params.cache_backend, "ibm_fez");
|
| 160 |
+
const threshRaw = asNum(b.params.threshold, 0);
|
| 161 |
+
// 0 / negative disables pass/fail, matching the backend's
|
| 162 |
+
// _build_summary contract.
|
| 163 |
+
const threshold = threshRaw > 0 ? threshRaw : null;
|
| 164 |
+
const lines = [
|
| 165 |
+
`from qlib.qbound import call_QuBound_from_cache`,
|
| 166 |
+
`from pathlib import Path`,
|
| 167 |
+
``,
|
| 168 |
+
`cache_path = Path("cache/ibm_history/${cacheBackend}.pkl")`,
|
| 169 |
+
`if qc.num_parameters > 0:`,
|
| 170 |
+
` qc_eval = qc.assign_parameters([0.0] * qc.num_parameters)`,
|
| 171 |
+
`else:`,
|
| 172 |
+
` qc_eval = qc`,
|
| 173 |
+
``,
|
| 174 |
+
`bound, model, meta = call_QuBound_from_cache(`,
|
| 175 |
+
` qc_eval, cache_path, reference_backend=backend if 'backend' in dir() else None,`,
|
| 176 |
+
`)`,
|
| 177 |
+
`print(f"QuBound predicted error bound: {bound:.6f}")`,
|
| 178 |
+
];
|
| 179 |
+
if (threshold !== null) {
|
| 180 |
+
lines.push(
|
| 181 |
+
`threshold = ${threshold}`,
|
| 182 |
+
`passes = bound <= threshold`,
|
| 183 |
+
`margin = threshold - bound`,
|
| 184 |
+
`print(f" threshold {threshold}: {'PASS' if passes else 'FAIL'} (margin {margin:+.4f})")`,
|
| 185 |
+
);
|
| 186 |
+
}
|
| 187 |
+
return lines;
|
| 188 |
+
};
|
| 189 |
+
|
| 190 |
+
const emitCompvqc: Emitter = () => [
|
| 191 |
+
`from qlib.compvqc import get_LUT, quadraticProgram_luttoqp, admmOptimizedCompVQC, resultsCompressVQC`,
|
| 192 |
+
``,
|
| 193 |
+
`if qc.num_parameters > 0:`,
|
| 194 |
+
` comp_backend = backend if 'backend' in dir() else None`,
|
| 195 |
+
` if comp_backend is None:`,
|
| 196 |
+
` from qiskit.providers.fake_provider import FakeFezV2`,
|
| 197 |
+
` comp_backend = FakeFezV2()`,
|
| 198 |
+
` lut = get_LUT(qc, comp_backend)`,
|
| 199 |
+
` if lut:`,
|
| 200 |
+
` qp = quadraticProgram_luttoqp(qc, lut)`,
|
| 201 |
+
` result = admmOptimizedCompVQC(qp)`,
|
| 202 |
+
` qc = resultsCompressVQC(result, qc)`,
|
| 203 |
+
` print(f"CompressVQC: compressed circuit depth {qc.depth()}")`,
|
| 204 |
+
` else:`,
|
| 205 |
+
` print("CompressVQC: no compressible pairs found")`,
|
| 206 |
+
`else:`,
|
| 207 |
+
` print("CompressVQC: skipped (no parameterized gates)")`,
|
| 208 |
+
];
|
| 209 |
+
|
| 210 |
+
const emitQshot: Emitter = (b) => {
|
| 211 |
+
const snapshot = asStr(b.params.noise_snapshot, "pittsburgh_1");
|
| 212 |
+
const alpha = asNum(b.params.alpha, 0.95);
|
| 213 |
+
return [
|
| 214 |
+
`from qlib.qshot import get_recommender, resolve_noise_snapshot`,
|
| 215 |
+
``,
|
| 216 |
+
`if qc.num_parameters > 0:`,
|
| 217 |
+
` qc_shot = qc.assign_parameters([0.0] * qc.num_parameters)`,
|
| 218 |
+
`else:`,
|
| 219 |
+
` qc_shot = qc`,
|
| 220 |
+
``,
|
| 221 |
+
`noise_path = resolve_noise_snapshot("${snapshot}")`,
|
| 222 |
+
`recommender = get_recommender()`,
|
| 223 |
+
`result = recommender.predict(qc_shot, noise_path, alpha=${alpha})`,
|
| 224 |
+
`if result:`,
|
| 225 |
+
` print(f"Qshot: recommended {result['recommended_shots']} shots")`,
|
| 226 |
+
` print(f" predicted fidelity: {result['predicted_fidelity']:.4f}")`,
|
| 227 |
+
`else:`,
|
| 228 |
+
` print("Qshot: could not produce recommendation")`,
|
| 229 |
+
];
|
| 230 |
+
};
|
| 231 |
+
|
| 232 |
+
const emitFidelity: Emitter = (b) => {
|
| 233 |
+
const method = asStr(b.params.method, "statevector");
|
| 234 |
+
const policy = asStr(b.params.unbound_param_policy, "bind_zero");
|
| 235 |
+
if (method === "sampled") {
|
| 236 |
+
return [
|
| 237 |
+
`from qlib.qiskit_utils import sampledFidelityEstimator`,
|
| 238 |
+
``,
|
| 239 |
+
`fidelity, meta = sampledFidelityEstimator(`,
|
| 240 |
+
` qc,`,
|
| 241 |
+
` backend if 'backend' in dir() else None,`,
|
| 242 |
+
` shots=shots if 'shots' in dir() else 1024,`,
|
| 243 |
+
` unbound_param_policy="${policy}",`,
|
| 244 |
+
`)`,
|
| 245 |
+
`print(f"Fidelity (sampled, shots={meta['shots']}): {fidelity:.6f}")`,
|
| 246 |
+
];
|
| 247 |
+
}
|
| 248 |
+
return [
|
| 249 |
+
`from qlib.qiskit_utils import simpleFidelityEstimator`,
|
| 250 |
+
``,
|
| 251 |
+
`fidelity, meta = simpleFidelityEstimator(`,
|
| 252 |
+
` qc, unbound_param_policy="${policy}",`,
|
| 253 |
+
`)`,
|
| 254 |
+
`print(f"Fidelity (noiseless statevector): {fidelity:.6f}")`,
|
| 255 |
+
];
|
| 256 |
+
};
|
| 257 |
+
|
| 258 |
+
const emitOutput: Emitter = () => [
|
| 259 |
+
`print("\\n" + "=" * 60)`,
|
| 260 |
+
`print(f"Final circuit: {qc.num_qubits}q, depth {qc.depth()}, {qc.size()} gates")`,
|
| 261 |
+
`print(f"Gate counts: {dict(qc.count_ops())}")`,
|
| 262 |
+
`print(qc.draw(output='text', fold=120))`,
|
| 263 |
+
];
|
| 264 |
+
|
| 265 |
+
const STEP_TITLES: Record<NodeKind, string> = {
|
| 266 |
+
input_circuit: "Load circuit",
|
| 267 |
+
fake_backend: "Noisy simulator",
|
| 268 |
+
ibm_backend: "IBM live backend",
|
| 269 |
+
qucad: "QuCAD — noise-aware VQC sparsification",
|
| 270 |
+
qubound: "QuBound — LSTM error-bound prediction",
|
| 271 |
+
compvqc: "CompressVQC — fold redundant gates",
|
| 272 |
+
qshot: "Qshot — noise-aware shot-count recommendation",
|
| 273 |
+
fidelity: "Fidelity estimate",
|
| 274 |
+
output: "Output summary",
|
| 275 |
+
};
|
| 276 |
+
|
| 277 |
+
const EMITTERS: Record<NodeKind, Emitter> = {
|
| 278 |
+
input_circuit: emitInputCircuit,
|
| 279 |
+
fake_backend: emitFakeBackend,
|
| 280 |
+
ibm_backend: emitIbmBackend,
|
| 281 |
+
qucad: emitQucad,
|
| 282 |
+
qubound: emitQubound,
|
| 283 |
+
compvqc: emitCompvqc,
|
| 284 |
+
qshot: emitQshot,
|
| 285 |
+
fidelity: emitFidelity,
|
| 286 |
+
output: emitOutput,
|
| 287 |
+
};
|
| 288 |
+
|
| 289 |
+
// ---- main entry ----------------------------------------------------------
|
| 290 |
+
|
| 291 |
export function generatePythonScript(
|
| 292 |
nodes: Node[],
|
| 293 |
edges: Edge[],
|
|
|
|
| 300 |
}));
|
| 301 |
|
| 302 |
const lines: string[] = [];
|
|
|
|
| 303 |
|
| 304 |
// Header
|
| 305 |
lines.push(`"""`);
|
|
|
|
| 308 |
lines.push(`"""`);
|
| 309 |
lines.push(``);
|
| 310 |
|
| 311 |
+
// Imports. QuantumCircuit is always needed; AerSimulator + NoiseModel
|
| 312 |
+
// come along for any backend block. Detailed qlib imports are emitted
|
| 313 |
+
// inline in each step's body so unused steps don't leave dead imports.
|
| 314 |
+
const imports = new Set<string>(["from qiskit import QuantumCircuit"]);
|
| 315 |
+
const hasBackend = blocks.some(
|
| 316 |
+
(b) => b.kind === "fake_backend" || b.kind === "ibm_backend",
|
| 317 |
+
);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 318 |
if (hasBackend) {
|
| 319 |
imports.add("from qiskit_aer import AerSimulator");
|
| 320 |
imports.add("from qiskit_aer.noise import NoiseModel");
|
| 321 |
}
|
|
|
|
| 322 |
lines.push([...imports].sort().join("\n"));
|
| 323 |
lines.push(``);
|
| 324 |
|
| 325 |
+
const sep = `# ${"─".repeat(60)}`;
|
| 326 |
+
const ctx: EmitContext = { sampleKey };
|
| 327 |
+
blocks.forEach((b, i) => {
|
| 328 |
+
const stepNum = i + 1;
|
| 329 |
+
const emitter = EMITTERS[b.kind];
|
| 330 |
+
if (!emitter) return; // Plugin / unknown — skip silently.
|
| 331 |
lines.push(sep);
|
| 332 |
+
lines.push(`# Step ${stepNum}: ${STEP_TITLES[b.kind] ?? b.kind}`);
|
| 333 |
+
lines.push(...emitter(b, stepNum, ctx));
|
| 334 |
+
lines.push(``);
|
| 335 |
+
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 336 |
|
| 337 |
// Footer
|
| 338 |
lines.push(`# ${"─".repeat(60)}`);
|