demo(hybrid-bridge): classical Orca ↔ quantum q-orca over the cross-tool bridge - #99
Conversation
…ool bridge
A runnable end-to-end demo of the v1.0 cross-tool bridge: a classical Orca
orchestrator (orca-lang runtime-python) runs a variational loop that tunes the
rotation angle of a single-qubit q-orca circuit until the measured P(1) hits a
target — delegating each forward pass over the bridge as JSON envelopes on a
subprocess. The two tools share no AST, no FFI, and no Python environment.
- forward.q.orca.md quantum child: Ry(theta); measure -> bits[0]
(returns prob_bits_0 = sin^2(theta/2))
- vqe-orchestrator.orca.md classical loop expressed in Orca states/transitions/
guards; invoke binds prob_bits_0 -> prob each iteration
- run_demo.py driver: register_foreign_runner -> `q-orca run --bridge`,
supplies the gradient_step action body; TARGET/Q_ORCA_BIN
env knobs; fixed seed for reproducibility
- README.md architecture, run instructions, and the both-halves-
must-carry-the-bridge release note
Converges to theta = pi/2 in 3 quantum calls for the default target 0.5; the
loop generalizes to any target (e.g. TARGET=0.85 -> theta ~ 2.35).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
jascal
left a comment
There was a problem hiding this comment.
Code Review — Claude Sonnet 4.6
Verdict: LGTM with non-blocking nits. This is a genuinely nice end-to-end demo. I verified the q-orca half actually runs over the bridge and reproduces the README's numbers exactly, the orchestrator machine parses cleanly, and ruff/tests are green. The findings below are polish, not blockers — the most useful one is a friendlier first-run failure when the runtime-python side lacks the bridge.
What I verified (not just read)
- The quantum forward pass works end-to-end over the bridge. I built an invocation envelope and piped it to the child directly:
printf '{"protocol_version":"1.0","child":"QForward","args":{"theta":1.5708},"shots":4096,"return_bindings":{"prob":"prob_bits_0"}}' \ | q-orca run forward.q.orca.md --bridge --seed 7 → {"protocol_version":"1.0","final_state":"|measured>","returns":{"bits[0]":0,"prob_bits_0":0.499267578125,"hist_bits_0":{"0":2051,"1":2045}}}prob_bits_0 = 0.4993at θ=π/2 matches the README's iter-3 sample line exactly, the histogram sums to 4096, and the run is seed-reproducible. Theforward.q.orca.mdmachine, theprob_bits_0/hist_bits_0derived-statistic naming, and the result-envelope shape are all correct againstq_orca/bridge/protocol.py. - The orchestrator parses and instantiates.
parse_orca_md(vqe-orchestrator.orca.md)→VqeOrchestrator, initial context{theta:0.3, prob:0.0, target:0.5, iteration:0, converged:False}— matches the declared defaults. - Versions in this checkout:
q-orca 0.9.1(satisfies the README's≥ 0.9.1claim),orca-runtime-python 0.1.26. - Lint:
ruff check examples/hybrid-bridge/→ All checks passed! - Tests: full suite 1130 passed, 20 skipped — the new
examples/dir doesn't disturb collection. (No automated test was added, which is reasonable for a cross-repo demo; see the test-coverage note below.)
Correctness — the design is sound
- Control flow lives in Orca (
idle → measuring →(MEASURED)→ evaluate →(next)→ measuring|done), with the host supplying onlygradient_step+ the bridge wiring. The two guardsis_converged/not_convergedare mutually exclusive and exhaustive over a bool, sonextinevaluatealways has exactly one matching transition. Clean separation. - Convergence math checks out.
P(1)=sin²(θ/2), sodP/dθ = ½·sin(θ) = 0.5at θ=π/2, making the Newton stepΔθ = error/0.5 = 2·error— i.e.GAIN = 2.0is the Newton gain near the target, as the comment claims. The clamp to[0.01, π−0.01]keeps θ in the monotonic half-period (avoids wandering past π where the gradient flips sign), andMAX_ITERS=12forcesconverged=True, so the loop always terminates.theta_star = 2·asin(√target)is the correct inverse.
Blocking-adjacent: first-run UX when the runtime lacks the bridge
In this venv, OrcaMachine from the installed orca-runtime-python 0.1.26 has no register_foreign_runner (hasattr(...) == False). That is exactly the caveat your README documents — so this is honest, not a bug — but as written run_demo.py will die with a bare AttributeError: 'OrcaMachine' object has no attribute 'register_foreign_runner', which buries the helpful README guidance. Since you already explain the fix in prose, consider a one-line preflight that points the user at it:
if not hasattr(machine, "register_foreign_runner"):
raise SystemExit(
"This orca-runtime-python build predates the bridge "
"(no OrcaMachine.register_foreign_runner). Run the driver from a "
"checkout whose runtime-python is post-PR #13. See README → "
"'Both halves must carry the bridge'."
)That turns a confusing stack trace into the exact instruction you already wrote. Optional, but it's the difference between "demo looks broken" and "oh, I need the newer runtime."
Nits (non-blocking)
- Doc value mismatch.
run_demo.py:39saysTARGET=0.85 ⇒ θ* ≈ 2.348, but2·asin(√0.85) = 2.3462. The README (≈ 2.346) and PR body (≈ 2.35) are right; just fix the docstring to2.346. - Relative doc link escapes the repo. The README links the protocol doc as
../../../orca-lang/docs/cross-tool-invoke-and-returns.md, which only resolves whenorca-langis a sibling checkout three levels up — it renders as a dead link on GitHub. Consider an absolute URL, or a note that it's a sibling-repo path. TARGETinput has no validation.float(TARGET_OVERRIDE)raises an uncaughtValueErroron non-numeric input, and a value outside(0,1)either blows up intheta_star = 2·asin(√target)(math domain error for>1) or simply can't converge (P(1) can never reach it, so you silently fall through toMAX_ITERS). A one-line guard —assert 0 < target < 1with a friendly message, or a clamp — would make misuse obvious.- Outer
whilehas no independent safety bound. Termination relies on every round reachingevaluate(so aMAX_ITERS-drivenconverged=Truecan route todone). That holds given the documentedinvoke/on_doneauto-advance, but if the machine ever parked in a state wherenextis a no-op,while state != "done"would spin forever. A defensive outer counter mirroringMAX_ITERSwould make the demo robust to runtime surprises. Minor. - Tiny: the ASCII diagrams in
README.mdandrun_demo.pyare slightly different (box alignment) — harmless, just noting in case you want them identical.
Test coverage
No automated test ships with this — defensible, since it spans two repos/venvs and can't run in q-orca-lang CI without a bridge-bearing runtime-python. If you want some regression protection on the half that does live here, a tiny test that pipes a fixed invocation envelope into q-orca run forward.q.orca.md --bridge --seed 7 and asserts 0.45 < prob_bits_0 < 0.55 would lock in the quantum forward pass cheaply (I effectively ran that by hand above and it passed).
Security / performance
No concerns. The subprocess is invoked as an argv list (no shell, no injection surface); Q_ORCA_BIN from env is standard dev ergonomics. 12,288 total shots across 3 calls is trivial.
Really solid demo — the Orca-owns-the-control-flow framing is well executed and the docs are unusually honest about the cross-repo version coupling. Fix the 2.348 typo and consider the preflight check, and this is in great shape. 👍
This review was posted automatically by Claude Sonnet 4.6.
- Preflight check: if the runtime-python lacks `register_foreign_runner`, exit with a README pointer (→ orca-runtime-python >= 0.1.28) instead of a bare AttributeError — the exact stale-build case the README warns about. - Validate the TARGET override: must parse as a float in the open interval (0, 1); clean SystemExit with no traceback otherwise. - Defensive bound on the drive loop (MAX_ITERS + 2) — belt-and-suspenders against an unexpected state-machine stall; never the normal exit. - Fix docstring: TARGET=0.85 ⇒ θ* ≈ 2.346 (was 2.348). - README: link the protocol doc by absolute GitHub URL (the relative ../../../orca-lang path only resolves in a local side-by-side checkout). Verified: default converges (θ→π/2); TARGET=0.85 converges (θ*→2.346); out-of-range / non-float TARGET and the pre-bridge runtime all exit cleanly. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Files the 2026-06-05 feedback triage (5 new items, §§7.21–7.25), then resolves the four hybrid-bridge entries: - §7.21 (friendly preflight for register_foreign_runner) — already shipped in PR #99: run_demo.py:86-91 checks hasattr(machine, "register_foreign_runner") and raises SystemExit with the README pointer. Marked done with a note that the hasattr target was adjusted (attribute lives on OrcaMachine, not the runtime_python module) from what the spec'd fix sketched. - §7.22 (2.348 vs 2.346 docstring typo) — already reconciled in PR #99's review-nits commit; 2.346 is correct (2·asin(√0.85)). - §7.23 (repo-escaping doc link) — drops the misleading HTML comment on examples/hybrid-bridge/README.md:10 that pointed readers at "../../../orca-lang/docs/...", a path only valid for one specific side-by-side checkout layout. The canonical upstream URL on the preceding line is now the single source of truth. - §7.24 (unguarded TARGET input) — already shipped in PR #99: run_demo.py:93-100 parses TARGET as a float and enforces 0.0 < TARGET < 1.0 (a probability bound; the angle clamp is a separate downstream invariant). §7.25 (ruff sweep of test files, ~13–18 pre-existing errors) is left open for a dedicated half-day pass. Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
Both items from PR #78's review log; both target the `scripts/*-prompt.txt` files the scheduled automations consume. §7.18 — `scripts/pr-review-prompt.txt` step 2.b. Replaced the `body contains "Claude"` substring check with a "starts with" match against the canonical header `## Code Review — Claude Sonnet 4.6`. The header is already required by step 3.e of the same prompt, so anchoring on it is the lowest-friction discriminator and prevents a false-positive skip when a human reviewer happens to mention Claude in a normal review body (option (b) of the three the task body enumerated). §7.19 — `scripts/nightly-prompt.txt` Step 2. Restructured the cross-check into two ordered checks. (1) Whole-change exact match: compare `<change-name>` to every open PR's `headRefName`, stop on equality — catches single-task changes (`add-reset-syntax`, `fix-mps-encoding-non-factorizing`, …) whose branch matches the change directory by convention and which the existing `§N.M`-anchor scan misses. (2) Per-task anchor scan, kept as-is and labelled as the granular case for multi-task changes like `tech-debt-backlog` whose individual PRs branch off as `tech-debt-backlog-7-18`, `tech-debt-backlog-7-16-7-17`, etc. Bundled in one PR because both tasks come from the same review log (`logs/pr-review-2026-05-28.log`) and both target sibling files in `scripts/`, matching the §7.16/§7.17 (PR #76) and §7.21–§7.24 (PR #99) bundling precedents. Tests: pytest -q is green at 1282 passed / 8 skipped — the prompt files are not referenced by anything under tests/, so the edits land as doc-style changes. The new behaviour will be exercised on the next scheduled run of each automation. Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
What
A runnable, end-to-end demo of the v1.0 cross-tool bridge — the first one that actually exercises both sides across the tool boundary.
A classical Orca orchestrator (orca-lang
runtime-python) runs a variational optimization loop that tunes the rotation anglethetaof a single-qubit q-orca circuit until the measured probability of outcome 1 hits a target. Each forward pass is delegated to q-orca over the bridge as JSON envelopes on a subprocess (q-orca run forward.q.orca.md --bridge). The two tools share no AST, no FFI, and no Python environment.The classical loop discovers θ=π/2 with no prior knowledge of it — only by measuring the quantum child.
Files (
examples/hybrid-bridge/)forward.q.orca.mdQForward:Ry(theta)→measure → bits[0], exposesbits[0]withexpectation, histogramvqe-orchestrator.orca.mdinvokebindsprob_bits_0 → probrun_demo.pyregister_foreign_runner→q-orca run --bridge, supplies thegradient_stepbody,TARGET/Q_ORCA_BINenv knobs, fixed seedREADME.mdNotable
gradient_stepaction and the bridge wiring.TARGET=0.85→ θ ≈ 2.35).q-orca ≥ 0.9.1and a post-Add execution-backends feature spec to docs/specs/ #13orca-runtime-python(documented in the README).🤖 Generated with Claude Code