Commit History
-
Precomputed cache: schema gate + live-API regeneration
TheYuchenThe 36 shipped entries predated the provenance rework (no transformation/distribution/seed fields) yet still validated as RunResponses, so a hit would render a crippled first run. Worse-and- better at once: every key was already unreachable — the key hashes QPY bytes (changed by the qiskit upgrade) and the script's preset mirror had drifted from the frontend's defaultData (JS `500` vs Python `500.0`, missing fidelity params). * run_cache: stamp cache_schema=2 on write, treat unstamped/old entries as misses (logged once per key); writes scrub the seed envelope (disk cache is seed-free by design; per-step seed_used stays as the honest record). 6 new unit tests; lane now 86 green. * Delete the 36 dead files; regenerate qucad+compvqc x 9 samples (18 entries) from the LIVE Space via the new resumable scripts/regenerate_precomputed_cache_live.py, which refuses to run unless local qiskit == live /api/health qiskit (key parity). Torch-heavy presets (qubound/qshot/full) stay unca…61a5f88 -
Audit C1: pinned step-cache identity includes node ids
TheYuchenPer-node seeds derive from sha256(root_seed:node_id), but the step cache's _prefix_hash keyed only {type, data} per node — so two id-renamed, structurally identical graphs under the same pinned seed shared cache entries while owing DIFFERENT draws (live-demonstrated cross-graph poisoning: run B was served run A's seeded numbers). Fix: in the salted (seed-pinned) regime the per-node hash payload now includes the node id — node ids are part of seed identity. The fresh (unsalted) regime stays id-free on purpose: fresh runs never cache stochastic steps, so id-blind prefix sharing is sound there and the precomputed/prewarm namespace is untouched. Regression tests: pinned hash is id-sensitive, fresh hash stays id-blind, plus an executor-level same-seed a1-vs-b1 test asserting the renamed graph executes with its OWN derived seed (no poisoned cache hit) and then replays bit-exactly from its own entry. Lane: 80 green.d5ab6bd -
Audit fixes: cache-hit node_id re-stamp, anon key, honest copy
TheYuchen* workflow_service: a step-cache hit now re-stamps the CURRENT node's id onto the served StepResult. The prefix hash ignores node ids, so a cached step written by a graph with different ids was served verbatim (live-reproduced: an s1..s5 scenario run poisoned a n1..n5 archive replay, which came back with node_ids s1..s3 the frontend cannot map). NOTE this fix only repairs the id, not the deeper pinned-cache identity hole — per-node seeds derive from node ids but the pinned cache key does not include them, so structurally-identical graphs with different ids can still serve each other's draws under the same root seed (see audit report). * FlowCanvas: ribbon-legend localStorage key renamed quaim-* -> quda.* ("quaim" matched the identifying Space slug and shipped in the VITE_ANON bundle, contradicting the doc's anon-audit claim). * scenarios/doc: F3's expected stop corrected to the value the live API actually produces (2,560 of 4096 shots; 512-shot batch granulari…18ca665
-
Wave I: anytime evidence steering (live CIs, optional stopping)
TheYuchenBackend: sampled fidelity always runs as B=min(8,max(2,shots//128)) batches; batch i seeded sha256(f"{node_seed}:batch:{i}") so replays are bit-exact regardless of any run's stopping point. Streaming SSE interleaves {"step_progress": {node_id, batch_i, n_batches, shots_done, successes, point, ci95}} frames (worker thread + queue in the executor; eager path unaffected). RunRequest.precision_target (CI half-width, (0,0.5]) = server-honoured optional stopping, min 2 batches; distribution records shots executed vs requested, stopped_early, and the full per-batch trace. qlib duplicates the Wilson fn (no app import from qlib); twins pinned equal by test. Frontend: toolbar precision-target select (off/±5/±2/±1pp); live narrowing CI band + shot counter on node faces from streamed frames; evidence-funnel in the fidelity card (one line per batch, opacity ramp, target ticks at point±target, early-stop annotation); RunRecord persists precision_target + stopped_early; restore/replay writes the tar…7fa375a -
Memoize fake-backend noise models; first-visit demo archive machinery
TheYuchenBackend: AerSimulator.from_backend / NoiseModel.from_backend rebuilt the full 100+ qubit device noise model on every sampled-fidelity and QuCAD step (~40-90 s of GIL-bound Python per fresh run — the dominant cost of every uncached run on the Space). Fake* snapshots are frozen, so the derived model is memoized by backend name (live IBM backends never cached). qlib/qiskit_utils.aer_simulator_for / noise_model_for. Frontend: plumbing for a bundled first-visit evidence archive — RunRecord.demo flag, lib/demoArchive.ts (ensureDemoArchive imports data/demoArchive.json via buildRunRecord on first visit only, decided flag quda-demo-decided, clearDemoRuns), DemoArchiveBanner on the Multiverse board + History tab, per-row demo chip, multiverse landing for first visits, welcome-slide tagline reframed to the evidence story. Archive JSON itself ships in the next commit (placeholder []).b84dc32 -
Seed coverage for QuBound/Qshot + cost estimates from run history
TheYuchenCloses the two remaining claim-integrity gaps for "every run is exactly replayable" over "stochastic, costly experiments": Seeds. QuBound trains its LSTM on BOTH ok paths (live IBM history and the cached 14-day pickle) — there is no precomputed-only branch in the handler — so both now seed the global RNGs (_seed_stochastic_libs: random + numpy + lazily-imported, try/except-guarded torch) and thread node_seed into qlib (Aer seed_simulator + Sabre seed_transpiler in get_labels_fromNoise); results carry nondeterministic=True + seed_used. Qshot's pilot seed was 99991 + hash(str(base)) — str hashes are PYTHONHASHSEED-salted, i.e. "fixed" only until the next server restart. pilot_seed is now threaded predict → recommend_shots → compute_pilot_pf, making the recommendation reproducible across processes given the seed. Executor cache logic untouched: fresh runs draw fresh node seeds (honest new draw, cache-bypassed), pinned runs re-derive the same seeds (cacheable in the seed-salted namespace)…91b2cd9 -
Gate-level circuit diff: qubit-lane LCS alignment per step
TheYuchenBackend: - New services/circuit_diff.py: lane_sequences() tokenizes each qubit's gate sequence (name + 3dp param fingerprint; unbound params keep symbol names; 2q gates on both lanes with c/t role tags, symmetric ops undecorated; measures kept, barriers skipped) and diff_lanes() aligns before/after lanes with a standard LCS diff (kept/removed/added in merged order). Hard cap 12 qubits / 600 combined ops -> truncated marker. - Executor: copy the circuit BEFORE dispatch (handlers may mutate ctx["circuit"] in place -- the historical QuBound measure_all bug shape), stamp gate_diff into StepResult.transformation when the step changed the circuit. Best-effort: any diff failure is logged and omitted, never breaks a run. - tests/test_gate_diff.py: 14 torch-free unit tests incl. an executor wiring test that mutates in place. Frontend: - New CircuitDiff.tsx inside SignatureCard, collapsed <details> ("Gate-level diff / N removed / M added"): one mono-labelled row per qu…94e47b0 -
Transformation signatures: uniform circuit-delta vocabulary per step
TheYuchenPhase 2 (part 1) of the evidence-workbench rework. The executor now snapshots the circuit's structure (shape + gate counts by op) before and after every dispatched node and stamps a uniform transformation payload onto each successful StepResult: before/after snapshots, shape delta (qubits/depth/gates/params), per-op count delta, and a changed flag distinguishing pass-through steps from mutating ones. Captured centrally — handlers (and user plugins) never build this themselves, which is what keeps the vocabulary identical across QuCAD pruning, CompVQC folding, transpiles, and anything a plugin does. Kind-specific detail stays in each handler's summary. Frontend renders it at two densities: SignatureTile on canvas nodes (nonzero delta channels only, e.g. "D-4 G-12 P-12"; decrease=green since every optimizer in the catalog aims downward, increase=amber, qubit-width neutral) and SignatureCard in the results pane (before → after per channel + per-op chips). Pass-through steps say so expli…f956d64 -
Provenance core: run identity, replayable seeds, distribution payloads
TheYuchenPhase 0 of the evidence-workbench rework. Every run now gets a server-stamped provenance envelope (run_id, seed_mode, root_seed, app_version) in both the eager and SSE routes; the SSE stream opens with a run_meta event. Every run draws a root seed even when the caller doesn't pin one, so any historical run is replayable later by sending its recorded seed back. Per-node seeds derive from sha256(root_seed, node_id) — independent of execution order and of unrelated graph edits, keeping A/B comparisons honest. Sampled fidelity accepts the seed (seed_simulator) and reports a structured distribution payload: binomial successes/shots, Wilson 95% CI, top-16 outcome histogram. Cache semantics: seed-pinned runs live in a salted cache namespace and may cache stochastic steps (reproducible by construction); fresh runs keep today's namespace and the nondeterministic bypass. Precomputed disk-cache responses are never served for pinned runs. 19 new unit tests (seed derivation, Wilson edges, salted…2efd890
-
Polish pass: dedupe pipeline runners, shared chip component, emitter map
Yuchen YuanThree 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 …4ee621f -
Code quality cleanup + first unit-test seed
Yuchen YuanPost-audit polish on the bug-fix wave from the last 9 commits: * Hoist function-level constants to module top so they're discoverable and reusable: _FAKE_BACKENDS_AVAILABLE, _FIDELITY_METHODS, _FIDELITY_UNBOUND_POLICIES, _COMPVQC_MAX_QP_VARS, _COMPVQC_ROTATION_GATES. * Move 'import re' from inside _format_exception_for_user to the file's top-level imports. * Standardise validation error phrasing on 'Choose one of: ...' (was a mix of 'Allowed values:' and 'Choose one of:'). * Add the same name-validation rigour to _handle_ibm_backend that _handle_fake_backend has — refuse empty / non-string names with a clear message, and surface IBM's resolution failure through _format_exception_for_user instead of letting it bubble as a 500. * Drop the now-unused '_qpy_bytes' alias from run_cache.py; the one remaining call site uses the canonical name directly. * Drop the trivial _is_known_fake_backend wrapper; inline the membership test at the one …6962cb3 -
Invalidate step cache when a plugin is (re-)installed
Yuchen YuanIf a user re-uploads a plugin with the same kind + params, every in-memory step-cache entry whose prefix covered that kind would otherwise stay valid — the next run hit-served a result computed by the OLD plugin code. Confirmed by code review: install_plugin_zip overwrote the on-disk handler but never touched _step_cache. Fix is a sidecar map of prefix_key → set of node types covered by that prefix. _cache_put populates it; install_plugin_zip calls a new invalidate_step_cache_for_node_type(kind) helper to evict any entry that includes the affected kind. LRU eviction was updated to drop both the cache entry and the sidecar entry in sync. Unit-tested locally (4 scenarios: plugin invalidate, builtin invalidate, no-match, LRU sync) — all green.0894ed2 -
Surface graph-cycle errors as 422 instead of 500
Yuchen YuanA8 degenerate-graph probing: a cyclic node graph (A→B→A) made topological_order raise ValueError, which propagated as an HTTP 500. The user saw 'Internal Server Error' with no diagnosis. Catch ValueError in both /workflow/run and /workflow/run-stream and return 422 with the actual cycle/malformed-graph message. For the stream route, pre-flight the topological sort BEFORE opening the stream — otherwise the error would happen mid-stream with an empty SSE response and no status code surface. Other A8 cases (empty graph, output-only, two inputs, disconnected nodes) all returned reasonable results without crashes.fa31bfd -
Validate fidelity method + fake-backend name; refuse unknown strings
Yuchen YuanA4 fuzzing found three silent-coerce UX cracks: * backend_name='FakeBollywood' silently fell back to FakeFez * backend_name='' (empty) silently fell back to FakeFez * method='banana' on Fidelity silently picked statevector In all three the run reported ok and produced a number — but the number was for inputs the user didn't ask for. That's worse than erroring: it pretends to have done what was requested. Replace the silent coerce with explicit validation. Allowed values are enumerated in the error message so the user knows what to type. Also surface the same hardening on unbound_param_policy (same enum trap pattern).8a2d350 -
Stop the chain when a handler returns status='error'
Yuchen YuanHandlers signal failure two ways: by raising (caught + converted to status='error' in the loop) or by returning a StepResult with status='error' directly (e.g. QuCAD's 'needs a backend upstream'). Only the raise path was breaking the loop. A direct-return error let downstream steps execute on whatever ctx['circuit'] the failed upstream had left alone, silently producing misleading metrics (e.g. Fidelity reporting the input circuit's fidelity rather than the algorithm-transformed one). Live repro before fix: efficient_su2_4q → QuCAD (no backend) → Fidelity → Output ran all four steps; Fidelity returned the input-circuit fidelity even though the chain logically failed. Now: status='error' is honoured in both run_pipeline and run_pipeline_stream the same way as an exception. status='skipped' (e.g. CompVQC scale-guard) still continues — ctx is still valid.102bda8 -
QuBound: stop mutating caller's QuantumCircuit + handler defensive copy
Yuchen YuanQuBound's get_labels_fromNoise called qc.measure_all() in place to attach measurements for the Aer shots that train the LSTM. The comment said 'caller doesn't reuse qc after this point' — but the pipeline runner does: ctx['circuit'] points to the same object, so the measurement register leaked into every downstream step. Reproduction on the live server (ry_chain_6q → QuCAD → QuBound → Qshot → Fidelity → Output): Qshot crashed with 'ValueError: invalid literal for int() with base 2: "110100…"' because the counts string suddenly had a 'classical_register meas' delimiter splitting it. Two-layer fix: 1. qbound.get_labels_fromNoise now copies qc before measure_all. 2. _handle_qubound also copies ctx['circuit'] defensively when num_parameters == 0 (when >0, assign_parameters already returns a fresh circuit). Belt + suspenders so any future in-place mutation deeper inside QuBound still can't leak. Audited sampledFidelityEstimator and qshot recommender — both already copy…1c02f7a -
CompVQC scale-guard: count actual rotation instances, not unique Params
Yuchen Yuan524cb79 -
Surface real exception detail + add CompVQC scale guard
Yuchen YuanTwo ergonomics fixes triggered by trying to chain all algorithms on a parametric circuit: 1. Built-in handler crashes used to say 'see the run log for details' — but HF Spaces don't expose log surfaces to end users. Now bubble the exception class + first line of str(exc) (path-sanitised, 240-char cap) into the user-facing message. Server-side traceback logging is unchanged. 2. CompressVQC silently exploded on any non-trivial parametric input (ValueError: Maximum allowed dimension exceeded — QAOA tried to allocate 2^120 statevector for a 24-rotation EfficientSU2). Add an explicit pre-flight guard: skip with an actionable message if the QUBO would have > 22 binary variables. Locally reproduced the 512 GiB allocation attempt that confirmed the limit. Tested locally: ValueError formatter strips paths, leaves message intact. qaoa_maxcut_4 → 35 vars → would have crashed; now skips cleanly. vqc_2q_small (10 vars) still passes through to the solver.9f61265 -
Tighten nondeterministic guard: set flag before put + evict stale entries
Yuchen YuanV1 of this fix wrote the nondeterministic step itself to the cache because the flag was set after _cache_put. Subsequent runs lookup-hit and served the frozen draw — same bug we were trying to fix. V2: set the sticky flag BEFORE _cache_put, mirror the same change on the plugin path, and refuse to lookup-hit any cached entry whose own nondeterministic flag is True (defense against legacy entries from the v1 deploy that already populated the cache before this commit).146c829 -
Fix sampled fidelity being frozen by the per-node step cache
Yuchen YuanThe SSE run path caches each step's StepResult+ctx snapshot keyed on the pipeline prefix. For deterministic blocks (statevector fidelity, QuCAD output, etc.) that's a feature: re-runs reuse the trained model or computed metric. For sampled fidelity it was a silent scientific bug — the first shot draw got frozen and replayed forever. Reproduced live: 5 SSE runs of bell + FakeFez + fidelity(method=sampled) returned identical 0.5938 with from_step_cache=true after the first run. Fix: handlers can mark a StepResult as nondeterministic. The stream loop carries a sticky flag — once a nondeterministic step is emitted, both cache lookups AND cache puts are disabled for the rest of that run, including all downstream steps (their ctx depends on the fresh draw, so a lookup hit would restore a contradictory state). Frontend renders a 'live' chip on those steps so users know the cache is intentionally bypassed. Statevector fidelity is unchanged (still cacheable). QuBound / Qshot / QuCAD are als…b3ebd47
-
Fix Fidelity on parameterized circuits + QuBound threshold + Backend shots
Yuchen Yuan +1: Claude Opus 4.7 (1M context)Three user-reported issues, all addressed with proper logging and actionable error surfaces. Issue 1 — Fidelity crashed on parameterized circuits simpleFidelityEstimator used Statevector.from_instruction(qc), which refuses circuits with unbound parameters. ry_chain_6q has 12 such parameters; Fidelity throw "TypeError: Parameter expression with unbound parameters … is not numeric" which surfaced as a generic "unexpected error" in the result card. The estimator now takes an `unbound_param_policy` argument: * "bind_zero" (default) — auto-binds free params to 0, matching the convention QuBound already uses internally, and reports `bound_unbound_to_zero: N` in the summary so the user sees what we did. * "error" — refuses and raises UnboundParametersError with the actionable message naming the offending param count and suggesting the upstream fix. _handle_fidelity catches UnboundParametersError specifically and maps it to a clean error step (the message is shown v…286193c
-
Canvas becomes data-aware: shapes, headline metrics, perf tint, pre-flight
Yuchen Yuan +1: Claude Opus 4.7 (1M context)After a Run, the canvas itself shows what's happening at every node and every edge — instead of just being a connection diagram with the real numbers banished to a sidebar. circuit_shape on every StepResult (backend) StepResult schema gains a CircuitShape sidecar field ({num_qubits, depth, size, num_parameters}). workflow_service snapshots ctx["circuit"] AFTER every successful handler and attaches it to the step. Built-in handlers and plugin steps both populate; ctx-less steps (source plugins with no upstream, errored steps) leave it as None. Edge data-flow labels (frontend) styledEdges memo in FlowCanvas reads the SOURCE node's circuit_shape and attaches a tiny monospace label to the React Flow edge: "5q · d8 · 17g". Falls back to no label when the source step doesn't have a shape (no run yet, or source errored). Drop-target highlight during drag-to-insert composes on top. Per-node headline metric + duration chip + tone (frontend) New lib/headlineMetric.ts table picks the most r…33e7bee -
Global code-quality polish: DRY + named constants + leak cleanup
Yuchen Yuan +1: Claude Opus 4.7 (1M context)Targeted refactor pass based on a structured audit. Pure maintainability wins; no behaviour changes. Frontend: collapse 8 popovers into one hook 8 components (AuthButton, ThemeSwitcher, MoreMenu, PapersPopover, SupportPopover, DevelopersPopover, BlockPicker, PresetPicker) each carried an identical 16-line "close on mousedown + Escape" effect block. Extracted to lib/useDismissOn.ts; ~150 lines deleted, one hook to audit instead of eight. useDismissOn(open, rootRef, useCallback(() => setOpen(false), [])) Behaviour is intentionally identical to the inlined block so older git-blame on the call sites stays coherent. Backend: consolidate effective-user-id resolution routes/plugins.py and routes/workflow.py each carried a subtly different implementation of "session cookie wins over query_user_id, anon hf_ prefix is reserved". Pulled into auth_service.resolve_effective_user_id(request, query, *, required). - required=True path raises ValueError → routes/plugins maps to 400 - required=…57f0b3e -
Plugin output: typed figures (markdown / table / bar / svg / png)
Yuchen Yuan +1: Claude Opus 4.7 (1M context)Plugins can now emit a list of typed visual outputs beyond the flat summary dict. Each figure is a small JSON object with a `type` field; the result card renders them inline below the summary table. Five types ship today - markdown — headings, lists, bold/italic/code, fenced code blocks. Raw HTML is rejected by the backend; the frontend renderer never reaches for dangerouslySetInnerHTML on this path. - table — headers (≤ 12 cols) + rows (≤ 100 rows), primitives only. - bar — inline SVG bar chart, up to 50 bars, zero JS deps. - svg — escape hatch with sanitisation: rejects <script>, javascript:, <foreignObject>, <iframe>, <object>, <embed>, and any on*= event-handler attribute. Up to 256 KB. - image_png_b64 — base64-encoded PNG, ≤ 1 MB decoded, must have the PNG magic bytes (JPEG/GIF/other formats rejected). Each figure also accepts an optional `title` (≤ 120 chars) rendered as the panel header. Total `figures` list capped at 10 entries. Backend - New plugin_run…725a720 -
Engineering hardening: PKCE + HF Datasets 412 retry
Yuchen Yuan +1: Claude Opus 4.7 (1M context)PKCE (RFC 7636) on OAuth flow The state cookie alone wasn't browser-bound — an attacker who could plant cookies on the Space's domain (e.g. via HTTPS-stripping proxy) could forge a matching state value. PKCE closes this: - /login mints a 64-byte code_verifier alongside the random state, computes code_challenge = base64url(sha256(verifier)), and stores state + verifier together in the signed cookie. - The /authorize URL passed to HF includes code_challenge=...& code_challenge_method=S256. - /callback retrieves the verifier from the signed cookie and POSTs it along with the code to /oauth/token. HF re-hashes it server-side and rejects the exchange if it doesn't match the original challenge. - A forged state cookie now needs the matching verifier to even attempt the exchange — and since the cookie binds them together, forging both requires the original itsdangerous secret. decode_state now returns (state, verifier) — both must validate; if either is missing or the cookie …ad3c861
-
Full audit pass: leak fixes, sign-in clarity, functional bugs
Yuchen Yuan +1: Claude Opus 4.7 (1M context)Triggered by user request "全方位的检查、测试" covering visualization, user comprehension, page logic, ease-of-use, science, info leakage, and security. Three parallel audits ran (info-leak, sign-in clarity, visual/a11y, functional/scientific); fixes batched below. Critical functional bugs - workflow_service.run_pipeline + run_pipeline_stream now call plugin_service.hydrate_from_dataset_if_needed before dispatch. Without this, a logged-in user running a pipeline on a fresh container (or on the mirror Space) would see "plugin not found" even though it sits safely in their HF Datasets backing store. - plugin_runner._scrub_scalars / _scrub_value drop NaN and ±Inf instead of passing them through. Standard JSON has no representation for either; model_dump_json emits NaN/Infinity which the browser's JSON.parse refuses, so any plugin returning a numerically degenerate scalar used to make the entire /run response fail to parse client- side. NaN → dropped from scalars dict; Inf → nul…4c566b4 -
Multi-user: HF OAuth login + per-user plugin persistence
Yuchen Yuan +1: Claude Opus 4.7 (1M context)What this lets users do - Anyone can click "Sign in" in the top bar and authenticate with their Hugging Face account (OpenID Connect via the HF OAuth flow). No account creation, no password management on our side. - Each signed-in user gets their own private namespace for uploaded plugins. Other users (and other browsers from the same person) cannot see them. - Plugins uploaded while signed in are mirrored to a private HF Dataset repo (qudastudio/quda-user-data) so they survive container restarts and follow the user across devices. - Guest (anonymous) mode is fully preserved: visitors can still drop a .zip without signing in; those plugins continue to live in /tmp and are per-browser, exactly as before. Architecture Browser ──cookie──▶ FastAPI ──HfApi──▶ HF Dataset (private) │ └──▶ /tmp (volatile cache) Identity = session cookie's hf_<username> (when signed in) ∥ anon UUID query par…b6faf15 -
Polish pass on plugin Upload modal
Yuchen Yuan +1: Claude Opus 4.7 (1M context)Detail review surfaced four small but meaningful items. Storage listener over-fires (App.tsx) - Was triggered by any quda.* key — included pane widths, theme, live-IBM toggle. Tightened to e.key === "quda.pluginsRev" so only actual plugin upload/delete events refetch. bumpPluginsRev() already writes that exact key. Duplicate-install regex collision (UploadPluginModal) - /already have a plugin/i matched both the per-kind duplicate AND the 5-plugin cap message, so a user at cap who clicked Install on a sample saw a green success banner. Tightened to /already have a plugin with kind=/i so only the idempotent case surfaces as a friendly hint; the cap is now an honest error. - Added a Content-Type guard after the example zip fetch so a captive portal serving an HTML 200 surfaces "got <type>, not a .zip" instead of the confusing manifest-parse error from the backend. Modal UX restructure - Examples-first ordering when installedPlugins.length === 0 — a first-time visito…4d0158a -
Bundled example plugins + UX polish from second audit pass
Yuchen Yuan +1: Claude Opus 4.7 (1M context)Lets users try the plugin upload flow end-to-end without writing one from scratch: the Upload modal now shows a "Try with a sample" section that fetches /api/plugins/examples and offers per-example Install + .zip download buttons. Backend: - New read-only GET /api/plugins/examples returns minimal metadata parsed from each bundled zip's manifest.json (label, family, tagline, color, size). Catalog is empty if the examples dir is missing. - New read-only GET /api/plugins/examples/{name}.zip returns the raw zip bytes. Name is constrained to `^[a-z][a-z0-9_]{0,30}$`; resolved path must stay inside the examples dir (defence in depth against symlink shenanigans). 400 on bad name, 404 on missing or escaped path. - manifest.json read inside the zip capped at 64 KB so a malformed bundled example can't allocate unboundedly. - Defensive comment about route ordering vs the path-param DELETE. - Dockerfile COPYs example_plugins/ into the runtime image so the endpoints have content to s…ef8bb5f -
Plugin protocol Phase 5: final audit fixes + polish
Yuchen Yuan +1: Claude Opus 4.7 (1M context)Defence-in-depth fixes from the security/UX/scientific audits: Backend safety: - Reject `\` and absolute paths in zip entry names (defensive even on Linux containers). - Cap stdin payload at 50 MB in the subprocess wrapper before parsing. - Drop the full `/tmp/quda_plugins/<user>/<kind>/` path from the "handler.py missing" error message — user already knows their kind. Frontend UX: - QNode now renders a red-bordered tombstone card with a "?" badge and a "plugin not installed" hint when a referenced plugin has been deleted, instead of silently disappearing. - App.tsx listens for `storage` events on `quda.*` keys to refresh the plugin list across tabs. - UploadPluginModal title now reads "Upload your own block" with a one-line explanation of what plugins do. - TrySlide adds a "Upload your own block" tip alongside the Export .py one so new users discover the plugin workflow. Docs: - README.md gains a User plugins section pointing to PLUGIN_SDK.md. - PLUGIN_SDK.md adds a "…d06bf19 -
Plugin protocol Phase 2: workflow runner dispatches to plugins
Yuchen Yuan* schemas.py: relax NodeType from a Literal of 9 built-in kinds to a free-form str. Plugin kinds are validated separately in plugin_service so they don't pollute the schema. Add optional user_id to RunRequest so the runner can find the right user's plugins. * workflow_service.py: new _handle_plugin() that converts in-process ctx (QuantumCircuit + Backend object + scalars) into the JSON- friendly inputs the plugin subprocess expects, invokes the subprocess via plugin_runner.run_plugin, then translates the result back: circuit replacement via QPY round-trip, backend selection limited to known fake backends, scalar writes folded into ctx for downstream blocks. run_pipeline + run_pipeline_stream both take a new user_id param and fall through to _handle_plugin for any node type not in the built-in _HANDLERS table. Plugin steps participate in the intermediate cache: the prefix hash includes the plugin's kind + params, so re-running with the same plugin setting…8d471b9 -
Plugin protocol Phase 1: backend service + subprocess runner
Yuchen YuanThree new backend modules to support user-uploaded plugin blocks: * plugin_service.py — manifest schema (Pydantic), per-user storage under /tmp/quda_plugins/<user_id>/, zip upload + validation: - max 1 MB zip, ≤ 50 entries, ≤ 512 KB per file - allowlist: .py / .json / .txt / .md only - rejects path traversal (.., leading /) - rejects reserved kinds (collisions with built-in block types) - rejects > 5 plugins per user (count cap) - validates manifest.json against PluginManifest schema (kind format, family enum, hex color, unique param keys, …) * plugin_runner.py — subprocess execution with safety measures: - 10-minute hard timeout (subprocess.run(timeout=600)) - 1 GB virtual memory cap via RLIMIT_AS in preexec_fn - 11-minute CPU time cap via RLIMIT_CPU - os.nice(10) so a busy plugin doesn't starve FastAPI - env stripped to allowlist (PATH, PYTHONPATH, HOME, TMPDIR, …) — drops IBM_QUANTUM_TOKEN and any other Space secrets - cwd set to plugin's own dire…34125c4 -
Remove Parameter Sweep feature
Yuchen YuanReverts all 8 files involved in the sweep feature (per user request): - Delete SweepDialog.tsx - Remove Sweep button + state + dialog mount in FlowCanvas - Remove Sweep entry + props from MoreMenu (mobile) - Drop Sweep mention from TrySlide power-features strip - Drop Sweep mention from NextStepsHint in ResultsPane - Remove SweepConfig/SweepRequest/SweepRunResult types + sweepStream method from api.ts - Remove /api/workflow/sweep endpoint from backend routes - Remove SweepConfig/SweepRequest/SweepRunResult/SweepResponse from backend schemas The per-node intermediate cache stays — it was originally built as groundwork for sweep but is independently useful for re-running modified pipelines.44acddd -
Feature: parameter sweep with comparison chart
Yuchen YuanBackend: - New POST /api/workflow/sweep SSE endpoint. Accepts a base pipeline + SweepConfig (target node_id, param_key, list of values up to 50). For each value, patches the target node's data and runs the full pipeline. Yields one SweepRunResult per value. - Schemas: SweepConfig, SweepRequest, SweepRunResult, SweepResponse. - Leverages the existing per-node intermediate cache: prefix steps upstream of the swept block are reused across all sweep iterations. An N-value sweep of the last block's parameter costs roughly N * (last-block runtime) instead of N * (full-pipeline runtime). Frontend: - New SweepDialog modal. UI flow: 1. Picks the target: auto-discovers all numeric NodeParamSpec entries on the canvas (QuCAD iters/lam/rho, Qshot alpha, etc.) 2. User sets start, end, steps (2-20) → preview of computed values 3. Click "Run sweep" → streams results from /workflow/sweep 4. Renders a line chart (param value on X, output metric on Y) plus a data table. Met…fead27e -
Fix 3 audit findings: export signatures, cache safety, accessibility
Yuchen Yuan1. CRITICAL — exportPython.ts CompressVQC template had 3 wrong function calls: - quadraticProgram_luttoqp(lut) → (qc, lut) - admmOptimizedCompVQC(qp, lut) → (qp) - resultsCompressVQC(qc, result, lut) → (result, qc) All verified against backend/qlib/compvqc.py actual signatures. Users who exported and ran pipeline.py would have hit TypeError. 2. MEDIUM — Step cache _cache_put now deep-copies QuantumCircuit objects via qc.copy() instead of storing references. Prevents a future handler that mutates circuit in-place from silently corrupting cached snapshots. Current handlers all reassign, so this is defensive, but the cost (one .copy() per step) is cheap. 3. MEDIUM — BlockPicker button now has aria-haspopup, aria-expanded, aria-label. Dropdown div has role="menu" and aria-label. Screen reader users can now navigate the block catalog.51365eb -
Feature: per-node intermediate result cache
Yuchen YuanBackend: - In-memory LRU cache (200 entries) keyed by pipeline-prefix hash. The prefix hash covers (circuit QPY + all node types & params up to the current step). If the user changes only the last block, all preceding steps return instantly from cache (~0ms) instead of re-running (saves minutes for QuBound LSTM / Qshot HDBSCAN). - After each step, a shallow copy of the ctx dict is cached alongside the StepResult. On cache hit, ctx is restored so subsequent steps can pick up where the cached prefix left off. - Cached steps are flagged with from_step_cache=True (new optional field on StepResult) so the frontend can distinguish them. - Cache is process-scoped and resets on container restart. LRU eviction at 200 entries prevents unbounded memory growth. Frontend: - StepResult type extended with optional from_step_cache. - Results pane shows a small "cached" chip on steps served from the intermediate cache, so users can see which steps were instant. Works with the SSE st…1e3019d -
Feature: SSE streaming for real-time pipeline progress
Yuchen YuanBackend: - Add run_pipeline_stream() generator in workflow_service.py that yields each StepResult as it completes instead of collecting all. - Add POST /api/workflow/run-stream SSE endpoint in workflow.py. Cache hits emit the full RunResponse as one event + [CACHED] sentinel. Cache misses stream individual step events + [DONE]. Frontend: - Add api.runStream() in api.ts: uses fetch + ReadableStream to parse SSE events incrementally. - FlowCanvas.runPipeline() now uses the streaming endpoint. Each step appears in the Results pane as soon as it finishes, so the user sees "Step 1: Input circuit... done" while Step 2 is still running, instead of staring at a blank spinner for 2+ minutes. - On cache hit, the full response arrives instantly (same UX as before). On stream error, falls back gracefully with an error toast. The old POST /api/workflow/run endpoint is unchanged for backwards compatibility and the precompute script.02d0eb5
-
Rebrand QuAIM → QuDA Studio (Quantum Design Automation Studio)
Yuchen YuanNew product name across all user-facing surfaces: - TopBar: title + tagline - index.html <title> - WelcomeTour slide 1 gradient heading - FastAPI app title + boot/shutdown log messages - README HF frontmatter (title, short_description) + H1 - config.py module docstring Domain moves from jqub21-quaim.hf.space to qudastudio-app.hf.space (new HF org "qudastudio" under the same jqub21 account).8742007
-
Neutralise dev-process metadata in code comments
Yuchen YuanEarlier audits caught keyword-level leaks (tokens, paths, emails). This pass goes one level up: comments throughout the codebase narrated the project's history — "Jovin's Streamlit prototype", "the handover snapshot", "Jovin's old prototype's flowChartProto", "Batch 2 circuits", etc. — which read like internal team notes rather than product code, and exposed the development trajectory (research handover → rewrite → packaging) to anyone reading the public repo. Replaced or trimmed the offending comments while keeping legitimate attribution (e.g., "author: Tong Li" in qshot/__init__.py docstring). No behavior change: docstrings + line comments only. Files touched: - qlib/qiskit_utils.py – module docstring rewritten - qlib/qucad.py – default-config attribution generalised - qlib/compvqc.py – "the original prototype did..." → factual - qlib/qshot/__init__.py – "handover snapshot" → "reference code" - app/services/workflow_service.py – Qshot docstring de-narrated - a…fa87757 -
Backend copy: extend QuAIM description and cache motivation to four algorithms
Yuchen YuanTwo more places that hadn't caught up with Qshot landing: - main.py FastAPI description ("/docs" page header) still listed only QuCAD/QuBound/CompressVQC. Add Qshot. - run_cache.py module docstring referenced "the three preset pipelines" and "four presets x six samples". Both numbers were stale (5 presets, 9 samples; the precompute matrix is 36 cache entries). Generalise the wording so it doesn't have to be edited on every preset/sample addition, and note current counts inline.ede3688 -
Comment-vs-behavior audit: fix four real mismatches
Yuchen Yuan- run_cache: docstring claimed `_normalize_node` drops node id, code actually keeps it. Rewrite docstring to match behavior + explain why the cache still hits in practice (frontend presets and precompute script both use the same n1, n2... convention). - precompute_preset_results: qshot preset existed in frontend but was missing from the script's PRESETS dict, so qshot+ry_chain_6q always cache-missed. Add it. - viz/Sparkline: docstring said "non-negative integers" but the code defensively handles negatives (Math.min(...data, 0)) and short arrays (returns null on len<2). Rewrite docstring to match. - ResultsPane: EmptyHint said QuBound takes "about 2 minutes" while RunningHint says "1-3 minutes" for QuBound or Qshot. Unify both to 1-3 min and mention both slow paths.8e6747e -
Param editor collapses by default; misc review-driven cleanups
Yuchen YuanUser feedback: a tunable block shouldn't default to a fully expanded form on the canvas — that pushes the block visually big and clutters a multi-block pipeline. Default the param editor to a single-line disclosure with a chevron + a one-line summary of current values; the full editor only renders when the user clicks to expand. * QNode now owns local `paramsOpen` state (not in node-data — it's a pure UI affordance, shouldn't pollute share-links or auto-connect output). Header row shows `chev > params: <summary>`. Click toggles. * New `summariseParams()` helper builds the short summary from the schema: select values stay as their short keys (`pittsburgh_1`), numbers respect each param's `displayPrecision`. Kept under ~30 chars so it fits the block width. Three issues from an independent review of the recent Qshot work: * CRITICAL: workflow_service `_default_label()` was missing `"qshot"`, so step results in the right pane displayed lowercase "qshot" instead of "Qshot".…b89f3b2
-
Integrate Qshot (noise-aware shot-count recommender) as a pipeline block
Yuchen YuanNew research block from the JQub lab (handover from Tong Li). Given a QuantumCircuit + an IBM calibration snapshot + a target fidelity α, Qshot predicts the minimum shots needed to reach α × F_converged on that backend. Backend: * qlib/qshot/ — handover package (recommend_shots_v4, dual_gnn_model, show_dag, train_dual_gnn) + new __init__.py wrapping lazy singleton and NOISE_SNAPSHOTS registry. GNN-fallback lazy imports converted to package-relative so it works as a proper Python package. * cache/qshot/ — 12 dataset dirs (~3.3k records) + best_model.pt (LFS). * _handle_qshot in workflow_service: binds free circuit parameters to zero (Aer constraint), calls singleton.predict, surfaces shots / fidelity ± std / fit parameters / pilot measurements in summary. * NodeType += "qshot"; dispatcher wired. * requirements += hdbscan, torch-geometric, pylatexenc. torch-scatter / torch-sparse NOT pinned — PyG falls back to pure-Python scatter without them, far simpler on HF Spaces. Fr…fd88622 -
Rename the product from "JQub Quantum Flow" to "QuAIM"
Yuchen YuanThe old name was just a working title. Adopt the proper product name so the Space card, browser tab, welcome tour, TopBar, and the FastAPI OpenAPI title all agree. Changed: * README frontmatter (Space card title + short_description) and H1 * index.html <title> * WelcomeSlide gradient title * TopBar product name * FastAPI app(title=) and startup/shutdown log lines * config.py module docstring * Dockerfile header comment Intentionally NOT changed: * Repo / HF Space path (jqub-quantum-flow) — renaming would break bookmarked share links, existing clones, and CI paths. * frontend/package.json "name" — not published to npm. * Git remote, git history, commit authors. No NSF-specific metadata (award number, program wording, PI listing, dollar amount, abstract text) is added anywhere in the repo. The name "QuAIM" is used standalone without its acronym expansion.52378e7 -
Revert "Add before/after circuit diff on QuCAD and CompressVQC steps"
Yuchen YuanThis reverts commit 73f63904abba9a42f464877bea7c622380054954.fb05400 -
Add before/after circuit diff on QuCAD and CompressVQC steps
Yuchen Yuan +1: Claude Opus 4.7QuCAD prunes variational parameters (by setting θ=0) and CompressVQC folds redundant rotations — both modify ctx["circuit"]. Until now the results panel only showed summary numbers. Visitors had no way to see what the algorithm actually did to the circuit. Backend - New _diagram_snapshot() helper in workflow_service captures {depth, size, num_parameters, ops, diagram_text} for a circuit. - QuCAD and CompressVQC handlers now attach matching `before` and `after` blocks to their step.summary (schema unchanged — summary is dict[str, Any]). Frontend - New <CircuitDiff> component in ResultsPane reads summary.before / summary.after and renders: · an inline metric header (depth X → Y (-Z), gates X → Y (-Z)) · a collapsible side-by-side pair of ASCII circuit diagrams (stacked on mobile so long diagrams don't clip) - Embedded in QuCADCard and CompressVQCCard. QuCAD gets an extra hint line explaining that its "after" has the same gate layout with θ=0 on pruned paramete…73f6390
-
Cache pipeline runs by (circuit, graph) content hash
Yuchen Yuan +1: Claude Opus 4.7For the demo flow -- pick a sample, pick a preset, hit Run -- the server was re-executing the full QuCAD + LSTM + QAOA stack every click, which is 30-90s per preset. Most visitors just want to see what each algorithm produces on a bundled sample; they bounce long before the pipeline finishes. This commit adds a read-only, content-addressed cache for run responses. Key is sha256(qpy_bytes(circuit) + normalized(nodes+edges) + use_live_ibm) truncated to 16 hex chars. The /workflow/run handler looks up the key before dispatching run_pipeline; hits return the stored RunResponse with from_cache=true. Live-IBM runs always bypass the cache, since calibration drifts and the point of "live" is to hit hardware. The precompute script under scripts/ runs every PRESET x every sample and serializes responses to backend/cache/precomputed_runs/<key>.json. Those files are checked in and bundled into the image, so first-visit users see results in <1s with a "cached" pill in the ResultsPane header expla…e4e737d -
Add sample diagram preview, upload hints, and block taglines
Yuchen YuanSample circuit preview: - Backend SampleCircuit now carries depth/size/params/diagram_text so the sample list exposes enough metadata to preview without a second round trip. - Each sample button has an eye-toggle that expands an ASCII circuit diagram inline. The Loaded card has a matching toggle. Upload affordance: - Button label is now 'upload .qpy / .qasm' with a descriptive title. - Empty Loaded card explains what formats are accepted and offers a 'download a sample' link so new users can try the upload flow with a known-good file. - New GET /api/circuits/samples/{key}/download serves the raw .qpy. Block discoverability: - Added NodeSpec.tagline (3-5 word human-friendly caption). - Palette tiles show the tagline under the label (tile height grew from 52px to 68px, width 92px -> 108px). - Canvas QNode also renders the tagline so users don't need the tooltip or the tour to recall what each block does.bd3a155 -
Polish: widen tiles, pedagogical sample order, em-dash sweep
Yuchen Yuan- NodePalette: widen tiles 72px->92px so CompressVQC / IBM live backend labels stop truncating; rewrite right-side hint into clean two-liner. - Backend: add SAMPLE_ORDER so /api/circuits/samples returns a pedagogical ordering (bell_state first, ry_chain_6q last) instead of alphabetical by filename. - Rename 'Circuit' -> 'Input circuit' for consistent naming across palette, tour, and results. - Remove em-dashes from user-visible copy (ResultsPane, FlowCanvas, nodeCatalog, WelcomeTour); replace with colons/periods/parens.fa80903 -
UX polish pass: results viz, sample descriptions, delete affordance
Yuchen YuanThree related changes aimed at making both experts and newcomers able to understand and play with the lab's algorithms through the demo. UX basics (Batch 1): - Fix all timing claims to match HF's shared CPU (~2 min, not ~60 s) - Rename "Fake backend" -> "Noisy simulator" with a plain-English description ("Simulates a real IBM quantum chip with its measured noise. Runs locally, no IBM account needed.") - Add a hover-X delete button on each canvas node, with a matching hint in the block palette about the Backspace shortcut - Sample circuit buttons now show a curated one-liner under the name, replacing the auto-generated "N-qubit circuit, depth D" text More demo circuits (Batch 2): - Add 4 new samples: w_state_3q, qft_3q, ry_chain_6q, hardware_efficient_4q - Each comes with a human-friendly description in the circuit picker Results visualization (Batch 3): - ResultsPane now renders per-algorithm cards instead of flat k/v rows: - QuBound: 0-1 gauge + "lower is better" caption …36d22d6