Spaces:
Sleeping
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.
Files changed (5)
28 unmodified lines29303132333450 unmodified lines858687888990919293949546 unmodified lines14214314414514614714814915015115215315415515615715815916016116216316416516616716891 unmodified lines2602612622632642654 unmodified lines27027127227327427527627727810 unmodified lines2892902912922932942952962972982993003013023033043053063073083092 unmodified lines31231331431531631731831932032132232332432532632732832933033133233330 unmodified lines364365366367368369370371372373374375376435 unmodified lines812813814815816817818127 unmodified lines94694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122128 unmodified linesfrom app.config import Settings, ibm_history_cache_pathfrom app.schemas import FlowEdge, FlowNode, StepResultlogger = logging.getLogger(__name__)50 unmodified lines_step_cache: OrderedDict[str, tuple[StepResult, dict]] = OrderedDict()# Re-export under the old name so other call sites in this module# don't have to change. The canonical implementation lives in# run_cache so cache-hash + plugin-payload use identical bytes.from app.services.run_cache import qpy_dump_bytes as _qpy_bytes_for_hash # noqa: E402def _prefix_hash(circuit_qpy: bytes, nodes_so_far: list[FlowNode]) -> str:"""Hash the pipeline prefix up to and including the last node in46 unmodified lineskey: str,result: StepResult,ctx: dict,prefix_types: set[str] | None = None,) -> None:# Deep-copy QuantumCircuit objects so that downstream handlers that# mutate in-place (we audited the built-ins and they all defensively# copy now, but a future plugin author may not) can't silently# corrupt the cached snapshot. Other ctx values (backend, floats)# are either immutable or cheap to share by reference.snapshot = {}for k, v in ctx.items():if isinstance(v, QuantumCircuit):snapshot[k] = v.copy()else:snapshot[k] = v_step_cache[key] = (result, snapshot)_step_cache.move_to_end(key)# Track which node types this prefix covers so plugin reinstalls# can surgically invalidate only the affected entries. None means# 'caller didn't supply' — the entry is still cached but won't be# invalidated by node-type lookup.if prefix_types is not None:_step_cache_node_types[key] = set(prefix_types)while len(_step_cache) > _STEP_CACHE_MAX:old_key, _ = _step_cache.popitem(last=False)_step_cache_node_types.pop(old_key, None)91 unmodified lines}.get(name, FakeFez)()# ---------- Per-node handlers ----------def _handle_fake_backend(node: FlowNode, ctx: dict, _settings: Settings) -> StepResult:4 unmodified linest0 = _now()name_raw = node.data.get("backend_name", "FakeFez")# Refuse empty / unknown names with a clear message instead of# silently picking FakeFez — users typo backend names and got# confused that their "FakeBollywood" run mysteriously matched# FakeFez results.if not isinstance(name_raw, str) or not name_raw:return _make_step(node, "error", started_at=t0,10 unmodified linesf"Choose one of: {', '.join(_FAKE_BACKENDS_AVAILABLE)}."),)name = name_raw# Clamp shots to a sensible range to avoid DOS via "shots=10**9".shots_raw = node.data.get("shots", 1024)shots = int(shots_raw) if isinstance(shots_raw, (int, float)) else 1024shots = max(1, min(shots, 65536))backend = _load_fake_backend(name)ctx["backend"] = backendctx["backend_is_live"] = Falsectx["shots"] = shotsreturn _make_step(node,"ok",started_at=t0,summary={"backend_name": name,"num_qubits": backend.configuration().n_qubits,"shots": shots,},2 unmodified linesdef _handle_ibm_backend(node: FlowNode, ctx: dict, settings: Settings) -> StepResult:t0 = _now()shots_raw = node.data.get("shots", 1024)shots = int(shots_raw) if isinstance(shots_raw, (int, float)) else 1024shots = max(1, min(shots, 65536))if not settings.has_ibm_token or not settings.allow_live_ibm:# Silently downgrade to fake so the rest of the pipeline still runs.fallback = _load_fake_backend(node.data.get("fallback_backend", "FakeFez"))ctx["backend"] = fallbackctx["backend_is_live"] = Falsectx["shots"] = shotsreturn _make_step(node,"skipped",started_at=t0,message="Live IBM call disabled; falling back to FakeFez.",summary={"fallback": "FakeFez", "shots": shots},)# Validate the requested backend name up front. IBM's set of live# backends is dynamic (depends on the user's plan and IBM's current# roster), so we can't enumerate them like the fake backends. The30 unmodified linesf"{_format_exception_for_user(exc)}"),)ctx["backend"] = backendctx["backend_is_live"] = Truectx["shots"] = shotsreturn _make_step(node,"ok",started_at=t0,summary={"backend_name": name, "live": True, "shots": shots},)435 unmodified lines# circuit serialized to QPY.inputs: dict = {"scalars": {}, "backend_name": None}if "circuit" in ctx:inputs["circuit_qpy_bytes"] = _qpy_bytes_for_hash(ctx["circuit"])if "backend" in ctx and ctx["backend"] is not None:# The Qiskit FakeBackend objects have a `.name` attribute the# plugin can use; live IBM backends also have one. We pass it127 unmodified lines# ---------- Public entry ----------def run_pipeline(*,circuit: QuantumCircuit,nodes: list[FlowNode],edges: list[FlowEdge],settings: Settings,user_id: str | None = None,) -> list[StepResult]:"""Execute the user's pipeline. Returns a StepResult per visited node."""ctx: dict = {"circuit": circuit}steps: list[StepResult] = []# If any node in the graph is a plugin and we know the user, make# sure their plugins are hydrated from the HF Datasets backing# store before dispatching. Without this, an authenticated user# running a pipeline on a freshly-restarted Space (or on the OTHER# Space mirroring the same dataset) would see "plugin not found"# even though it's safely in their dataset.if user_id and any(n.type not in _HANDLERS and n.type != "input_circuit" for n in nodes):from app.services import plugin_servicetry:plugin_service.hydrate_from_dataset_if_needed(user_id)except Exception:logger.exception("Pre-run plugin hydration failed for %s (continuing)", user_id)ordered = topological_order(nodes, edges)for node in ordered:if node.type == "input_circuit":steps.append(_make_step(node,"ok",summary={"num_qubits": circuit.num_qubits,"depth": circuit.depth(),"num_parameters": circuit.num_parameters,},circuit_shape=_shape_of(circuit),))continuehandler = _HANDLERS.get(node.type)if handler is not None:try:step = handler(node, ctx, settings)# Snapshot the circuit's current shape onto the step.# Handlers don't bother setting this themselves —# they just mutate ctx, and we read it here.if step.status == "ok" and "circuit" in ctx:step = step.model_copy(update={"circuit_shape": _shape_of(ctx["circuit"])},)steps.append(step)# A handler that returned status="error" (e.g. QuCAD# raised "needs a backend upstream") must stop the# chain — downstream steps would otherwise execute on# whatever ctx['circuit'] the upstream handed in,# silently producing misleading results. status="skipped"# is fine to continue past (the user is told the block# didn't run, and ctx remains valid).if step.status == "error":breakexcept Exception as exc:# Log the full traceback server-side; surface the# exception class + first line of str(exc) to the# user so they can self-diagnose without server log# access (a Space deployment has no log surface for# end users). We deliberately keep it to one line —# full tracebacks may contain file paths.logger.exception("Built-in handler %s crashed for node %s",node.type, node.id,)detail = _format_exception_for_user(exc)steps.append(_make_step(node, "error",message=(f"The {node.type} block hit an unexpected error: {detail}"),))breakcontinue# Not a built-in — try a user plugin if we have a user_id.if user_id:step = _handle_plugin(node, ctx, settings, user_id=user_id)if step.status == "ok" and "circuit" in ctx:step = step.model_copy(update={"circuit_shape": _shape_of(ctx["circuit"])},)steps.append(step)if step.status == "error":breakcontinuesteps.append(_make_step(node, "skipped",message=f"No handler for node type {node.type!r}",))return stepsdef run_pipeline_stream(*,circuit: QuantumCircuit,nodes: list[FlowNode],edges: list[FlowEdge],settings: Settings,user_id: str | None = None,) -> Generator[StepResult, None, None]:"""Generator version of run_pipeline: yields each StepResult as itcompletes, enabling Server-Sent Events in the route layer.Uses an in-memory per-node prefix cache so that unchanged pipelineprefixes resolve instantly. If the user changes only the last blockand re-runs, all preceding steps are served from cache (~0 ms each)instead of re-executing (which can take minutes for QuBound/Qshot).When ``user_id`` is provided, unknown node types are dispatched tothe per-user plugin registry (see services/plugin_service.py).Plugin steps participate in the cache: the prefix hash includesthe plugin's kind + params, so re-running with the same pluginsettings hits the cache; modifying the plugin's params (orre-uploading) busts only the suffix."""ctx: dict = {"circuit": circuit}ordered = topological_order(nodes, edges)# Same hydration as run_pipeline — without this, a logged-in user# running a pipeline on a freshly-restarted Space or on the OTHER# mirror Space would see "plugin not found" even though it sits# in their HF Datasets backing store.if user_id and any(n.type not in _HANDLERS and n.type != "input_circuit" for n in nodes):from app.services import plugin_servicetry:plugin_service.hydrate_from_dataset_if_needed(user_id)except Exception:logger.exception("Pre-stream plugin hydration failed for %s (continuing)", user_id)# Compute the circuit's QPY hash once (expensive) — reused for# every prefix hash in this run.circuit_qpy = _qpy_bytes_for_hash(circuit)nodes_so_far: list[FlowNode] = []# Sticky flag: once a step emits nondeterministic=True (e.g.# sampled fidelity), the in-memory prefix cache must stop# participating for the rest of the run. Reasons:# * THIS step's result is fresh-each-run by design; caching it# would freeze a single shot draw and replay it.# * EVERY downstream step's prefix hash would match a previous# run's, but the ctx it depends on (e.g. ctx['fidelity']) is# stale, so a lookup hit would restore a contradictory state.cache_disabled_for_tail = Falsefor node in ordered:nodes_so_far.append(node)prefix_key = _prefix_hash(circuit_qpy, nodes_so_far)prefix_types = {n.type for n in nodes_so_far}# ---- cache hit: return saved result + restore ctx ----# A cached entry that is itself nondeterministic must NEVER# be served — it'd be the same scientific bug we're fixing.# This guards against (a) legacy entries from before this# fix, and (b) any future handler that retroactively flips# nondeterministic on. We evict and re-execute.if not cache_disabled_for_tail and prefix_key in _step_cache:cached_result, cached_ctx = _step_cache[prefix_key]if cached_result.nondeterministic:logger.debug("Step cache EVICT (nondet legacy) %s (%s)",node.type, prefix_key[:8],)del _step_cache[prefix_key]cache_disabled_for_tail = True# Fall through to the miss path.else:ctx.update(cached_ctx)_step_cache.move_to_end(prefix_key) # refresh LRUlogger.debug("Step cache HIT for %s (%s)", node.type, prefix_key[:8])yield cached_result.model_copy(update={"from_step_cache": True})continue# ---- cache miss: execute the step ----logger.debug("Step cache MISS for %s (%s)", node.type, prefix_key[:8])if node.type == "input_circuit":result = _make_step(node,"ok",summary={"num_qubits": circuit.num_qubits,"depth": circuit.depth(),"num_parameters": circuit.num_parameters,},circuit_shape=_shape_of(circuit),)if not cache_disabled_for_tail:_cache_put(prefix_key, result, ctx, prefix_types)yield resultcontinuehandler = _HANDLERS.get(node.type)if handler is not None:try:result = handler(node, ctx, settings)if result.status == "ok" and "circuit" in ctx:result = result.model_copy(update={"circuit_shape": _shape_of(ctx["circuit"])},)# A nondeterministic step (e.g. sampled fidelity) trips# the sticky flag so this step itself AND any# downstream step in the same run no longer write to# the cache, AND future runs of the same prefix won't# lookup-hit a stale draw. Crucially the flag is set# BEFORE _cache_put so the nondeterministic step's# own result is also not written.if result.nondeterministic:cache_disabled_for_tail = Trueif not cache_disabled_for_tail:_cache_put(prefix_key, result, ctx, prefix_types)yield result# Same break-on-error policy as run_pipeline above:# status="error" stops the chain so downstream steps# don't silently execute on stale ctx.if result.status == "error":breakexcept Exception as exc:# Same policy as run_pipeline above: log traceback +# surface the exception class + first line of message.logger.exception("Built-in handler %s crashed (stream) for node %s",node.type, node.id,)detail = _format_exception_for_user(exc)result = _make_step(node, "error",message=(f"The {node.type} block hit an unexpected error: {detail}"),)yield resultbreakcontinue# Not a built-in — plugin dispatch path.if user_id:result = _handle_plugin(node, ctx, settings, user_id=user_id)if result.status == "ok" and "circuit" in ctx:result = result.model_copy(update={"circuit_shape": _shape_of(ctx["circuit"])},)# Flag first so a plugin marking itself nondeterministic# is treated like sampled fidelity: its own result isn't# cached, and nothing downstream is.if result.nondeterministic:cache_disabled_for_tail = True# Only cache successful plugin runs so a transient crash# doesn't get pinned to the prefix, and respect the flag.if result.status == "ok" and not cache_disabled_for_tail:_cache_put(prefix_key, result, ctx, prefix_types)yield resultif result.status == "error":breakcontinueresult = _make_step(node, "skipped",message=f"No handler for node type {node.type!r}",)if not cache_disabled_for_tail:_cache_put(prefix_key, result, ctx, prefix_types)yield result28 unmodified lines2930313233343550 unmodified lines86878889909146 unmodified lines13813914014114214314414514614714814915015115215315415515615715815916016116216316491 unmodified lines2562572582592602612622632642652662672682692702712722732742752762772782792802812822832842854 unmodified lines29029129229329429529629710 unmodified lines3083093103113123133143153163173183193202 unmodified lines32332432532632732832933033133233333433533633733833934034130 unmodified lines372373374375376377378379380435 unmodified lines816817818819820821822127 unmodified lines95095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114328 unmodified linesfrom app.config import Settings, ibm_history_cache_pathfrom app.schemas import FlowEdge, FlowNode, StepResultfrom app.services.run_cache import qpy_dump_byteslogger = logging.getLogger(__name__)50 unmodified lines_step_cache: OrderedDict[str, tuple[StepResult, dict]] = OrderedDict()def _prefix_hash(circuit_qpy: bytes, nodes_so_far: list[FlowNode]) -> str:"""Hash the pipeline prefix up to and including the last node in46 unmodified lineskey: str,result: StepResult,ctx: dict,prefix_types: set[str],) -> None:"""Store ``result`` + a snapshot of ``ctx`` under ``key``.QuantumCircuit objects in ctx are deep-copied so that downstreamhandlers that mutate in-place (built-ins all defensively copynow, but a future plugin author may not) can't silently corruptthe cached snapshot. Other ctx values (backend, floats, lists ofprimitives) are either immutable or cheap to share by reference.``prefix_types`` is the set of node types covered by this prefix,used by :func:`invalidate_step_cache_for_node_type` to surgicallyevict on plugin reinstall."""snapshot = {k: v.copy() if isinstance(v, QuantumCircuit) else vfor k, v in ctx.items()}_step_cache[key] = (result, snapshot)_step_cache.move_to_end(key)_step_cache_node_types[key] = set(prefix_types)while len(_step_cache) > _STEP_CACHE_MAX:old_key, _ = _step_cache.popitem(last=False)_step_cache_node_types.pop(old_key, None)91 unmodified lines}.get(name, FakeFez)()# ---------- Per-handler shared helpers ----------# Allowed shot count range. 1 shot is degenerate but legitimate (single# sample); 65536 is the largest power-of-two that Aer happily runs# without OOM on free HF tier. Outside the range we clamp silently —# the user's intent (more / fewer shots) is honoured to the extent we# can serve it._MIN_SHOTS, _MAX_SHOTS = 1, 65536def _clamp_shots(node: FlowNode, default: int = 1024) -> int:"""Read ``shots`` off a node payload and clamp to the safe range."""raw = node.data.get("shots", default)shots = int(raw) if isinstance(raw, (int, float)) else defaultreturn max(_MIN_SHOTS, min(shots, _MAX_SHOTS))def _set_backend_ctx(ctx: dict, backend, *, is_live: bool, shots: int) -> None:"""Standard shape for what backend-emitting handlers write to ctx."""ctx["backend"] = backendctx["backend_is_live"] = is_livectx["shots"] = shots# ---------- Per-node handlers ----------def _handle_fake_backend(node: FlowNode, ctx: dict, _settings: Settings) -> StepResult:4 unmodified linest0 = _now()name_raw = node.data.get("backend_name", "FakeFez")# Refuse empty / unknown names with a clear message instead of# silently picking FakeFez. Typos like "FakeBollywood" used to# match FakeFez results and confuse users about why.if not isinstance(name_raw, str) or not name_raw:return _make_step(node, "error", started_at=t0,10 unmodified linesf"Choose one of: {', '.join(_FAKE_BACKENDS_AVAILABLE)}."),)shots = _clamp_shots(node)backend = _load_fake_backend(name_raw)_set_backend_ctx(ctx, backend, is_live=False, shots=shots)return _make_step(node, "ok", started_at=t0,summary={"backend_name": name_raw,"num_qubits": backend.configuration().n_qubits,"shots": shots,},2 unmodified linesdef _handle_ibm_backend(node: FlowNode, ctx: dict, settings: Settings) -> StepResult:t0 = _now()shots = _clamp_shots(node)# Live IBM disabled on this deployment: silently downgrade so the# rest of the pipeline still runs against the named fallback fake.if not settings.has_ibm_token or not settings.allow_live_ibm:fallback = _load_fake_backend(node.data.get("fallback_backend", "FakeFez"))_set_backend_ctx(ctx, fallback, is_live=False, shots=shots)return _make_step(node, "skipped", started_at=t0,message="Live IBM call disabled; falling back to FakeFez.",summary={"fallback": "FakeFez", "shots": shots},)# Validate the requested backend name up front. IBM's set of live# backends is dynamic (depends on the user's plan and IBM's current# roster), so we can't enumerate them like the fake backends. The30 unmodified linesf"{_format_exception_for_user(exc)}"),)_set_backend_ctx(ctx, backend, is_live=True, shots=shots)return _make_step(node, "ok", started_at=t0,summary={"backend_name": name, "live": True, "shots": shots},)435 unmodified lines# circuit serialized to QPY.inputs: dict = {"scalars": {}, "backend_name": None}if "circuit" in ctx:inputs["circuit_qpy_bytes"] = qpy_dump_bytes(ctx["circuit"])if "backend" in ctx and ctx["backend"] is not None:# The Qiskit FakeBackend objects have a `.name` attribute the# plugin can use; live IBM backends also have one. We pass it127 unmodified lines# ---------- Public entry ----------def _dispatch_one_node(node: FlowNode,ctx: dict,circuit: QuantumCircuit,settings: Settings,user_id: str | None,) -> StepResult:"""Compute the StepResult for a single node, with no caching.This is the only place that knows how to map a ``node.type`` to anexecutor — built-in handlers, the user-plugin dispatcher, or the'no handler found' skip. Exceptions from built-in handlers arecaught and surfaced through ``_format_exception_for_user``;handlers that fail by *returning* status='error' (the common pathfor input-validation failures) flow through unmodified."""if node.type == "input_circuit":return _make_step(node, "ok",summary={"num_qubits": circuit.num_qubits,"depth": circuit.depth(),"num_parameters": circuit.num_parameters,},circuit_shape=_shape_of(circuit),)handler = _HANDLERS.get(node.type)if handler is not None:try:return handler(node, ctx, settings)except Exception as exc:logger.exception("Built-in handler %s crashed for node %s", node.type, node.id,)return _make_step(node, "error",message=(f"The {node.type} block hit an unexpected error: "f"{_format_exception_for_user(exc)}"),)# Not a built-in — try the user-plugin path if we have a user.if user_id:return _handle_plugin(node, ctx, settings, user_id=user_id)return _make_step(node, "skipped",message=f"No handler for node type {node.type!r}",)def _hydrate_user_plugins_if_needed(nodes: list[FlowNode], user_id: str | None) -> None:"""Make sure the user's plugins are on disk before dispatch.On a freshly-restarted HF Space (or the mirror Space) anauthenticated user's plugins live only in HF Datasets until thefirst reference, so a pipeline that uses them would otherwise hit'plugin not found'. Cheap when nothing to hydrate. Failure islogged but non-fatal — dispatch continues and the missing pluginsurfaces as a regular step error."""if not user_id:returnhas_user_plugin = any(n.type not in _HANDLERS and n.type != "input_circuit" for n in nodes)if not has_user_plugin:returnfrom app.services import plugin_service # local: avoid import cycletry:plugin_service.hydrate_from_dataset_if_needed(user_id)except Exception:logger.exception("Plugin hydration failed for %s (continuing)", user_id)def _execute_pipeline(*,circuit: QuantumCircuit,nodes: list[FlowNode],edges: list[FlowEdge],settings: Settings,user_id: str | None,) -> Generator[StepResult, None, None]:"""Single execution loop for a pipeline graph.Both :func:`run_pipeline` (eager list) and:func:`run_pipeline_stream` (SSE generator) delegate here. Thisfunction:* dispatches each node via :func:`_dispatch_one_node`,* stamps the post-step ``circuit_shape`` onto successful results(handlers don't bother — they just mutate ctx),* participates in the in-memory prefix cache,* obeys the sticky 'cache disabled' rule that the first:attr:`StepResult.nondeterministic` step trips for the rest ofthe run — both this step and every downstream step bypasscache lookup AND put, because caching a single shot draw andreplaying it (or restoring a stale ctx that depended on one)is a silent scientific bug,* stops on ``status == 'error'`` so downstream steps don't runon inconsistent ctx,* caches only ``ok`` / ``skipped`` results — error results areoften transient and shouldn't pin the prefix."""ctx: dict = {"circuit": circuit}ordered = topological_order(nodes, edges)_hydrate_user_plugins_if_needed(nodes, user_id)circuit_qpy = qpy_dump_bytes(circuit) # expensive; reuse across prefixesnodes_so_far: list[FlowNode] = []cache_disabled = Falsefor node in ordered:nodes_so_far.append(node)prefix_key = _prefix_hash(circuit_qpy, nodes_so_far)prefix_types = {n.type for n in nodes_so_far}# Cache hit path. A nondeterministic cached entry MUST NEVER# be served (legacy entries from before this rule existed are# actively evicted so they can't haunt future runs).if not cache_disabled and prefix_key in _step_cache:cached_result, cached_ctx = _step_cache[prefix_key]if cached_result.nondeterministic:del _step_cache[prefix_key]_step_cache_node_types.pop(prefix_key, None)cache_disabled = True# Fall through to re-execute.else:ctx.update(cached_ctx)_step_cache.move_to_end(prefix_key) # LRU refreshyield cached_result.model_copy(update={"from_step_cache": True})continue# Cache miss: actually run the node.result = _dispatch_one_node(node, ctx, circuit, settings, user_id)# Stamp the post-step circuit shape onto successful results so# the canvas can draw data-flow labels on outgoing edges.if result.status == "ok" and "circuit" in ctx:result = result.model_copy(update={"circuit_shape": _shape_of(ctx["circuit"])},)# Disable cache forward of the first nondeterministic step.# Set the flag BEFORE _cache_put so this step itself isn't# written — otherwise a single shot draw would get cached.if result.nondeterministic:cache_disabled = Trueif not cache_disabled and result.status in ("ok", "skipped"):_cache_put(prefix_key, result, ctx, prefix_types)yield result# Error stops the chain — downstream steps would silently run# on the previous handler's stale ctx and report misleading# numbers. (skipped does NOT stop; ctx is still valid.)if result.status == "error":breakdef run_pipeline(*,circuit: QuantumCircuit,nodes: list[FlowNode],edges: list[FlowEdge],settings: Settings,user_id: str | None = None,) -> list[StepResult]:"""Eager wrapper: run the pipeline and collect StepResults."""return list(_execute_pipeline(circuit=circuit, nodes=nodes, edges=edges,settings=settings, user_id=user_id,))def run_pipeline_stream(*,circuit: QuantumCircuit,nodes: list[FlowNode],edges: list[FlowEdge],settings: Settings,user_id: str | None = None,) -> Generator[StepResult, None, None]:"""Streaming wrapper for the SSE route. Yields each StepResult assoon as it completes so the UI can show progressive output."""yield from _execute_pipeline(circuit=circuit, nodes=nodes, edges=edges,settings=settings, user_id=user_id,)
13 unmodified lines141516171819335 unmodified lines35535635735835936036136236336436536636736836937037137237337437537613 unmodified linestype PluginNodeSpec,} from "../lib/nodeCatalog";import { NodeParamEditor } from "./NodeParamEditor";import { TipIcon } from "./TipIcon";import { useApp } from "../lib/store";import { FAMILY_HINTS } from "../lib/familyHints";335 unmodified lines<div className="flex-1 text-[10px] text-ok/80">✓ ran</div>)}<div className="flex items-center gap-1 shrink-0">{step.from_step_cache && (<spanclassName="text-[9px] px-1 py-0.5 rounded border border-accent/30 text-accent"title="Served from per-node cache (pipeline prefix unchanged)">cached</span>)}{step.nondeterministic && !step.from_step_cache && (<spanclassName="text-[9px] px-1 py-0.5 rounded border border-warn/30 text-warn"title="Result is intentionally fresh each run (e.g. sampled shots). The per-node cache is bypassed for this step and every downstream step.">live</span>)}{durationS !== null && (<spanclassName={`text-[9px] px-1 py-0.5 rounded border font-mono ${durBadgeClass}`}13 unmodified lines14151617181920335 unmodified lines35635735835936036136213 unmodified linestype PluginNodeSpec,} from "../lib/nodeCatalog";import { NodeParamEditor } from "./NodeParamEditor";import { RunStatusChips } from "./RunStatusChips";import { TipIcon } from "./TipIcon";import { useApp } from "../lib/store";import { FAMILY_HINTS } from "../lib/familyHints";335 unmodified lines<div className="flex-1 text-[10px] text-ok/80">✓ ran</div>)}<div className="flex items-center gap-1 shrink-0"><RunStatusChips step={step} variant="tile" />{durationS !== null && (<spanclassName={`text-[9px] px-1 py-0.5 rounded border font-mono ${durBadgeClass}`}
20 unmodified lines212223242526148 unmodified lines17517617717817918018118218318418518618718818919019119219320 unmodified lines} from "lucide-react";import { StepBody } from "./results/cards";import { PluginFigures } from "./PluginFigures";export function ResultsPane({ onCollapse }: { onCollapse?: () => void } = {}) {const run = useApp((s) => s.run);148 unmodified lines<span className={`chip ${statusClass}`}>{statusIcon} {step.status}</span>{step.from_step_cache && (<span className="chip !border-accent/30 !text-accent text-[9px]">cached</span>)}{step.nondeterministic && !step.from_step_cache && (<spanclassName="chip !border-warn/30 !text-warn text-[9px]"title="Fresh each run — the per-node cache is bypassed for this step and everything downstream.">live</span>)}</div><div className="text-[11px] text-mute">{dur.toFixed(2)}s · node <span className="font-mono">{step.node_id}</span>20 unmodified lines21222324252627148 unmodified lines17617717817918018118220 unmodified lines} from "lucide-react";import { StepBody } from "./results/cards";import { PluginFigures } from "./PluginFigures";import { RunStatusChips } from "./RunStatusChips";export function ResultsPane({ onCollapse }: { onCollapse?: () => void } = {}) {const run = useApp((s) => s.run);148 unmodified lines<span className={`chip ${statusClass}`}>{statusIcon} {step.status}</span><RunStatusChips step={step} variant="card" /></div><div className="text-[11px] text-mute">{dur.toFixed(2)}s · node <span className="font-mono">{step.node_id}</span>
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758import type { StepResult } from "../lib/api";
/** * The pair of contextual chips a step can carry beyond its status: * * "cached" — served from the per-node prefix cache (pipeline * prefix unchanged since the last run). * * "live" — intentionally nondeterministic (e.g. sampled * fidelity with N shots). The cache is bypassed for this step * and everything downstream so the user gets a fresh shot draw * each run. * * Two visual variants: * * `tile` — compact 9px text + tight padding for the canvas tile * (QNode's result strip). * * `card` — the global `.chip` pill used in the right pane card * (ResultsPane's step header). * * cached and live are mutually exclusive in practice (a cache hit * can't also be flagged nondeterministic, since we never write * nondeterministic results into the cache), so we render at most one. */export function RunStatusChips({ step, variant,}: { step: StepResult; variant: "tile" | "card";}) { const isTile = variant === "tile"; const cachedClass = isTile ? "text-[9px] px-1 py-0.5 rounded border border-accent/30 text-accent" : "chip !border-accent/30 !text-accent text-[9px]"; const liveClass = isTile ? "text-[9px] px-1 py-0.5 rounded border border-warn/30 text-warn" : "chip !border-warn/30 !text-warn text-[9px]";
if (step.from_step_cache) { return ( <span className={cachedClass} title="Served from per-node cache (pipeline prefix unchanged)" > cached </span> ); } if (step.nondeterministic) { return ( <span className={liveClass} title="Result is intentionally fresh each run (e.g. sampled shots). The per-node cache is bypassed for this step and every downstream step." > live </span> ); } return null;}8 unmodified lines910111213145 unmodified lines20212223242526272825 unmodified lines5455565758596 unmodified lines666768697071722 unmodified lines757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163178 unmodified lines* We deliberately keep the generated code flat and readable (no* classes, no abstractions) so someone unfamiliar with the codebase* can follow it line by line.*/import type { Node, Edge } from "@xyflow/react";5 unmodified linesparams: Record<string, unknown>;}/*** Topological sort of canvas nodes using the edge list.* Falls back to catalog family order if the graph is disconnected.*/function topoSort(nodes: Node[], edges: Edge[]): Node[] {const adj = new Map<string, string[]>();25 unmodified linesreturn order.map((id) => byId.get(id)!).filter(Boolean);}export function generatePythonScript(nodes: Node[],edges: Edge[],6 unmodified lines}));const lines: string[] = [];const imports = new Set<string>();// Headerlines.push(`"""`);2 unmodified lineslines.push(`"""`);lines.push(``);// Always need QuantumCircuitimports.add("from qiskit import QuantumCircuit");let hasBackend = false;// Scan what we need for imports.for (const b of blocks) {if (b.kind === "fake_backend" || b.kind === "ibm_backend") {hasBackend = true;}}// Imports sectionif (hasBackend) {imports.add("from qiskit_aer import AerSimulator");imports.add("from qiskit_aer.noise import NoiseModel");}lines.push([...imports].sort().join("\n"));lines.push(``);// Generate code for each blocklet stepNum = 0;for (const b of blocks) {stepNum++;const sep = `# ${"─".repeat(60)}`;lines.push(sep);switch (b.kind) {case "input_circuit": {lines.push(`# Step ${stepNum}: Load circuit`);if (sampleKey) {lines.push(`# Sample: ${sampleKey}`);lines.push(`# Option A: Load from a .qpy file`);lines.push(`# from qiskit import qpy`);lines.push(`# with open("${sampleKey}.qpy", "rb") as f:`);lines.push(`# qc = qpy.load(f)[0]`);lines.push(``);lines.push(`# Option B: Build programmatically (replace with your circuit)`);} else {lines.push(`# Replace with your circuit`);}lines.push(`qc = QuantumCircuit(4, name="my_circuit")`);lines.push(`# qc.ry(0.5, 0)`);lines.push(`# qc.cx(0, 1)`);lines.push(`# ... add your gates here`);lines.push(``);break;}case "fake_backend": {const name = String(b.params.backend_name ?? "FakeFez");const shots = Number(b.params.shots ?? 1024);lines.push(`# Step ${stepNum}: Noisy simulator (${name})`);lines.push(`from qiskit.providers.fake_provider import ${name}V2`);lines.push(`backend = ${name}V2()`);lines.push(`noise_model = NoiseModel.from_backend(backend)`);lines.push(`shots = ${shots} # user-set measurement count`);lines.push(``);break;}case "ibm_backend": {const name = String(b.params.backend_name ?? "ibm_fez");const shots = Number(b.params.shots ?? 1024);lines.push(`# Step ${stepNum}: IBM live backend (${name})`);lines.push(`# Requires: pip install qiskit-ibm-runtime`);lines.push(`# from qiskit_ibm_runtime import QiskitRuntimeService`);lines.push(`# service = QiskitRuntimeService(channel="ibm_quantum", token="YOUR_TOKEN")`);lines.push(`# backend = service.backend("${name}")`);lines.push(`# noise_model = NoiseModel.from_backend(backend)`);lines.push(`#`);lines.push(`# For now, falling back to fake backend:`);lines.push(`from qiskit.providers.fake_provider import FakeFezV2`);lines.push(`backend = FakeFezV2()`);lines.push(`noise_model = NoiseModel.from_backend(backend)`);lines.push(`shots = ${shots}`);lines.push(``);break;}case "qucad": {const iters = Number(b.params.iterations ?? 3);const lam = Number(b.params.lam ?? 0.005);const rho = Number(b.params.rho ?? 500.0);lines.push(`# Step ${stepNum}: QuCAD — noise-aware VQC sparsification`);lines.push(`from qlib.qucad import run_qucad_training_noisy`);lines.push(``);lines.push(`# Bind free parameters to zero if circuit is parameterized`);lines.push(`if qc.num_parameters > 0:`);lines.push(` qc_bound = qc.assign_parameters([0.0] * qc.num_parameters)`);lines.push(`else:`);lines.push(` qc_bound = qc`);lines.push(``);lines.push(`theta, mask, history = run_qucad_training_noisy(`);lines.push(` qc, noise_model, backend,`);lines.push(` iterations=${iters}, lam=${lam}, rho=${rho},`);lines.push(`)`);lines.push(`qc = qc.assign_parameters(theta * (mask != 0))`);lines.push(`print(f"QuCAD: kept {int((mask != 0).sum())}/{len(mask)} parameters")`);lines.push(``);break;}case "qubound": {const cacheBackend = String(b.params.cache_backend ?? "ibm_fez");const thresholdRaw = Number(b.params.threshold ?? 0);// 0 / negative disables pass/fail, matching the backend's// _build_summary contract.const threshold = thresholdRaw > 0 ? thresholdRaw : null;lines.push(`# Step ${stepNum}: QuBound — LSTM error-bound prediction`);lines.push(`from qlib.qbound import call_QuBound_from_cache`);lines.push(`from pathlib import Path`);lines.push(``);lines.push(`cache_path = Path("cache/ibm_history/${cacheBackend}.pkl")`);lines.push(`if qc.num_parameters > 0:`);lines.push(` qc_eval = qc.assign_parameters([0.0] * qc.num_parameters)`);lines.push(`else:`);lines.push(` qc_eval = qc`);lines.push(``);lines.push(`bound, model, meta = call_QuBound_from_cache(`);lines.push(` qc_eval, cache_path, reference_backend=backend if 'backend' in dir() else None,`);lines.push(`)`);lines.push(`print(f"QuBound predicted error bound: {bound:.6f}")`);if (threshold !== null) {lines.push(`threshold = ${threshold}`);lines.push(`passes = bound <= threshold`);lines.push(`margin = threshold - bound`);lines.push(`print(f" threshold {threshold}: {'PASS' if passes else 'FAIL'} (margin {margin:+.4f})")`,);}lines.push(``);break;}case "compvqc": {lines.push(`# Step ${stepNum}: CompressVQC — fold redundant gates`);lines.push(`from qlib.compvqc import get_LUT, quadraticProgram_luttoqp, admmOptimizedCompVQC, resultsCompressVQC`);lines.push(``);lines.push(`if qc.num_parameters > 0:`);lines.push(` comp_backend = backend if 'backend' in dir() else None`);lines.push(` if comp_backend is None:`);lines.push(` from qiskit.providers.fake_provider import FakeFezV2`);lines.push(` comp_backend = FakeFezV2()`);lines.push(` lut = get_LUT(qc, comp_backend)`);lines.push(` if lut:`);lines.push(` qp = quadraticProgram_luttoqp(qc, lut)`);lines.push(` result = admmOptimizedCompVQC(qp)`);lines.push(` qc = resultsCompressVQC(result, qc)`);lines.push(` print(f"CompressVQC: compressed circuit depth {qc.depth()}")`);lines.push(` else:`);lines.push(` print("CompressVQC: no compressible pairs found")`);lines.push(`else:`);lines.push(` print("CompressVQC: skipped (no parameterized gates)")`);lines.push(``);break;}case "qshot": {const snapshot = String(b.params.noise_snapshot ?? "pittsburgh_1");const alpha = Number(b.params.alpha ?? 0.95);lines.push(`# Step ${stepNum}: Qshot — noise-aware shot-count recommendation`);lines.push(`from qlib.qshot import get_recommender, resolve_noise_snapshot`);lines.push(``);lines.push(`if qc.num_parameters > 0:`);lines.push(` qc_shot = qc.assign_parameters([0.0] * qc.num_parameters)`);lines.push(`else:`);lines.push(` qc_shot = qc`);lines.push(``);lines.push(`noise_path = resolve_noise_snapshot("${snapshot}")`);lines.push(`recommender = get_recommender()`);lines.push(`result = recommender.predict(qc_shot, noise_path, alpha=${alpha})`);lines.push(`if result:`);lines.push(` print(f"Qshot: recommended {result['recommended_shots']} shots")`);lines.push(` print(f" predicted fidelity: {result['predicted_fidelity']:.4f}")`);lines.push(`else:`);lines.push(` print("Qshot: could not produce recommendation")`);lines.push(``);break;}case "fidelity": {const method = String(b.params.method ?? "statevector");const policy = String(b.params.unbound_param_policy ?? "bind_zero");lines.push(`# Step ${stepNum}: Fidelity estimate`);if (method === "sampled") {lines.push(`from qlib.qiskit_utils import sampledFidelityEstimator`,);lines.push(``);lines.push(`fidelity, meta = sampledFidelityEstimator(`,);lines.push(` qc,`);lines.push(` backend if 'backend' in dir() else None,`,);lines.push(` shots=shots if 'shots' in dir() else 1024,`,);lines.push(` unbound_param_policy="${policy}",`);lines.push(`)`);lines.push(`print(f"Fidelity (sampled, shots={meta['shots']}): {fidelity:.6f}")`,);} else {lines.push(`from qlib.qiskit_utils import simpleFidelityEstimator`,);lines.push(``);lines.push(`fidelity, meta = simpleFidelityEstimator(`,);lines.push(` qc, unbound_param_policy="${policy}",`,);lines.push(`)`);lines.push(`print(f"Fidelity (noiseless statevector): {fidelity:.6f}")`,);}lines.push(``);break;}case "output": {lines.push(`# Step ${stepNum}: Output summary`);lines.push(`print("\\n" + "=" * 60)`);lines.push(`print(f"Final circuit: {qc.num_qubits}q, depth {qc.depth()}, {qc.size()} gates")`);lines.push(`print(f"Gate counts: {dict(qc.count_ops())}")`);lines.push(`print(qc.draw(output='text', fold=120))`);lines.push(``);break;}}}// Footerlines.push(`# ${"─".repeat(60)}`);8 unmodified lines910111213141516171819205 unmodified lines26272829303132333435363738394041424325 unmodified lines697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922936 unmodified lines3003013023033043052 unmodified lines3083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373388 unmodified lines* We deliberately keep the generated code flat and readable (no* classes, no abstractions) so someone unfamiliar with the codebase* can follow it line by line.** Architecture: one ``Emitter`` per node kind. Each emitter is a pure* function from (params, stepNum, ctx) to a list of source lines. The* main loop walks the topo-sorted nodes, dispatches to the emitter,* and concatenates. To support a new node kind, add one entry to* ``EMITTERS``.*/import type { Node, Edge } from "@xyflow/react";5 unmodified linesparams: Record<string, unknown>;}interface EmitContext {/** Filename suggestion for an Option A QPY load. */sampleKey: string | null;}type Emitter = (b: PipelineNode, stepNum: number, ctx: EmitContext) => string[];// ---- topology helper -----------------------------------------------------/*** Topological sort of canvas nodes using the edge list.* Falls back to catalog order if the graph is disconnected.*/function topoSort(nodes: Node[], edges: Edge[]): Node[] {const adj = new Map<string, string[]>();25 unmodified linesreturn order.map((id) => byId.get(id)!).filter(Boolean);}// ---- emitters: one per node kind -----------------------------------------//// Each emitter returns ONLY the body lines for its step — the main// loop handles the leading "# Step N: <title>" header and a trailing// blank line. Keep each emitter self-contained so adding a new node// kind is a strictly additive change.function asStr(v: unknown, dflt: string): string {return typeof v === "string" && v.length > 0 ? v : dflt;}function asNum(v: unknown, dflt: number): number {return typeof v === "number" && Number.isFinite(v) ? v : dflt;}const emitInputCircuit: Emitter = (_b, _step, { sampleKey }) => {const lines: string[] = [];if (sampleKey) {lines.push(`# Sample: ${sampleKey}`);lines.push(`# Option A: Load from a .qpy file`);lines.push(`# from qiskit import qpy`);lines.push(`# with open("${sampleKey}.qpy", "rb") as f:`);lines.push(`# qc = qpy.load(f)[0]`);lines.push(``);lines.push(`# Option B: Build programmatically (replace with your circuit)`);} else {lines.push(`# Replace with your circuit`);}lines.push(`qc = QuantumCircuit(4, name="my_circuit")`);lines.push(`# qc.ry(0.5, 0)`);lines.push(`# qc.cx(0, 1)`);lines.push(`# ... add your gates here`);return lines;};const emitFakeBackend: Emitter = (b) => {const name = asStr(b.params.backend_name, "FakeFez");const shots = asNum(b.params.shots, 1024);return [`from qiskit.providers.fake_provider import ${name}V2`,`backend = ${name}V2()`,`noise_model = NoiseModel.from_backend(backend)`,`shots = ${shots} # user-set measurement count`,];};const emitIbmBackend: Emitter = (b) => {const name = asStr(b.params.backend_name, "ibm_fez");const shots = asNum(b.params.shots, 1024);return [`# Requires: pip install qiskit-ibm-runtime`,`# from qiskit_ibm_runtime import QiskitRuntimeService`,`# service = QiskitRuntimeService(channel="ibm_quantum", token="YOUR_TOKEN")`,`# backend = service.backend("${name}")`,`# noise_model = NoiseModel.from_backend(backend)`,`#`,`# For now, falling back to fake backend:`,`from qiskit.providers.fake_provider import FakeFezV2`,`backend = FakeFezV2()`,`noise_model = NoiseModel.from_backend(backend)`,`shots = ${shots}`,];};const emitQucad: Emitter = (b) => {const iters = asNum(b.params.iterations, 3);const lam = asNum(b.params.lam, 0.005);const rho = asNum(b.params.rho, 500.0);return [`from qlib.qucad import run_qucad_training_noisy`,``,`# Bind free parameters to zero if circuit is parameterized`,`if qc.num_parameters > 0:`,` qc_bound = qc.assign_parameters([0.0] * qc.num_parameters)`,`else:`,` qc_bound = qc`,``,`theta, mask, history = run_qucad_training_noisy(`,` qc, noise_model, backend,`,` iterations=${iters}, lam=${lam}, rho=${rho},`,`)`,`qc = qc.assign_parameters(theta * (mask != 0))`,`print(f"QuCAD: kept {int((mask != 0).sum())}/{len(mask)} parameters")`,];};const emitQubound: Emitter = (b) => {const cacheBackend = asStr(b.params.cache_backend, "ibm_fez");const threshRaw = asNum(b.params.threshold, 0);// 0 / negative disables pass/fail, matching the backend's// _build_summary contract.const threshold = threshRaw > 0 ? threshRaw : null;const lines = [`from qlib.qbound import call_QuBound_from_cache`,`from pathlib import Path`,``,`cache_path = Path("cache/ibm_history/${cacheBackend}.pkl")`,`if qc.num_parameters > 0:`,` qc_eval = qc.assign_parameters([0.0] * qc.num_parameters)`,`else:`,` qc_eval = qc`,``,`bound, model, meta = call_QuBound_from_cache(`,` qc_eval, cache_path, reference_backend=backend if 'backend' in dir() else None,`,`)`,`print(f"QuBound predicted error bound: {bound:.6f}")`,];if (threshold !== null) {lines.push(`threshold = ${threshold}`,`passes = bound <= threshold`,`margin = threshold - bound`,`print(f" threshold {threshold}: {'PASS' if passes else 'FAIL'} (margin {margin:+.4f})")`,);}return lines;};const emitCompvqc: Emitter = () => [`from qlib.compvqc import get_LUT, quadraticProgram_luttoqp, admmOptimizedCompVQC, resultsCompressVQC`,``,`if qc.num_parameters > 0:`,` comp_backend = backend if 'backend' in dir() else None`,` if comp_backend is None:`,` from qiskit.providers.fake_provider import FakeFezV2`,` comp_backend = FakeFezV2()`,` lut = get_LUT(qc, comp_backend)`,` if lut:`,` qp = quadraticProgram_luttoqp(qc, lut)`,` result = admmOptimizedCompVQC(qp)`,` qc = resultsCompressVQC(result, qc)`,` print(f"CompressVQC: compressed circuit depth {qc.depth()}")`,` else:`,` print("CompressVQC: no compressible pairs found")`,`else:`,` print("CompressVQC: skipped (no parameterized gates)")`,];const emitQshot: Emitter = (b) => {const snapshot = asStr(b.params.noise_snapshot, "pittsburgh_1");const alpha = asNum(b.params.alpha, 0.95);return [`from qlib.qshot import get_recommender, resolve_noise_snapshot`,``,`if qc.num_parameters > 0:`,` qc_shot = qc.assign_parameters([0.0] * qc.num_parameters)`,`else:`,` qc_shot = qc`,``,`noise_path = resolve_noise_snapshot("${snapshot}")`,`recommender = get_recommender()`,`result = recommender.predict(qc_shot, noise_path, alpha=${alpha})`,`if result:`,` print(f"Qshot: recommended {result['recommended_shots']} shots")`,` print(f" predicted fidelity: {result['predicted_fidelity']:.4f}")`,`else:`,` print("Qshot: could not produce recommendation")`,];};const emitFidelity: Emitter = (b) => {const method = asStr(b.params.method, "statevector");const policy = asStr(b.params.unbound_param_policy, "bind_zero");if (method === "sampled") {return [`from qlib.qiskit_utils import sampledFidelityEstimator`,``,`fidelity, meta = sampledFidelityEstimator(`,` qc,`,` backend if 'backend' in dir() else None,`,` shots=shots if 'shots' in dir() else 1024,`,` unbound_param_policy="${policy}",`,`)`,`print(f"Fidelity (sampled, shots={meta['shots']}): {fidelity:.6f}")`,];}return [`from qlib.qiskit_utils import simpleFidelityEstimator`,``,`fidelity, meta = simpleFidelityEstimator(`,` qc, unbound_param_policy="${policy}",`,`)`,`print(f"Fidelity (noiseless statevector): {fidelity:.6f}")`,];};const emitOutput: Emitter = () => [`print("\\n" + "=" * 60)`,`print(f"Final circuit: {qc.num_qubits}q, depth {qc.depth()}, {qc.size()} gates")`,`print(f"Gate counts: {dict(qc.count_ops())}")`,`print(qc.draw(output='text', fold=120))`,];const STEP_TITLES: Record<NodeKind, string> = {input_circuit: "Load circuit",fake_backend: "Noisy simulator",ibm_backend: "IBM live backend",qucad: "QuCAD — noise-aware VQC sparsification",qubound: "QuBound — LSTM error-bound prediction",compvqc: "CompressVQC — fold redundant gates",qshot: "Qshot — noise-aware shot-count recommendation",fidelity: "Fidelity estimate",output: "Output summary",};const EMITTERS: Record<NodeKind, Emitter> = {input_circuit: emitInputCircuit,fake_backend: emitFakeBackend,ibm_backend: emitIbmBackend,qucad: emitQucad,qubound: emitQubound,compvqc: emitCompvqc,qshot: emitQshot,fidelity: emitFidelity,output: emitOutput,};// ---- main entry ----------------------------------------------------------export function generatePythonScript(nodes: Node[],edges: Edge[],6 unmodified lines}));const lines: string[] = [];// Headerlines.push(`"""`);2 unmodified lineslines.push(`"""`);lines.push(``);// Imports. QuantumCircuit is always needed; AerSimulator + NoiseModel// come along for any backend block. Detailed qlib imports are emitted// inline in each step's body so unused steps don't leave dead imports.const imports = new Set<string>(["from qiskit import QuantumCircuit"]);const hasBackend = blocks.some((b) => b.kind === "fake_backend" || b.kind === "ibm_backend",);if (hasBackend) {imports.add("from qiskit_aer import AerSimulator");imports.add("from qiskit_aer.noise import NoiseModel");}lines.push([...imports].sort().join("\n"));lines.push(``);const sep = `# ${"─".repeat(60)}`;const ctx: EmitContext = { sampleKey };blocks.forEach((b, i) => {const stepNum = i + 1;const emitter = EMITTERS[b.kind];if (!emitter) return; // Plugin / unknown — skip silently.lines.push(sep);lines.push(`# Step ${stepNum}: ${STEP_TITLES[b.kind] ?? b.kind}`);lines.push(...emitter(b, stepNum, ctx));lines.push(``);});// Footerlines.push(`# ${"─".repeat(60)}`);