Skip to content

demo(hybrid-bridge): classical Orca ↔ quantum q-orca over the cross-tool bridge - #99

Merged
jascal merged 2 commits into
mainfrom
demo/hybrid-bridge
May 31, 2026
Merged

demo(hybrid-bridge): classical Orca ↔ quantum q-orca over the cross-tool bridge#99
jascal merged 2 commits into
mainfrom
demo/hybrid-bridge

Conversation

@jascal

@jascal jascal commented May 30, 2026

Copy link
Copy Markdown
Owner

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 angle theta of 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.

iter │   θ used │ measured P(1) │    error │   θ → next
   1 │   0.3000 │        0.0188 │  +0.4812 │     1.2624
   2 │   1.2624 │        0.3457 │  +0.1543 │     1.5710
   3 │   1.5710 │        0.4993 │  +0.0007 │ (converged)
final θ : 1.5725  (θ* = π/2 = 1.5708) · 3 quantum calls · 12288 shots

The classical loop discovers θ=π/2 with no prior knowledge of it — only by measuring the quantum child.

Files (examples/hybrid-bridge/)

file role
forward.q.orca.md quantum child QForward: Ry(theta)measure → bits[0], exposes bits[0] with expectation, histogram
vqe-orchestrator.orca.md classical machine — the whole loop is Orca states / transitions / guards; invoke binds prob_bits_0 → prob
run_demo.py driver: register_foreign_runnerq-orca run --bridge, supplies the gradient_step body, TARGET/Q_ORCA_BIN env knobs, fixed seed
README.md architecture, run instructions, and the both-halves-must-carry-the-bridge version note

Notable

  • The optimization control flow lives in Orca, not Python — the host supplies only the numeric gradient_step action and the bridge wiring.
  • Reproducible (fixed simulator seed) and generalizes (TARGET=0.85 → θ ≈ 2.35).
  • Requires bridge-bearing builds on both sides: q-orca ≥ 0.9.1 and a post-Add execution-backends feature spec to docs/specs/ #13 orca-runtime-python (documented in the README).

🤖 Generated with Claude Code

…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 jascal left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.4993 at θ=π/2 matches the README's iter-3 sample line exactly, the histogram sums to 4096, and the run is seed-reproducible. The forward.q.orca.md machine, the prob_bits_0/hist_bits_0 derived-statistic naming, and the result-envelope shape are all correct against q_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.1 claim), 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 only gradient_step + the bridge wiring. The two guards is_converged/not_converged are mutually exclusive and exhaustive over a bool, so next in evaluate always has exactly one matching transition. Clean separation.
  • Convergence math checks out. P(1)=sin²(θ/2), so dP/dθ = ½·sin(θ) = 0.5 at θ=π/2, making the Newton step Δθ = error/0.5 = 2·error — i.e. GAIN = 2.0 is 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), and MAX_ITERS=12 forces converged=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)

  1. Doc value mismatch. run_demo.py:39 says TARGET=0.85 ⇒ θ* ≈ 2.348, but 2·asin(√0.85) = 2.3462. The README (≈ 2.346) and PR body (≈ 2.35) are right; just fix the docstring to 2.346.
  2. 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 when orca-lang is 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.
  3. TARGET input has no validation. float(TARGET_OVERRIDE) raises an uncaught ValueError on non-numeric input, and a value outside (0,1) either blows up in theta_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 to MAX_ITERS). A one-line guard — assert 0 < target < 1 with a friendly message, or a clamp — would make misuse obvious.
  4. Outer while has no independent safety bound. Termination relies on every round reaching evaluate (so a MAX_ITERS-driven converged=True can route to done). That holds given the documented invoke/on_done auto-advance, but if the machine ever parked in a state where next is a no-op, while state != "done" would spin forever. A defensive outer counter mirroring MAX_ITERS would make the demo robust to runtime surprises. Minor.
  5. Tiny: the ASCII diagrams in README.md and run_demo.py are 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>
@jascal
jascal merged commit 3e46739 into main May 31, 2026
6 checks passed
@jascal
jascal deleted the demo/hybrid-bridge branch May 31, 2026 18:42
jascal added a commit that referenced this pull request Jun 7, 2026
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>
jascal added a commit that referenced this pull request Jun 16, 2026
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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant