open-standards/wai/wai-web/src/quantum_engine.rs
Transaction Science a274776b50
All checks were successful
WAI conformance / does this change touch it (pull_request) Successful in 8s
standards workspaces build + test / which workspaces this change touches (pull_request) Successful in 10s
WAI breaking changes and the conformance runner / WAI breaking · does this change touch WAI (pull_request) Successful in 11s
joule-moq-remote host agent / joule-moq-remote · does this change touch it (pull_request) Successful in 14s
wai-audit collector and player integration / does this change touch it (pull_request) Successful in 13s
joule-moq-room room service / joule-moq-room · does this change touch it (pull_request) Successful in 15s
joule-moq-web browser client / joule-moq-web · does this change touch it (pull_request) Successful in 14s
WAI examples / WAI examples · does this change touch them (pull_request) Successful in 7s
WAI operation catalogue / does this change touch it (pull_request) Successful in 19s
wai-app and Create / wai-app · does this change touch it (pull_request) Successful in 20s
wai-fleet service / does this change touch it (pull_request) Successful in 9s
WAI energy receipts / does this change touch it (pull_request) Successful in 19s
WAI JPEG-AI whole decode (pinned inputs, required) / does this change touch it (pull_request) Successful in 7s
wai-ledger service / does this change touch it (pull_request) Successful in 10s
wai-key-proxy / does this change touch it (pull_request) Successful in 10s
wai-ops-gpu integer operators on GPUs / does this change touch it (pull_request) Successful in 10s
wai-pack / wai-pack · does this change touch it (pull_request) Successful in 7s
WAI neural sink gates / does this change touch it (pull_request) Successful in 11s
wai-quantum contract / does this change touch it (pull_request) Successful in 6s
wai-quantum command line / does this change touch it (pull_request) Successful in 8s
joule-code conformance gate / joule-moq-relay, its own energy on a counter (macos) (pull_request) Successful in 37s
wai-quantum signal processor / does this change touch it (pull_request) Successful in 10s
wai-quantum CUDA member / does this change touch it (pull_request) Successful in 13s
wai-quantum resource estimation / does this change touch it (pull_request) Successful in 8s
WAI conformance / cross-arch byte-equality · macos (pull_request) Successful in 27s
wai-quantum other formats / does this change touch it (pull_request) Successful in 10s
wai-quantum editors / does this change touch it (pull_request) Successful in 13s
wai-quantum FPGA member / does this change touch it (pull_request) Successful in 11s
wai-quantum dataflow member / does this change touch it (pull_request) Successful in 16s
wai-quantum docs, course and locales / does this change touch it (pull_request) Successful in 16s
wai-quantum for JavaScript / does this change touch it (pull_request) Successful in 7s
wai-quantum HIP member / does this change touch it (pull_request) Successful in 7s
wai-quantum OpenQASM reader / does this change touch it (pull_request) Successful in 13s
wai-quantum Metal member / does this change touch it (pull_request) Successful in 13s
wai-quantum OpenCL member / does this change touch it (pull_request) Successful in 11s
wai-quantum npu-cores member / does this change touch it (pull_request) Successful in 18s
wai-quantum neural-processor member / does this change touch it (pull_request) Successful in 11s
WAI conformance / codec wrappers · fuzz smoke, text decode limits, C entry points, provenance, the semantic path (pull_request) Successful in 1m3s
joule-moq-remote host agent / joule-moq-remote, every target (macos) (pull_request) Successful in 54s
wai-quantum pulse and dynamics / does this change touch it (pull_request) Successful in 13s
wai-audit collector and player integration / collector, player integration and the browser end to end · macos (pull_request) Successful in 1m37s
wai-quantum on every processor / emulated · armv7-unknown-linux-gnueabihf (pull_request) Successful in 59s
wai-quantum for Python / does this change touch it (pull_request) Successful in 8s
wai-quantum error correction and mitigation / does this change touch it (pull_request) Successful in 8s
wai-quantum CUDA member / member · CUDA (jetson-hub) (pull_request) Successful in 1m33s
wai-quantum-qpu / does this change touch it (pull_request) Successful in 10s
wai-quantum extension points / does this change touch it (pull_request) Successful in 9s
wai-quantum matrix-extension member / does this change touch it (pull_request) Successful in 8s
wai-quantum service / does this change touch it (pull_request) Successful in 10s
wai-quantum on every processor / emulated · loongarch64-unknown-linux-gnu (pull_request) Successful in 1m44s
joule-code conformance gate / Build + round-trip C1-C4 vectors (pull_request) Successful in 2m47s
wai-quantum studio and desktop / does this change touch it (pull_request) Successful in 11s
wai-quantum tensor-engine member / does this change touch it (pull_request) Successful in 10s
wai-quantum CUDA member / member · CUDA (thor) (pull_request) Successful in 1m58s
wai-quantum OpenCL member / member · OpenCL GPU and CPU (jetson-hub) (pull_request) Successful in 33s
wai-quantum portable tensor program / does this change touch it (pull_request) Successful in 5s
wai-quantum verdicts and repairs / does this change touch it (pull_request) Successful in 9s
wai-quantum variational and algorithm library / does this change touch it (pull_request) Successful in 13s
wai-quantum CPU vector units / does this change touch it (pull_request) Successful in 12s
wai-quantum views in agent hosts / does this change touch it (pull_request) Successful in 8s
wai-quantum WebGPU member / does this change touch it (pull_request) Successful in 6s
WAI mbt2018_mean integer decode (regenerated vectors) / does this change touch it (pull_request) Successful in 7s
wai-sink-android native sink library / does this change touch it (pull_request) Successful in 16s
WAI conformance / fast integer kernels, every x86_64 kernel set (AVX-512 silicon) (pull_request) Successful in 3m6s
wai-sink-swift native sink package / does this change touch it (pull_request) Successful in 14s
WAI Studio / does this change touch it (pull_request) Successful in 7s
wai-web reach builds / wai-web reach · does this change touch it (pull_request) Successful in 5s
wai-web wasm32 / does this change touch it (pull_request) Successful in 8s
wai-quantum OpenCL member / member · OpenCL GPU and CPU (thor) (pull_request) Successful in 49s
WAI conformance / cross-arch byte-equality · linux (pull_request) Successful in 32s
wai-quantum service / service energy · linux packages (pull_request) Successful in 1m17s
wai-quantum HIP member / member · HIP (framework-128gb) (pull_request) Successful in 1m8s
wai-quantum portable tensor program / tensor program · GPUs (jetson-hub) (pull_request) Successful in 24s
wai-quantum on every processor / emulated · riscv64gc-unknown-linux-gnu (pull_request) Successful in 3m33s
wai-quantum on every processor / emulated · s390x-unknown-linux-gnu (pull_request) Successful in 4m11s
WAI conformance / faces from keypoints under wasm32-wasip2 (wasmtime) (pull_request) Successful in 1m35s
wai-audit collector and player integration / collector · linux (pull_request) Successful in 1m10s
wai-quantum OpenCL member / member · OpenCL GPU (framework-128gb) (pull_request) Successful in 34s
standards workspaces build + test / macOS energy backends (pull_request) Successful in 4m14s
wai-quantum on every processor / emulated · sparc64-unknown-linux-gnu (pull_request) Successful in 5m11s
wai-quantum on every processor / emulated · aarch64-unknown-linux-gnu (pull_request) Successful in 5m53s
WAI breaking changes and the conformance runner / WAI breaking · wire, record and API against main · linux (pull_request) Successful in 1m49s
WAI conformance / quantum core and corpus under wasm32-wasip2 (wasmtime) (pull_request) Successful in 3m38s
wai-fleet service / service · macos (pull_request) Successful in 56s
wai-app and Create / wai-app · tests, clippy, the line language's verifier (linux) (pull_request) Successful in 39s
wai-quantum npu-cores member / member · npu-cores, neural processor (framework-128gb silicon) (pull_request) Successful in 1m37s
WAI breaking changes and the conformance runner / WAI breaking and conform · their tests, and the independent verifiers through wai conform · linux (pull_request) Successful in 2m38s
wai-quantum portable tensor program / tensor program · integrated GPU (framework-128gb) (pull_request) Successful in 34s
wai-app and Create / wai-app · Create, browser end-to-end (macos) (pull_request) Successful in 7m26s
wai-quantum CPU vector units / member · vector units, avx2 and avx512 (framework-128gb silicon) (pull_request) Successful in 38s
wai-quantum on every processor / emulated · powerpc64-unknown-linux-gnu (pull_request) Successful in 8m57s
wai-ledger service / service · linux (pull_request) Successful in 2m24s
wai-pack / wai-pack · linux (pull_request) Successful in 2m16s
WAI operation catalogue / the catalogue and every door · linux (pull_request) Successful in 5m11s
wai-ledger service / service · macos (pull_request) Successful in 1m37s
wai-quantum WebGPU member / member · DX12 and Vulkan (cbio-windows) (pull_request) Successful in 11m54s
wai-key-proxy / proxy · linux (pull_request) Successful in 1m34s
wai-fleet service / service · linux (pull_request) Successful in 5m4s
WAI neural sink gates / model-free refusals of the neural sink (pull_request) Successful in 2m16s
WAI conformance / cargo-class corpora · macos (pull_request) Successful in 12m36s
wai-quantum contract / the policy is linked, and the deprecations page reads (pull_request) Successful in 38s
wai-quantum on every processor / emulated · powerpc64le-unknown-linux-gnu (pull_request) Successful in 13m51s
WAI examples / WAI examples · portable · linux (pull_request) Successful in 9m30s
WAI JPEG-AI whole decode (pinned inputs, required) / fetch pinned JPEG-AI inputs → whole decode + pixel hash, required (pull_request) Successful in 7m12s
WAI examples / WAI examples · the archive, the readiness check, the browser and Apple · macos (pull_request) Successful in 13m21s
WAI energy receipts / energy receipts · macos (pull_request) Successful in 7m40s
wai-quantum CUDA member / member · CUDA absent (linux) (pull_request) Successful in 1m34s
wai-pack / wai-pack · macos (pull_request) Successful in 3m26s
wai-quantum contract / API compatibility · linux (pull_request) Successful in 4m41s
wai-quantum editors / editors · macos (pull_request) Successful in 1m4s
wai-quantum other formats / the set under wasm32-wasip2 (wasmtime) (pull_request) Successful in 1m26s
wai-quantum dataflow member / member · dataflow device absent (macos) (pull_request) Successful in 14s
joule-moq-web browser client / joule-moq-web · browser end-to-end (macos) (pull_request) Successful in 16m12s
wai-quantum FPGA member / member · FPGA simulation absent (linux) (pull_request) Successful in 21s
wai-quantum command line / command line · linux (pull_request) Successful in 3m38s
wai-quantum FPGA member / member · FPGA datapath, simulated (macos) (pull_request) Successful in 1m23s
wai-quantum command line / command line · macos (pull_request) Successful in 1m55s
wai-quantum OpenCL member / member · OpenCL GPU (macos) (pull_request) Successful in 27s
wai-quantum resource estimation / estimation and calibration · linux, release (pull_request) Successful in 2m1s
wai-quantum Metal member / member · Metal (macos) (pull_request) Successful in 50s
wai-quantum on every processor / emulated · i686-unknown-linux-gnu (pull_request) Successful in 16m52s
wai-quantum editors / editors · linux (pull_request) Successful in 2m31s
wai-quantum-qpu / credentials in the keychain (macos) (pull_request) Successful in 38s
wai-quantum contract / schemas and the committed tool lists · linux (pull_request) Successful in 6m53s
wai-quantum pulse and dynamics / the same bits · macos (pull_request) Successful in 1m20s
wai-quantum docs, course and locales / the Studio's words in every locale · linux (pull_request) Successful in 8s
wai-quantum matrix-extension member / member · matrix extension absent (macos) (pull_request) Successful in 15s
wai-quantum other formats / readers, writers and the set · linux (pull_request) Successful in 3m44s
wai-quantum dataflow member / member · dataflow device, simulated (pci 1e52:401e) (pull_request) Successful in 2m4s
wai-quantum for Python / python · macos (pull_request) Successful in 2m13s
wai-quantum OpenQASM reader / corpus under wasm32-wasip2 (wasmtime) (pull_request) Successful in 40s
WAI conformance / v2 vocabulary · manifests validate as stated (pull_request) Successful in 46s
wai-quantum Metal member / member · Metal absent (linux) (pull_request) Successful in 33s
wai-quantum WebGPU member / member · integrated GPU, Vulkan (framework-128gb) (pull_request) Successful in 9m21s
repository checks / lockfiles, advisories, tests in CI, workflow hygiene, spec and section references, public text (pull_request) Successful in 1m54s
WAI conformance / cargo-class corpora · linux (pull_request) Successful in 16m29s
wai-quantum portable tensor program / tensor program · Metal and the arm64 CPU (macos) (pull_request) Successful in 15s
wai-quantum OpenCL member / member · OpenCL absent (linux) (pull_request) Successful in 23s
wai-quantum neural-processor member / member · neural processor absent (linux) (pull_request) Successful in 19s
wai-quantum CPU vector units / member · vector unit absent (macos) (pull_request) Successful in 16s
joule-code conformance gate / joule-moq-relay, every target (pull_request) Successful in 2m59s
WAI conformance / delivery telemetry · CMCD and CMSD against an independent library (pull_request) Successful in 12s
wai-quantum OpenQASM reader / reader and corpus · linux (pull_request) Successful in 1m53s
wai-quantum pulse and dynamics / reader, simulator and pulse jobs under wasm32-wasip2 (wasmtime) (pull_request) Successful in 49s
WAI conformance / cross-arch byte-equality · linux-arm64 (pull_request) Successful in 27s
wai-ops-gpu integer operators on GPUs / builds · no adapter is not a pass (linux) (pull_request) Successful in 7m42s
wai-quantum for JavaScript / javascript · linux (pull_request) Successful in 2m43s
wai-quantum pulse and dynamics / reader, simulator and pulse jobs · linux, release (pull_request) Successful in 1m37s
wai-quantum-qpu / clients against their contracts (linux) (pull_request) Successful in 38s
wai-quantum studio and desktop / desktop app · windows (pull_request) Successful in 9m9s
wai-quantum matrix-extension member / member · matrix extension, emulated (aarch64 Linux) (pull_request) Successful in 17s
wai-quantum extension points / the registry under wasm32-wasip2 (wasmtime) (pull_request) Successful in 55s
wai-quantum WebGPU member / member · Metal (macos) (pull_request) Successful in 2m17s
wai-quantum service / service · macos (pull_request) Successful in 4m1s
wai-ops-gpu integer operators on GPUs / Metal GPU and browser WebGPU (macos) (pull_request) Successful in 8m41s
WAI conformance / C2PA manifest emission · signed, read back, validated (pull_request) Successful in 1m45s
WAI energy receipts / energy receipts · linux (pull_request) Successful in 15m1s
wai-quantum dataflow member / member · dataflow device, simulated (pci 1e52:b140) (pull_request) Successful in 5m49s
wai-quantum for Python / python · linux (pull_request) Successful in 2m54s
wai-quantum error correction and mitigation / codes, decoders, texts and mitigation · linux, release (pull_request) Successful in 2m34s
wai-quantum studio and desktop / desktop app · macos (pull_request) Successful in 4m34s
wai-quantum portable tensor program / tensor program · CPU, mutants, GPU builds (pull_request) Successful in 33s
joule-code conformance gate / joule-moq-ingest, every target (pull_request) Successful in 5m52s
wai-quantum docs, course and locales / the course and the command line's languages · linux (pull_request) Successful in 5m20s
joule-moq-remote host agent / joule-moq-remote, every target (linux-arm64) (pull_request) Successful in 1m8s
wai-quantum neural-processor member / member · neural processor (macos) (pull_request) Successful in 6m41s
wai-quantum WebGPU member / member · browser WebGPU (macos) (pull_request) Successful in 1m29s
wai-quantum CPU vector units / member · vector unit, rvv 1024-bit (riscv64, emulated) (pull_request) Successful in 48s
wai-quantum verdicts and repairs / the intent set and the verdict under wasm32-wasip2 (wasmtime) (pull_request) Successful in 1m16s
wai-quantum CPU vector units / member · vector unit, rvv 128-bit (riscv64, emulated) (pull_request) Successful in 25s
wai-quantum verdicts and repairs / verdicts, repairs and the intent set · linux (pull_request) Successful in 1m57s
wai-quantum variational and algorithm library / parameters, gradients, optimisers, VQE, QAOA and builders · linux, release (pull_request) Successful in 1m40s
wai-quantum CPU vector units / member · vector unit, avx2 (x86_64 silicon) (pull_request) Successful in 19s
wai-quantum CPU vector units / member · vector unit, sve 2048-bit (aarch64, emulated) (pull_request) Successful in 27s
wai-quantum CPU vector units / member · vector unit, sve 128-bit (aarch64, emulated) (pull_request) Successful in 1m3s
wai-quantum CPU vector units / member · vector unit, sve 512-bit (aarch64, emulated) (pull_request) Successful in 21s
wai-quantum studio and desktop / studio · browser (pull_request) Successful in 3m45s
wai-quantum WebGPU member / member · GPU, Vulkan (jetson-hub) (pull_request) Successful in 21m15s
wai-quantum service / service · linux (pull_request) Successful in 4m57s
wai-quantum extension points / the registry and the example · linux (pull_request) Successful in 5m58s
WAI Studio / the catalogue's actions, the unit tests and the core · linux (pull_request) Successful in 52s
wai-quantum studio and desktop / desktop app · linux (pull_request) Successful in 5m24s
wai-quantum WebGPU member / member · software Vulkan (linux) (pull_request) Successful in 2m13s
joule-moq-room room service / joule-moq-room, every target (pull_request) Successful in 4m33s
wai-quantum tensor-engine member / member · tensor engine, the kernel toolchain's simulator (linux) (pull_request) Successful in 5m33s
wai-quantum WebGPU member / member · GPU, Vulkan (thor) (pull_request) Successful in 24m51s
wai-quantum views in agent hosts / views · the page and its engine (pull_request) Successful in 3m22s
wai-quantum WebGPU member / shader checks · browser build · wasip2 inertness (pull_request) Successful in 3m19s
WAI examples / WAI examples · android-app · linux-arm64 (pull_request) Successful in 5m4s
wai-sink-android native sink library / every ABI, the AAR, and the instrumented tests in a headless emulator · macos (pull_request) Successful in 7m2s
wai-web reach builds / wai-web reach builds · the package of record, every output as recorded (pull_request) Successful in 2m29s
WAI mbt2018_mean integer decode (regenerated vectors) / regenerate mbt2018_mean integer vectors → Rust decode, required (pull_request) Successful in 5m30s
WAI conformance / each feature of the independent verifiers' steps compiles alone (pull_request) Successful in 11m35s
wai-web reach builds / wai-web reach builds · this tree's wai-web, every rung on its engine line (pull_request) Successful in 4m21s
wai-quantum views in agent hosts / views · a scripted host (pull_request) Successful in 7m15s
wai-web wasm32 / wai-web wasm32 build · corpus, menu and writers (pull_request) Successful in 6m8s
wai-sink-swift native sink package / libwai slices, desktop tests, simulator tests · macos (pull_request) Successful in 12m25s
WAI Studio / Studio in Chromium and Firefox · macos (pull_request) Successful in 11m58s
wai-pack / wai-pack · linux-arm64 (pull_request) Successful in 4m2s
WAI conformance / cargo-class corpora · linux-arm64 (pull_request) Successful in 18m33s
wai-pack / wai-pack · the floor through a media prober (pull_request) Successful in 38s
wai-pack / wai-pack · dependency licences (pull_request) Successful in 25s
wai-quantum docs, course and locales / every command and snippet in the docs · linux (pull_request) Successful in 20m39s
wai-quantum HIP member / member · HIP absent (linux-arm64) (pull_request) Successful in 56s
wai-quantum npu-cores member / member · npu-cores absent (linux-arm64) (pull_request) Successful in 26s
wai-quantum pulse and dynamics / the same bits · linux-arm64 (pull_request) Successful in 1m21s
standards workspaces build + test / joule-code-rs (joule-code/joule-code-rs, joule-code-rs, linux-arm64, true) (pull_request) Successful in 13m44s
wai-quantum tensor-engine member / member · tensor engine absent (linux-arm64) (pull_request) Successful in 35s
WAI energy receipts / energy receipts · linux-arm64 (pull_request) Successful in 13m45s
wai-quantum extension points / the registry and the example · linux-arm64 (pull_request) Successful in 2m46s
wai-pack / wai-pack · independent verifier (Python) (pull_request) Successful in 8m2s
wai-quantum variational and algorithm library / parameters, gradients, optimisers, VQE, QAOA and builders · linux-arm64, release (pull_request) Successful in 2m29s
wai-quantum signal processor / processor and member · signal processor, emulated (pull_request) Successful in 30m3s
wai-sink-android native sink library / the JNI layer and the platform-free half on the host JVM · linux-arm64 (pull_request) Successful in 3m15s
WAI Studio / Studio in WebKit · linux (pull_request) Successful in 22m57s
WAI conformance / independent verifiers · claims, JWP, key discovery and integer payloads (Python) (pull_request) Successful in 1h31m53s
wai-quantum 0.8.1, wai-quantum-qpu 0.4.1, wai-quantum-cli 0.2.4, the job service 0.2.2 and the Python package 0.1.2: the release's versions, its changelog heading, and every lock
Every change since 0.8.0 only adds or fixes, so each package moves its last
number (VERSIONING.md, "Before 1.0"). cargo-semver-checks 0.51.0 finds no
semver update required for wai-quantum, wai-quantum-cli or wai-quantum-qpu
against 0.8.0, 0.2.3 and 0.4.0 on crates.io, and keeps its baselines at the
versions last published. Every dependent's requirement names the new
versions, both server.json files follow, and the seventeen lockfiles that
resolve any of them move with them, each read with --locked. The JavaScript
package stays 0.1.1, as nothing in it changed, and the desktop app stays
0.1.2; its requirements move with the others. VERSIONING.md's "Version
today" table already reads 0.8.x, 0.4.x and 0.2.x, so only its example of a
result's engine moves. The Python README and its zh-CN translation name the
wheel at 0.1.2, and the views manifest records the new digest of
wai-quantum-views's lockfile, the two things 0.8.0 needed after its release
commit. The page is rebuilt with wai/wai-quantum-views/build.sh on the build
host with Rust 1.99.1 (build-views.mjs --check passes): its script and styles
are unchanged, and the engine inside it is the engine as it is now, which
changed its bytes, not its size.

The engine's version is among the sealed bytes of a stamped result, so the
page's pinned digests move (the course check's 1a9aa0ad... to 49a9fdb8...,
the compile's beffb3cb... to 198ea9bd..., the estimate's db90b147... to
acbd7208...), the answer set's stored seal is written again
(WAI_ANSWER_BUNDLE_WRITE=1), and the notebooks' stored outputs are stored
again (ci/check.sh --write-notebooks). The job pins strip the engine and
schema and do not move.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 15:46:22 -05:00

1625 lines
92 KiB
Rust

//! The quantum job service's engine in a page ([`wai::engine`]): a job
//! planned, run and sealed in the tab exactly as the service plans, runs and
//! seals it, with the page's own key; the receipt of any job, the service's
//! included, checked in the tab; a program linted and drawn. Requests and
//! answers are the service's JSON, so a page shows a job run here and one run
//! there with the same code.
use ed25519_dalek::SigningKey;
use serde_json::{Value, json};
use wai::engine::discover::{self, Archive, Budget, Evaluator, SearchOptions, Spec, search};
use wai::engine::answer::{self, eval as answer_eval};
use wai::engine::{catalog, compile, converge, course, critique, debug, describe, draw, equiv, estimate, job, latex, locks, novelty, refusal, repair, rewrite, shortcuts, study, svg, taste, telemetry, verdict, versions, visual};
use wasm_bindgen::prelude::*;
/// What a result run in a tab says of its energy.
const UNMETERED: &str = "a browser tab does not meter a run's energy";
fn error_json(e: impl std::fmt::Display) -> String {
json!({ "error": e.to_string() }).to_string()
}
fn read(request: &str) -> Result<Value, String> {
serde_json::from_str(request).map_err(|e| format!("the job is not JSON: {e}"))
}
/// The engine, with the key it signs with and the memory a job may take.
#[wasm_bindgen]
pub struct QuantumEngine {
key: SigningKey,
job_bytes: u64,
}
#[wasm_bindgen]
impl QuantumEngine {
/// An engine that signs with the Ed25519 key whose 32-byte seed is
/// `seed` (the page makes one at random and keeps it in this browser),
/// and admits a job of at most `memory_mb` MiB.
#[wasm_bindgen(constructor)]
pub fn new(seed: &[u8], memory_mb: u32) -> Result<QuantumEngine, String> {
let bytes: [u8; 32] = seed.try_into().map_err(|_| format!("a signing key's seed is 32 bytes, not {}", seed.len()))?;
Ok(QuantumEngine { key: SigningKey::from_bytes(&bytes), job_bytes: u64::from(memory_mb.max(1)) << 20 })
}
/// The signer the receipts name: the key as a `did:key`.
pub fn signer_did(&self) -> String {
wai::quantum_receipt::did_key(&self.key.verifying_key())
}
/// Run a job (the service's request JSON): the job as the service
/// returns it, the request, the plan and the result with its receipt; or
/// `{"error"}` with why it did not run.
pub fn run(&self, request: &str) -> String {
let req = match read(request) {
Ok(r) => r,
Err(e) => return error_json(e),
};
match job::run(&req, self.job_bytes, &self.key, json!({ "unmetered": UNMETERED })) {
Ok(body) => body.to_string(),
// A refusal names its codes, and a job that asked for a verdict
// gets the verdict of what was refused.
Err(e) => {
let mut v = refusal::refusal_json(&e);
v["error"] = json!(e);
if verdict::asked(&req) {
v["verdict"] = verdict::of_refusal(&req, &e);
}
v.to_string()
}
}
}
/// The method a job would run on and why, its memory and work, without
/// running it; or `{"error"}`.
pub fn plan(&self, request: &str) -> String {
match read(request).and_then(|req| catalog::plan(&req, self.job_bytes)) {
Ok(p) => serde_json::to_value(p).map(|v| v.to_string()).unwrap_or_else(error_json),
Err(e) => error_json(e),
}
}
/// Compile a program (`{"qasm", "epsilon", "level", "basis"}`, each
/// option optional): the compiled program and its certificate (every
/// pass's counts and check, the ε budget and the bound), sealed with the
/// page's key in a job's form so `engine_verify` checks it; or
/// `{"error"}` with why it was refused.
pub fn compile(&self, request: &str) -> String {
match read(request).and_then(|req| compile::call(&req).map(|result| compile::seal(&req, result, &self.key))) {
Ok(body) => body.to_string(),
Err(e) => error_json(e),
}
}
/// What a fault-tolerant machine would need to run a program
/// (`{"qasm" | "counts" | "routine", "budget", "qubit", "calibration",
/// "max_slowdown", "export"}`): its logical counts, each estimate on the
/// frontier sealed with the page's key in the resource-estimate receipt
/// family and the whole answer in a job's form, so `engine_verify`
/// checks its seal and `engine_estimate_verify` re-runs it; or
/// `{"error"}` with why it was refused.
pub fn estimate(&self, request: &str) -> String {
match read(request).and_then(|req| estimate::sealed(&req, &self.key)) {
Ok(body) => body.to_string(),
Err(e) => error_json(e),
}
}
/// An error-correction call ([`wai::engine::qec::call`]): `code` (a code
/// and its certified distance), `decode` (a syndrome, or a circuit's
/// detectors) or `threshold` (failure rates over distances), its
/// arguments as JSON; the answer sealed with the page's key in a job's
/// form, so `engine_verify` checks it; or `{"error"}` with why it was
/// refused.
pub fn qec(&self, op: &str, args: &str) -> String {
let req = match serde_json::from_str::<Value>(args) {
Ok(r) => r,
Err(e) => return error_json(format!("{op}: the arguments are not JSON: {e}")),
};
match wai::engine::qec::call(op, &req) {
Ok(result) => wai::engine::qec::seal(&req, result, &self.key).to_string(),
Err(e) => {
let mut v = refusal::refusal_json(&e);
v["error"] = json!(e);
v.to_string()
}
}
}
/// A pulse call ([`wai::engine::pulse::call`]): `schedule` (a pulse
/// program's schedule on frames: every instruction at its sample, the
/// waveforms' samples and the gate calls, which the Studio's pulse view
/// draws) or `check` (a pulse job checked by running it again), its
/// arguments as JSON; the answer sealed with the page's key in a job's
/// form, so `engine_verify` checks it; or `{"error"}` with why it was
/// refused. A pulse run is a job: `run` with `"method": "pulse"`.
pub fn pulse(&self, op: &str, args: &str) -> String {
let req = match serde_json::from_str::<Value>(args) {
Ok(r) => r,
Err(e) => return error_json(format!("{op}: the arguments are not JSON: {e}")),
};
match wai::engine::pulse::call(op, &req) {
Ok(result) => wai::engine::pulse::seal(&req, result, &self.key).to_string(),
Err(e) => {
let mut v = refusal::refusal_json(&e);
v["error"] = json!(e);
v.to_string()
}
}
}
/// A call of the variational and algorithm library
/// ([`wai::engine::variational::call`]): `gradient` (a Hamiltonian's
/// expectation at a program's params and its exact gradient by each),
/// `optimize` (gradient descent, Adam or SPSA, every step in a digest
/// chain), `vqe`, `qaoa` or `build` (a standard algorithm's program,
/// checked against its reference), its arguments as JSON; the answer
/// sealed with the page's key in a job's form, so `engine_verify` checks
/// it; or the refusal with its codes.
pub fn variational(&self, op: &str, args: &str) -> String {
let req = match serde_json::from_str::<Value>(args) {
Ok(r) => r,
Err(e) => return error_json(format!("{op}: the arguments are not JSON: {e}")),
};
match wai::engine::variational::call(op, &req) {
Ok(result) => wai::engine::variational::seal(&req, result, &self.key).to_string(),
Err(e) => {
let mut v = refusal::refusal_json(&e);
v["error"] = json!(e);
v.to_string()
}
}
}
/// Each method, its accuracy, what it takes, and the most qubits it holds
/// in a job's memory here.
pub fn methods(&self) -> String {
json!({ "methods": catalog::describe(self.job_bytes) }).to_string()
}
}
/// A program read as the engine reads it: `{"ok": true, ...}` with its shape
/// (and the reader's warnings under `diagnostics`), or `{"ok": false,
/// "error", "line", "code", "column", "length"}`.
#[wasm_bindgen]
pub fn engine_lint(src: &str) -> String {
job::lint(src).to_string()
}
/// The OpenQASM reader's diagnostic codes: `{"codes": [{"code", "outcome",
/// "meaning", "retired"}…]}`, for an editor to explain a refusal's `[Q103]`.
#[wasm_bindgen]
pub fn engine_diagnostic_codes() -> String {
job::diagnostic_codes().to_string()
}
/// A program's circuit as text, wrapped at `width` columns: `{"text"}`, or
/// `{"error"}`.
#[wasm_bindgen]
pub fn engine_draw(src: &str, width: u32) -> String {
match wai::qasm::parse(src) {
Ok(p) => json!({ "text": draw::draw(&p, width.max(20) as usize) }).to_string(),
Err(e) => error_json(e),
}
}
/// A program's circuit as data for a page to draw: `{"qubits", "columns",
/// "legend"}` ([`draw::layout`]), or `{"error"}`.
#[wasm_bindgen]
pub fn engine_layout(src: &str) -> String {
match wai::qasm::parse(src) {
Ok(p) => draw::layout(&p).to_string(),
Err(e) => error_json(e),
}
}
/// What the engine can say about a program before it runs: its measures and
/// its smells, each with its lines ([`critique::critique`]); `{"ok": false,
/// "error", "line"}` when it does not read.
#[wasm_bindgen]
pub fn engine_critique(src: &str) -> String {
critique::critique(src).to_string()
}
/// Whether two programs apply the same gates up to a global phase, and how
/// that was decided ([`equiv::equivalent`]).
#[wasm_bindgen]
pub fn engine_equivalent(a: &str, b: &str) -> String {
equiv::equivalent(a, b).to_string()
}
/// A program carried between formats, OpenQASM 3, QIR (LLVM text) and jeff
/// (as base64), and checked: what is written is read back and held to the
/// program by the equivalence ladder
/// ([`wai::engine::formats::convert_json`]). `request` is
/// `{"to", "program" | "program_base64", "from"?, "profile"?, "check"?}`; a
/// refusal is `{"error", "code", "codes", "outcome", "meaning"}`, its code the
/// reader's (Q700 to Q721) and the place in its message. The Studio opens a
/// QIR or jeff file through it.
#[wasm_bindgen]
pub fn engine_convert(request: &str) -> String {
let answer = serde_json::from_str::<Value>(request).map_err(|e| format!("the request is not JSON: {e}")).and_then(|r| wai::engine::formats::convert_json(&r));
answer.map(|v| v.to_string()).unwrap_or_else(|e| {
let mut r = refusal::refusal_json(&e);
r["error"] = json!(e);
r.to_string()
})
}
/// The variants a program's fixes make, each checked equivalent to it
/// ([`critique::variants`]).
#[wasm_bindgen]
pub fn engine_variants(src: &str) -> String {
critique::variants(src).to_string()
}
/// Every exact classical route to simulating a program, with its cost on it,
/// and the cheapest for each question ([`shortcuts::shortcuts`]). `thorough`
/// also searches a contraction tree: seconds to minutes on a large program.
#[wasm_bindgen]
pub fn engine_shortcuts(src: &str, thorough: bool) -> String {
shortcuts::shortcuts(src, thorough).to_string()
}
/// The verdict of a job, worked out in the page ([`verdict::of_job`]): the
/// job as a run returned it (`{"request", "result"}`, or `{"error"}` with
/// its `request`), and `intent` (JSON: one intent or a list; empty for the
/// request's own), checked within `memory_mb` MiB. The result's own verdict,
/// sealed with it, when it carries one and no other intent is given;
/// otherwise one worked out here, which says it is not sealed (`"sealed":
/// false`). `{"error"}` when the job is not one.
#[wasm_bindgen]
pub fn engine_verdict(job_json: &str, intent_json: &str, memory_mb: u32) -> String {
let job: Value = match serde_json::from_str(job_json) {
Ok(v) => v,
Err(e) => return error_json(format!("the job is not JSON: {e}")),
};
let intent = match intent_json.trim() {
"" => None,
t => match serde_json::from_str::<Value>(t) {
Ok(v) => Some(v),
Err(e) => return error_json(format!("the intent is not JSON: {e}")),
},
};
match verdict::of_job(&job, intent.as_ref(), u64::from(memory_mb.max(1)) << 20) {
Ok(v) => v.to_string(),
Err(e) => error_json(e),
}
}
/// A program repaired on the lines its diagnostics flag alone
/// ([`repair::repair`]): `options` (JSON: `{"proposed", "max_iterations",
/// "dyadic_bits", "sizes", "diagnostics", "rules"}`, or empty) as the engine
/// takes them. `{"ok", "changed", "qasm", "repairs", "needs_person",
/// "verdict"}`, or `{"error", "code"}` for a proposal rejected or choices
/// that do not read.
#[wasm_bindgen]
pub fn engine_repair(src: &str, options: &str) -> String {
let o: Value = match options.trim() {
"" => json!(true),
t => match serde_json::from_str(t) {
Ok(v) => v,
Err(e) => return error_json(format!("the options are not JSON: {e}")),
},
};
match repair::repair(src, &o) {
Ok(v) => v.to_string(),
Err(e) => {
let mut v = refusal::refusal_json(&e);
v["error"] = json!(e);
v.to_string()
}
}
}
/// Whether a job's receipt seals its request and its result, checked here:
/// `{"valid", "key", "signer"}` (the signer as a `did:key`), or `{"error"}`.
#[wasm_bindgen]
pub fn engine_verify(job_json: &str) -> String {
let v: Value = match serde_json::from_str(job_json) {
Ok(v) => v,
Err(e) => return error_json(format!("not JSON: {e}")),
};
match job::verify(&v) {
Ok((valid, key)) => {
let signer = key.as_str().and_then(job::did_of);
json!({ "valid": valid, "key": key, "signer": signer }).to_string()
}
Err(e) => error_json(e),
}
}
/// Whether an estimate's answer holds, checked here: its seal, every
/// estimate's resource receipt (one key, the frontier's naming the
/// headline's), and its request re-run to the same receipts and figures.
/// `{"valid", "signed", "receipts", "reproduced", "key", "signer",
/// "estimates"}`, or `{"error"}`.
#[wasm_bindgen]
pub fn engine_estimate_verify(body: &str) -> String {
match serde_json::from_str::<Value>(body).map_err(|e| format!("not JSON: {e}")).and_then(|v| estimate::verify(&v)) {
Ok(v) => v.to_string(),
Err(e) => error_json(e),
}
}
/// A workbench specification from its JSON, ready to judge candidates.
fn evaluator(spec: &str) -> Result<Evaluator, String> {
let v: Value = serde_json::from_str(spec).map_err(|e| format!("the specification is not JSON: {e}"))?;
Evaluator::new(Spec::from_json(&v)?)
}
/// An archive from its JSON, which must have been built for `ev`'s specification.
fn archive(ev: &Evaluator, text: &str) -> Result<Archive, String> {
let a: Archive = serde_json::from_str(text).map_err(|e| format!("the archive is not one: {e}"))?;
if !a.is_for(&ev.spec) {
return Err("this archive was built for another specification (or this one changed); start a new one".into());
}
Ok(a)
}
/// The workbench's answer: the archive, its summary, and what else was asked.
fn workbench(ev: &Evaluator, a: &Archive, extra: Value) -> String {
let mut v = json!({ "archive": a, "summary": a.summary(&ev.spec) });
if let (Some(o), Some(x)) = (v.as_object_mut(), extra.as_object()) {
o.extend(x.clone());
}
v.to_string()
}
/// The workbench in a page ([`wai::engine::discover`]): an archive for a
/// specification, generators judged by the engine and kept when they are the
/// cheapest of their cell, each sealed with the page's key.
#[wasm_bindgen]
impl QuantumEngine {
/// An archive for `spec` (its JSON), seeded with the reference:
/// `{archive, summary}`, or `{error}`.
pub fn discover_start(&self, spec: &str) -> String {
evaluator(spec)
.and_then(|ev| Archive::new_sealed(&ev, Some(&self.key)).map(|a| workbench(&ev, &a, json!({}))))
.unwrap_or_else(error_json)
}
/// `source` judged and kept in the archive if it is the cheapest of its
/// cell: `{archive, summary, outcome}`, or `{error}`.
pub fn discover_submit(&self, spec: &str, archive_json: &str, source: &str, parent: Option<String>, proposer: &str, note: Option<String>) -> String {
submit_in(&self.key, spec, archive_json, source, parent.as_deref(), proposer, note.as_deref()).unwrap_or_else(error_json)
}
/// `evaluations` more candidates from the built-in search, from `seed`:
/// `{archive, summary, kept}` (the ids kept), or `{error}`. A tab claims no
/// time and meters no energy, so the budget is evaluations alone; the
/// Studio calls it in small steps to show progress.
pub fn discover_search(&self, spec: &str, archive_json: &str, seed: u32, evaluations: u32) -> String {
search_in(&self.key, spec, archive_json, seed, evaluations).unwrap_or_else(error_json)
}
}
/// A study in a page ([`wai::engine::study`]): the participant's record
/// sealed with the page's key, and the protocol a researcher seals here too.
#[wasm_bindgen]
impl QuantumEngine {
/// `op` on the study, sealing with the page's key where it seals
/// (`seal_record`, `seal_protocol`): the answer, or `{error}`.
pub fn study(&self, op: &str, args: &str) -> String {
serde_json::from_str::<Value>(args)
.map_err(|e| format!("{op}: the arguments are not JSON: {e}"))
.and_then(|a| study::call_sealing(op, &a, &self.key))
.map(|v| v.to_string())
.unwrap_or_else(error_json)
}
}
/// A program's history in a page ([`wai::engine::versions`]), kept by the
/// page as JSON: who made each version and how, whose hand each line and gate
/// is in, and each version recorded sealed with the page's key.
#[wasm_bindgen]
impl QuantumEngine {
/// `op` on a history ([`versions::call`]), its arguments as JSON: the
/// answer, or `{error}`.
pub fn history(&self, op: &str, args: &str) -> String {
serde_json::from_str::<Value>(args)
.map_err(|e| format!("{op}: the arguments are not JSON: {e}"))
.and_then(|a| versions::call(op, &a, Some(&self.key)))
.map(|v| v.to_string())
.unwrap_or_else(error_json)
}
}
fn submit_in(key: &SigningKey, spec: &str, archive_json: &str, source: &str, parent: Option<&str>, proposer: &str, note: Option<&str>) -> Result<String, String> {
let ev = evaluator(spec)?;
let mut a = archive(&ev, archive_json)?;
let out = a.submit_sealed(&ev, source, parent, proposer, note, Some(key));
Ok(workbench(&ev, &a, json!({ "outcome": out })))
}
fn search_in(key: &SigningKey, spec: &str, archive_json: &str, seed: u32, evaluations: u32) -> Result<String, String> {
let mut ev = evaluator(spec)?;
ev.spec.budget = Budget { evaluations: Some(u64::from(evaluations)), seconds: None, joules: None };
let mut a = archive(&ev, archive_json)?;
let opts = SearchOptions { seed: u64::from(seed), max_edits: 2, key: Some(key.clone()) };
let mut kept = Vec::new();
search(&ev, &mut a, &opts, &|| 0.0, &|| None, &mut |e| kept.push(e.id.clone()));
Ok(workbench(&ev, &a, json!({ "kept": kept })))
}
/// The engine's verdict on one generator against a workbench specification,
/// without an archive ([`Evaluator::evaluate`]), or `{error}`.
#[wasm_bindgen]
pub fn engine_discover_evaluate(spec: &str, source: &str) -> String {
evaluator(spec).map(|ev| serde_json::to_string(&ev.evaluate(source)).unwrap_or_else(error_json)).unwrap_or_else(error_json)
}
fn inputs_of(inputs: &str) -> Result<wai::qasm::Inputs, String> {
serde_json::from_str(inputs).map_err(|e| format!("inputs: {e}"))
}
/// A generator linted at `inputs` (JSON, as `{"n": 5}`), its problems on the
/// generator's own lines ([`job::lint_with`]).
#[wasm_bindgen]
pub fn engine_lint_with(src: &str, inputs: &str) -> String {
inputs_of(inputs).map(|ins| job::lint_with(src, &ins).to_string()).unwrap_or_else(|e| json!({ "ok": false, "error": e }).to_string())
}
/// A generator critiqued at `inputs`: its measures there and its smells on the
/// generator's own lines, none offered as a fix ([`critique::critique_with`]).
#[wasm_bindgen]
pub fn engine_critique_with(src: &str, inputs: &str) -> String {
inputs_of(inputs).map(|ins| critique::critique_with(src, &ins).to_string()).unwrap_or_else(|e| json!({ "ok": false, "error": e }).to_string())
}
/// `op` on the person's rules for proposals ([`locks::call`]), its arguments
/// as JSON: the answer, or `{error}`.
#[wasm_bindgen]
pub fn engine_locks(op: &str, args: &str) -> String {
serde_json::from_str::<Value>(args)
.map_err(|e| format!("{op}: the arguments are not JSON: {e}"))
.and_then(|a| locks::call(op, &a))
.map(|v| v.to_string())
.unwrap_or_else(error_json)
}
/// What is new in a program ([`novelty::call`]), its arguments as JSON
/// (`qasm`, and `inputs`, `against`, `reference`, `weighed`): its nearest
/// known construction or other program, each known construction it is found
/// to be, and whether by a different route; or `{error}`.
#[wasm_bindgen]
pub fn engine_novelty(args: &str) -> String {
serde_json::from_str::<Value>(args)
.map_err(|e| format!("the arguments are not JSON: {e}"))
.and_then(|a| novelty::call(&a))
.map(|v| v.to_string())
.unwrap_or_else(error_json)
}
/// What is new in the entry `id` of an archive for `spec`, read at the
/// specification's largest size ([`discover::novelty`]), or `{error}`.
#[wasm_bindgen]
pub fn engine_discover_novelty(spec: &str, archive_json: &str, id: &str) -> String {
evaluator(spec)
.and_then(|ev| archive(&ev, archive_json).and_then(|a| discover::novelty(&ev, &a, id)))
.map(|v| v.to_string())
.unwrap_or_else(error_json)
}
/// `op` on the convergence monitor ([`converge::call`]): `history` (the
/// page's history of the program) or `cohort`: the answer, or `{error}`.
#[wasm_bindgen]
pub fn engine_converge(op: &str, args: &str) -> String {
serde_json::from_str::<Value>(args)
.map_err(|e| format!("{op}: the arguments are not JSON: {e}"))
.and_then(|a| converge::call(op, &a))
.map(|v| v.to_string())
.unwrap_or_else(error_json)
}
/// `op` on the rewrites ([`rewrite::call`]): `options`, `apply`, `simplify`,
/// `explain` or `prove`, its arguments as JSON: the answer, or `{error}`.
#[wasm_bindgen]
pub fn engine_rewrite(op: &str, args: &str) -> String {
serde_json::from_str::<Value>(args)
.map_err(|e| format!("{op}: the arguments are not JSON: {e}"))
.and_then(|a| rewrite::call(op, &a))
.map(|v| v.to_string())
.unwrap_or_else(error_json)
}
/// `op` on the person's taste model ([`taste::call`]), the profile kept by
/// the page and passed in the arguments as JSON: the answer, or `{error}`.
#[wasm_bindgen]
pub fn engine_taste(op: &str, args: &str) -> String {
serde_json::from_str::<Value>(args)
.map_err(|e| format!("{op}: the arguments are not JSON: {e}"))
.and_then(|a| taste::call(op, &a))
.map(|v| v.to_string())
.unwrap_or_else(error_json)
}
/// `op` on the debugger ([`debug::call`]): `step` (the state at a position
/// or before a line, on the path a list of outcomes chooses, with its
/// probes) or `branches` (every branch at the measurements in the middle,
/// with its weight), its arguments as JSON: the answer, or `{error}`.
#[wasm_bindgen]
pub fn engine_debug(op: &str, args: &str) -> String {
serde_json::from_str::<Value>(args)
.map_err(|e| format!("{op}: the arguments are not JSON: {e}"))
.and_then(|a| debug::call(op, &a))
.map(|v| v.to_string())
.unwrap_or_else(error_json)
}
/// The device targets every host knows by name (synthetic, made up in the
/// shapes of published formats), each with its summary: `{targets}`.
#[wasm_bindgen]
pub fn engine_targets() -> String {
json!({ "targets": wai::engine::targets::library::list() }).to_string()
}
/// A device target: a built-in target's name, or the JSON text of a target
/// document or of a snapshot in any format the engine reads. `{summary, view,
/// document}`, the view what the Studio draws (each qubit's place and errors,
/// each pair's error), or `{error}`.
#[wasm_bindgen]
pub fn engine_target(spec: &str) -> String {
use wai::engine::targets::{import, library};
let t = if spec.trim_start().starts_with('{') {
serde_json::from_str::<Value>(spec).map_err(|e| format!("the target is not JSON: {e}")).and_then(|v| import::import(&v, None, None))
} else {
library::get(spec.trim()).ok_or_else(|| format!("no built-in target named {spec:?}; the built-in targets are {}", library::names().join(", ")))
};
match t {
Ok(t) => json!({ "summary": t.summary(), "view": t.view(), "document": t.to_json() }).to_string(),
Err(e) => error_json(e),
}
}
/// A program placed on a target (a request's `target`: a built-in's name or
/// a document, as JSON) without running it: the layout, its expected
/// success, the fewest-swaps layout's and the noise derived, as a plan
/// states them; or `{error}`.
#[wasm_bindgen]
pub fn engine_target_place(src: &str, target: &str) -> String {
serde_json::from_str::<Value>(target)
.map_err(|e| format!("the target is not JSON: {e}"))
.and_then(|t| wai::engine::targets::job::placement(&json!({ "qasm": src, "target": t })))
.map(|v| v.to_string())
.unwrap_or_else(error_json)
}
/// A drawing's edit (a gate put on a wire, moved or deleted) made in the
/// program's own text ([`visual::edit`]), the edit as JSON: the new program
/// and the one change that makes it, or `{error}`.
#[wasm_bindgen]
pub fn engine_visual_edit(src: &str, edit: &str) -> String {
serde_json::from_str::<Value>(edit)
.map_err(|e| format!("the edit is not JSON: {e}"))
.and_then(|e| visual::edit(src, &e))
.map(|v| v.to_string())
.unwrap_or_else(error_json)
}
/// The circuit as a picture to keep or read: `svg` (the standalone drawing,
/// [`svg::circuit`]), `latex` (plain TikZ, [`latex::circuit`]) or
/// `description` (in words, for a screen reader, [`describe::describe`]), as
/// `{format: text}`; or `{error}`.
#[wasm_bindgen]
pub fn engine_picture(src: &str, format: &str) -> String {
wai::qasm::parse(src)
.and_then(|p| match format {
"svg" => Ok(svg::circuit::<&str>(&p, &[])),
"latex" => Ok(latex::circuit(&p)),
"description" => Ok(describe::describe(&p)),
f => Err(format!("{f}: the formats are svg, latex and description")),
})
.map(|t| Value::Object([(format.to_string(), json!(t))].into_iter().collect()).to_string())
.unwrap_or_else(error_json)
}
/// A generator written out at `inputs` (JSON, as `{"n": 5}`) as plain
/// OpenQASM: `{text}`, or `{error}`.
#[wasm_bindgen]
pub fn engine_instantiate(src: &str, inputs: &str) -> String {
inputs_of(inputs).and_then(|ins| wai::qasm::instantiate(src, &ins)).map(|text| json!({ "text": text }).to_string()).unwrap_or_else(error_json)
}
/// An answer in the answer view layer ([`answer`]), read as it streams
/// into the page: `push` each piece of text as it arrives (the lines it
/// completes come back as events), `snapshot` what can be drawn so far, and
/// `finish` the answer once the text has ended, which is the answer
/// `engine_answer_parse` gives the whole text however it was split.
#[wasm_bindgen]
pub struct AnswerStream {
inner: answer::Stream,
}
#[wasm_bindgen]
impl AnswerStream {
#[wasm_bindgen(constructor)]
#[allow(clippy::new_without_default)]
pub fn new() -> AnswerStream {
AnswerStream { inner: answer::Stream::new() }
}
/// Take `text`: the events of the lines it completes, as a JSON list.
pub fn push(&mut self, text: &str) -> String {
Value::Array(self.inner.push(text)).to_string()
}
/// What can be drawn of the lines that have arrived: each statement
/// ready, pending on one still to come, or dropped with its code.
pub fn snapshot(&self) -> String {
self.inner.snapshot().to_json().to_string()
}
/// The answer, the text having ended.
pub fn finish(&self) -> String {
self.inner.clone().finish().to_json().to_string()
}
}
/// An answer's whole text read: `{format, root, order, statements,
/// diagnostics, errors, warnings, digest, receipt}`.
#[wasm_bindgen]
pub fn engine_answer_parse(text: &str) -> String {
answer::parse(text).to_json().to_string()
}
/// The layer described for a model's system prompt: `{prompt}`.
#[wasm_bindgen]
pub fn engine_answer_prompt() -> String {
json!({ "prompt": answer::prompt() }).to_string()
}
/// Whether a stored answer's receipt marker seals what its statements give
/// when the answer is run again here, within `memory_mb` MiB: `{valid, key,
/// signer, statement, sealed}`, or `{error}`.
#[wasm_bindgen]
pub fn engine_answer_verify(text: &str, memory_mb: u32) -> String {
answer_eval::verify(text, u64::from(memory_mb.max(1)) << 20).map(|v| v.to_string()).unwrap_or_else(error_json)
}
/// The marker line a stored answer carries for its seal `statement`, from
/// the sealed value (JSON) a `@Seal` gave: `{marker}`.
#[wasm_bindgen]
pub fn engine_answer_marker(statement: &str, sealed: &str) -> String {
match serde_json::from_str::<Value>(sealed) {
Ok(v) => json!({ "marker": answer_eval::marker(statement, &v) }).to_string(),
Err(e) => error_json(format!("the seal is not JSON: {e}")),
}
}
/// An answer's `@` calls in the page, a seal signed with the page's key.
#[wasm_bindgen]
impl QuantumEngine {
/// The value of the statement `name` of an answer: its text so far
/// (`complete` false: what a stream has delivered, the statements still
/// to come pending) or whole. `{ok: true, value}`, or the engine's
/// refusal with its codes.
pub fn answer_value(&self, text: &str, name: &str, complete: bool) -> String {
let a = if complete {
answer::parse(text)
} else {
let mut s = answer::Stream::new();
s.push(text);
s.snapshot()
};
answer_eval::outcome(answer_eval::value(&a, name, &answer_eval::Host { job_bytes: self.job_bytes, key: Some(&self.key) })).to_string()
}
/// Every statement of a whole answer carried out: `{format, digest,
/// results}`.
pub fn answer_evaluate(&self, text: &str) -> String {
answer_eval::evaluate(&answer::parse(text), &answer_eval::Host { job_bytes: self.job_bytes, key: Some(&self.key) }).to_string()
}
}
/// A correctness record ([`telemetry::record`]) from what the page saw,
/// checked and kept to its fields; or `{error}`.
#[wasm_bindgen]
pub fn engine_telemetry_record(fields: &str) -> String {
serde_json::from_str::<Value>(fields).map_err(|e| format!("the record is not JSON: {e}")).and_then(|v| telemetry::record(&v)).map(|v| v.to_string()).unwrap_or_else(error_json)
}
/// The failures among records (a JSON list) as an evaluation corpus in the
/// conformance format ([`telemetry::corpus`]); or `{error}`.
#[wasm_bindgen]
pub fn engine_telemetry_corpus(records: &str) -> String {
match serde_json::from_str::<Value>(records) {
Ok(Value::Array(list)) => telemetry::corpus(&list).to_string(),
Ok(_) => error_json("the records are a JSON list"),
Err(e) => error_json(format!("the records are not JSON: {e}")),
}
}
/// The circuits course in `locale` ([`course::course`]): its units with their
/// lessons, the companion courses, and where progress is kept; `{error}`
/// otherwise. A locale tag the course is not written in reads in English.
#[wasm_bindgen]
pub fn engine_course(locale: &str) -> String {
course::course(locale).map(|v| v.to_string()).unwrap_or_else(error_json)
}
/// One lesson in `locale` ([`course::lesson`]): its text, task, starter
/// program, hints and what the program must do; the program a check compares
/// against is never in it.
#[wasm_bindgen]
pub fn engine_course_lesson(id: &str, locale: &str) -> String {
course::lesson(id, locale).map(|v| v.to_string()).unwrap_or_else(error_json)
}
/// A program checked against lesson `id`'s exercise ([`course::check`]),
/// each run within `memory_mb` MiB: whether it passes, each case's verdict,
/// each constraint, what went wrong in `locale`, and where to look.
#[wasm_bindgen]
pub fn engine_course_check(id: &str, src: &str, locale: &str, memory_mb: u32) -> String {
course::check(id, src, u64::from(memory_mb.max(1)) << 20, locale).map(|v| v.to_string()).unwrap_or_else(error_json)
}
/// Hint `level` (from 1) of lesson `id` ([`course::hint`]), with the
/// check's pointer for `src` (none when it is empty).
#[wasm_bindgen]
pub fn engine_course_hint(id: &str, src: &str, level: u32, locale: &str, memory_mb: u32) -> String {
course::hint(id, src, level.max(1) as usize, u64::from(memory_mb.max(1)) << 20, locale).map(|v| v.to_string()).unwrap_or_else(error_json)
}
#[cfg(test)]
mod tests {
use super::*;
/// A check every build answers with the same bytes: the noisy lesson's
/// starter, its density matrix and its gaps in Chinese.
pub(super) const COURSE_CHECK: (&str, &str) = ("noise", "zh-CN");
/// BLAKE3 of [`engine_course_check`]'s answer for [`COURSE_CHECK`] on the
/// lesson's starter, at 512 MiB, as the native build and the wasm32 one write it.
/// A check names the engine that made it (`engine::schema::stamp_as`), so this
/// moves with every release of wai-quantum (374b400e… before checks named it,
/// 969b2c1c… at 0.7.0, 1a9aa0ad… at 0.8.0, 49a9fdb8… at 0.8.1).
pub(super) const COURSE_DIGEST: &str = "49a9fdb8f46840e376e8d36a190feb7c9bf10491511cae7e93349c687e60877c";
pub(super) fn starter(id: &str) -> String {
let l: Value = serde_json::from_str(&engine_course_lesson(id, "en")).unwrap();
l["starter"].as_str().unwrap().to_string()
}
/// The course in the page: the course in either language, a lesson with
/// no solution in it, a solution passing by proof, a wrong program with
/// what went wrong in Chinese, a hint with its pointer, and the same bytes
/// as every other build.
#[test]
fn the_course_is_read_and_checked_in_the_page() {
let c: Value = serde_json::from_str(&engine_course("zh_CN.UTF-8")).unwrap();
assert_eq!((c["locale"].as_str(), c["lessons"].as_u64()), (Some("zh-CN"), Some(21)), "{c}");
assert!(c["translation"].as_str().unwrap().starts_with("machine-assisted"));
let l = engine_course_lesson("ghz", "en");
assert!(!l.contains("\"reference\"") && !l.contains("cx q[0], q[2]"), "{l}");
let bell = "OPENQASM 3.0;\nqubit[2] q;\nbit[2] c;\nh q[0];\ncx q[0], q[1];\nc = measure q;\n";
let ok: Value = serde_json::from_str(&engine_course_check("bell", bell, "en", 512)).unwrap();
assert_eq!((ok["passed"].as_bool(), ok["level"].as_str()), (Some(true), Some("proof")), "{ok}");
let no: Value = serde_json::from_str(&engine_course_check("bell", "OPENQASM 3.0;\nqubit[2] q;\nbit[2] c;\nh q[0];\nc = measure q;\n", "zh-CN", 512)).unwrap();
assert!(no["passed"] == false && no["what_went_wrong"][0]["text"].as_str().unwrap().contains("你的程序给出"), "{no}");
let h: Value = serde_json::from_str(&engine_course_hint("bell", "OPENQASM 3.0;\nqubit[2] q;\nbit[2] c;\nc = measure q;\n", 1, "en", 512)).unwrap();
assert!(h["pointer"].as_str().unwrap().contains("outcome") && h["more"] == true, "{h}");
assert!(engine_course_check("nowhere", "", "en", 512).contains("no such lesson"));
let (id, loc) = COURSE_CHECK;
let out = engine_course_check(id, &starter(id), loc, 512);
assert_eq!(blake3::hash(out.as_bytes()).to_hex().as_str(), COURSE_DIGEST, "{out}");
}
const CHAIN: &str = "OPENQASM 3.0;\ninput uint n;\nqubit[n] q;\nh q[0];\nfor uint i in [0:n-2] { cx q[i], q[i + 1]; }\n";
const STAR: &str = "OPENQASM 3.0;\ninput uint n;\nqubit[n] q;\nh q[0];\nfor uint i in [1:n-1] { cx q[0], q[i]; }\n";
const ANSWER: &str = "root = Answer([bell, counts, check, seal])\n```qasm bell\nOPENQASM 3.0;\nqubit[2] q;\nbit[2] c;\nh q[0];\ncx q[0], q[1];\nc = measure q;\n```\ncounts = Histogram(@Sample(bell, 1000))\ncheck = Verdict(@Check(bell, {\"00\": 0.5, \"11\": 0.5}))\nseal = Receipt(@Seal([bell, counts, check]))\n";
/// An answer streamed into the page a few characters at a time: the
/// events as lines complete, the histogram pending until its program
/// arrives, the finished answer the one the whole text gives, its calls
/// run in the page and its seal verifying when the stored answer runs
/// again.
#[test]
fn an_answer_streams_into_the_page_and_its_seal_verifies() {
let mut s = AnswerStream::new();
let mut events = Vec::new();
for piece in ANSWER.as_bytes().chunks(7).map(|c| std::str::from_utf8(c).unwrap()) {
let ev: Value = serde_json::from_str(&s.push(piece)).unwrap();
events.extend(ev.as_array().unwrap().iter().map(|e| e["event"].as_str().unwrap().to_string()));
// The root is drawn before the views it lists have arrived.
let snap: Value = serde_json::from_str(&s.snapshot()).unwrap();
if let Some(root) = snap["statements"].as_array().unwrap().iter().find(|x| x["name"] == "root") {
assert_eq!(root["status"], "ready", "{snap}");
}
}
assert!(events.contains(&"program".to_string()) && events.iter().filter(|e| *e == "statement").count() == 4, "{events:?}");
let whole: Value = serde_json::from_str(&engine_answer_parse(ANSWER)).unwrap();
assert_eq!(serde_json::from_str::<Value>(&s.finish()).unwrap(), whole);
assert_eq!(whole["errors"], 0, "{whole}");
let e = QuantumEngine::new(&[3u8; 32], 512).unwrap();
let counts: Value = serde_json::from_str(&e.answer_value(ANSWER, "counts", true)).unwrap();
assert_eq!(counts["value"]["result"]["counts"].as_object().unwrap().values().filter_map(Value::as_u64).sum::<u64>(), 1000, "{counts}");
let seal: Value = serde_json::from_str(&e.answer_value(ANSWER, "seal", true)).unwrap();
let m: Value = serde_json::from_str(&engine_answer_marker("seal", &seal["value"].to_string())).unwrap();
let stored = format!("{ANSWER}{}\n", m["marker"].as_str().unwrap());
let v: Value = serde_json::from_str(&engine_answer_verify(&stored, 512)).unwrap();
assert_eq!(v["valid"], true, "{v}");
// The stored conformance case was written natively with the same key: the page seals the same bytes.
let bundle: Value = serde_json::from_str(include_str!("../../quantum-conformance/answers/bundle.json")).unwrap();
let native = bundle["cases"].as_array().unwrap().iter().find(|c| c["name"] == "bell-stored").unwrap()["answer"].as_str().unwrap().to_string();
assert_eq!(native, stored);
}
#[test]
fn a_correctness_record_and_its_corpus_in_the_page() {
let r: Value = serde_json::from_str(&engine_telemetry_record(&json!({ "program": "OPENQASM 3.0;\nqubit[1] q;\n", "intent": { "distribution": { "0": 1.0 } }, "codes": [], "verdict": { "level": "proof", "holds": false }, "decision": "pending" }).to_string())).unwrap();
assert_eq!(r["format"], "wai.quantum.telemetry/1", "{r}");
assert!(engine_telemetry_record("{\"codes\": [\"nope\"]}").contains("error"));
let c: Value = serde_json::from_str(&engine_telemetry_corpus(&json!([r]).to_string())).unwrap();
assert_eq!(c["cases"][0]["covers"][0], "its intent did not hold", "{c}");
}
/// A request every build compiles to the same bytes.
pub(super) const COMPILE_REQUEST: &str = "{\"qasm\": \"OPENQASM 3.0; qubit[2] q; h q[0]; rz(0.3) q[0]; cx q[0], q[1]; ry(1.1) q[1];\", \"epsilon\": 1e-6, \"level\": 2}";
/// BLAKE3 of the sealed compile of [`COMPILE_REQUEST`] with the seed
/// `[9; 32]`, as the native build and the wasm32 one write it: its result
/// names the engine and its schema (`engine::schema::stamp_as`), and its
/// certificate names its gate set `basis` (04a03934… when it was `target`).
/// The engine's version is among the sealed bytes, so this moves with every
/// release of wai-quantum (0a165415… at 0.6.16, ac948133… at 0.7.0, beffb3cb… at 0.8.0,
/// 198ea9bd… at 0.8.1).
/// The compile sealed before either, whose bytes hashed to 14db506e…, is
/// kept in wai-quantum's `src/engine/testdata/compile-legacy.json` and still
/// verifies.
/// A pulse program, and the digest of its run's final density matrix:
/// the same bits natively and in wasm32 (the engine pins it too).
pub(super) const PULSE_XM: &str = "OPENQASM 3.0;\ndefcalgrammar \"openpulse\";\ncal {\n extern port d0;\n extern port m0;\n extern port a0;\n frame q0 = newframe(d0, 5.0e9, 0);\n frame r0 = newframe(m0, 7.1e9, 0);\n frame c0 = newframe(a0, 7.1e9, 0);\n}\ndefcal x $0 { play(q0, gaussian(0.4, 64dt, 16dt)); }\ndefcal measure $0 -> bit { play(r0, constant(0.1, 200dt)); return capture_v2(c0, 200dt); }\nbit[1] c;\nx $0;\nc[0] = measure $0;\n";
pub(super) const PULSE_XM_DENSITY: &str = "03c0c48a8a3568fdd86e792633c5b4ea98eca3d09dc40d028bb50e13c489828b";
pub(super) const COMPILE_DIGEST: &str = "198ea9bd9431f491a02dbd3af3a4b1309999837dfb0916902b41023aeab21040";
/// A compile in the page: Clifford+T within the budget, every pass
/// recorded, the certificate sealed with the page's key and checked
/// here, the compiled program running bit-exact, and the same bytes as
/// every other build.
#[test]
fn a_compile_is_sealed_in_the_page_and_runs_bit_exact() {
let e = QuantumEngine::new(&[9u8; 32], 512).unwrap();
let out = e.compile(COMPILE_REQUEST);
let body: Value = serde_json::from_str(&out).unwrap();
let cert = &body["result"]["certificate"];
assert!(cert["epsilon"]["bound"].as_f64().unwrap() <= 1e-6, "{cert}");
assert_eq!(cert["output"]["counts"]["rotations"], 0);
let v: Value = serde_json::from_str(&engine_verify(&out)).unwrap();
assert_eq!(v["valid"], true, "{v}");
let run: Value = serde_json::from_str(&e.run(&json!({ "qasm": body["result"]["qasm"], "shots": 100 }).to_string())).unwrap();
assert_eq!(run["method"], "exact", "{run}");
assert_eq!(blake3::hash(out.as_bytes()).to_hex().as_str(), COMPILE_DIGEST);
assert!(e.compile("{\"qasm\": \"qubit[1] q;\", \"basis\": \"native\"}").contains("error"));
}
/// A request every build estimates to the same bytes.
pub(super) const ESTIMATE_REQUEST: &str = "{\"qasm\": \"OPENQASM 3.0; qubit[4] q; h q; ctrl(3) @ x q[0], q[1], q[2], q[3]; rz(0.3) q[0]; ry(1.1) q[2]; t q[1];\", \"budget\": 1e-3, \"qubit\": \"us-e3\", \"max_slowdown\": 64}";
/// BLAKE3 of the sealed estimate of [`ESTIMATE_REQUEST`] with the seed
/// `[9; 32]`, as the native build and the wasm32 one write it: its result
/// names the engine and its schema (`engine::schema::stamp_as`), which
/// moved it from aaa42bc8…, the estimate sealed before. The engine's
/// version is among the sealed bytes, so this moves with every release of
/// wai-quantum (0cd25cf6… at 0.6.16, 8715e76b… at 0.7.0, db90b147… at 0.8.0,
/// acbd7208… at 0.8.1).
pub(super) const ESTIMATE_DIGEST: &str = "acbd7208b4a229240bbe3125636f430f680e8d89344682966396b7693b0d7938";
/// An estimate in the page: the counts (a ladder through an ancilla), the
/// frontier, every receipt sealed with the page's key, the seal checked
/// by engine_verify, the request re-run by engine_estimate_verify, and the
/// same bytes as every other build.
#[test]
fn an_estimate_is_sealed_in_the_page_and_re_runs() {
let e = QuantumEngine::new(&[9u8; 32], 512).unwrap();
let out = e.estimate(ESTIMATE_REQUEST);
let body: Value = serde_json::from_str(&out).unwrap();
let c = &body["result"]["counts"];
assert_eq!((c["logical_qubits"].as_u64(), c["toffolis"].as_u64(), c["rotations"].as_u64(), c["ancillas"].as_u64()), (Some(5), Some(3), Some(2), Some(1)), "{c}");
assert_eq!(body["result"]["estimate"]["receipt"]["kind"], "quantum-resource");
let v: Value = serde_json::from_str(&engine_verify(&out)).unwrap();
assert_eq!(v["valid"], true, "{v}");
let r: Value = serde_json::from_str(&engine_estimate_verify(&out)).unwrap();
assert_eq!((r["valid"].as_bool(), r["reproduced"].as_bool()), (Some(true), Some(true)), "{r}");
assert_eq!(blake3::hash(out.as_bytes()).to_hex().as_str(), ESTIMATE_DIGEST);
assert!(e.estimate("{\"qasm\": \"qubit[1] q;\", \"qubit\": \"nowhere\"}").contains("[QE08]"));
}
/// The workbench in the page: an archive started, a generator judged and
/// kept, a search, every seal holding, and an archive refused for another
/// specification.
#[test]
fn the_workbench_runs_and_seals_in_the_page() {
let e = QuantumEngine::new(&[9u8; 32], 512).unwrap();
let spec = json!({ "name": "ghz", "task": "prepares", "reference": CHAIN, "inputs": { "n": [3, 5] }, "cost": { "depth": 1.0 }, "axes": ["two_qubit", "depth"] }).to_string();
let started: Value = serde_json::from_str(&e.discover_start(&spec)).unwrap();
assert_eq!(started["summary"]["stats"]["kept"], 1, "{started}");
let a = started["archive"].to_string();
let sub: Value = serde_json::from_str(&e.discover_submit(&spec, &a, STAR, Some("e0".into()), "person", None)).unwrap();
assert_eq!(sub["outcome"]["evaluation"]["verified"], true, "{sub}");
let searched: Value = serde_json::from_str(&e.discover_search(&spec, &sub["archive"].to_string(), 5, 10)).unwrap();
assert_eq!(searched["summary"]["stats"]["evaluations"], 2 + 10);
let back: Archive = serde_json::from_value(searched["archive"].clone()).unwrap();
assert!(back.verify().iter().all(|(_, ok)| *ok));
let other = spec.replace("\"depth\":1.0", "\"depth\":2.0");
assert_ne!(other, spec);
assert!(e.discover_submit(&other, &a, STAR, None, "person", None).contains("another specification"));
let v: Value = serde_json::from_str(&engine_discover_evaluate(&spec, STAR)).unwrap();
assert_eq!(v["strength"], "state");
let lint: Value = serde_json::from_str(&engine_lint_with(CHAIN, "{\"n\": 4}")).unwrap();
assert_eq!((lint["qubits"].as_u64(), lint["gates"].as_u64()), (Some(4), Some(4)), "{lint}");
let crit: Value = serde_json::from_str(&engine_critique_with(CHAIN, "{\"n\": 4}")).unwrap();
assert_eq!(crit["depth"], 4);
let inst: Value = serde_json::from_str(&engine_instantiate(CHAIN, "{\"n\": 3}")).unwrap();
assert!(inst["text"].as_str().unwrap().contains("cx q[1], q[2];"), "{inst}");
}
/// The history in the page: recorded and sealed with the page's key, and
/// the gates in each hand.
#[test]
fn the_history_records_and_blames_in_the_page() {
let e = QuantumEngine::new(&[9; 32], 64).unwrap();
let bell = "OPENQASM 3.0;\nqubit[2] q;\nh q[0];\ncx q[0], q[1];\n";
let r: Value = serde_json::from_str(&e.history("start", &json!({ "source": bell, "by": { "kind": "origin", "name": "example" }, "at": 1 }).to_string())).unwrap();
let proposed = format!("{bell}x q[1];\n");
let r: Value = serde_json::from_str(&e.history("propose", &json!({ "history": r["history"], "parent": "v0", "proposed": proposed, "accepted": [0], "by": { "kind": "assistant", "name": "m" }, "at": 2 }).to_string())).unwrap();
let b: Value = serde_json::from_str(&e.history("blame", &json!({ "history": r["history"], "version": "v1" }).to_string())).unwrap();
assert_eq!(b["gates"], json!(["origin", "origin", "assistant"]), "{b}");
let seal = &r["history"]["versions"][1]["seal"];
assert_eq!(seal["key"].as_str().map(str::len), Some(64), "{seal}");
assert!(e.history("nonsense", "{}").contains("no such call"));
}
/// The rules in the page: a change in a held block, and one adding a gate
/// the rules do not allow, are named with their rule.
#[test]
fn the_rules_check_a_proposal_in_the_page() {
let base = "OPENQASM 3.0;\nqubit[2] q;\n// @lock\nh q[0];\n// @unlock\ncx q[0], q[1];\n";
let proposed = base.replace("h q[0];", "h q[1];") + "cz q[0], q[1];\n";
let v: Value = serde_json::from_str(&engine_locks("check", &json!({ "base": base, "proposed": proposed, "locks": { "gates": ["h", "cx"] } }).to_string())).unwrap();
let rules: Vec<&str> = v["changes"].as_array().unwrap().iter().map(|c| c["breaches"][0]["rule"].as_str().unwrap()).collect();
assert_eq!(rules, ["held", "gates"], "{v}");
let h: Value = serde_json::from_str(&engine_locks("held", &json!({ "source": base }).to_string())).unwrap();
assert_eq!(h["ops"], json!([0]), "{h}");
assert!(engine_locks("check", "not json").contains("not JSON"));
}
/// What is new in the page: a reversed chain is the GHZ state by a
/// different route; an archive's entry is read against the others.
#[test]
fn novelty_is_read_in_the_page() {
let ladder = "OPENQASM 3.0;\ninput uint n;\nqubit[n] q;\nh q[n - 1];\nfor uint i in [1:n-1] { cx q[n - i], q[n - i - 1]; }\n";
let v: Value = serde_json::from_str(&engine_novelty(&json!({ "qasm": ladder, "inputs": { "n": 5 } }).to_string())).unwrap();
assert!(v["rediscovers"].as_array().unwrap().iter().any(|r| r["route"] == "a different route"), "{v}");
assert!(engine_novelty("{\"qasm\": \"qubit[1] q; foo q[0];\"}").contains("does not read"));
let e = QuantumEngine::new(&[9u8; 32], 512).unwrap();
let spec = json!({ "name": "ghz", "task": "prepares", "reference": CHAIN, "inputs": { "n": [3, 5] }, "cost": { "depth": 1.0 }, "axes": ["two_qubit", "depth"] }).to_string();
let started: Value = serde_json::from_str(&e.discover_start(&spec)).unwrap();
let doubling = "OPENQASM 3.0;\ninput uint n;\nqubit[n] q;\nh q[0];\nfor uint k in [0:n] { for uint i in [0:2**k - 1] { if (2**k < n && i + 2**k < n) { cx q[i], q[i + 2**k]; } } }\n";
let sub: Value = serde_json::from_str(&e.discover_submit(&spec, &started["archive"].to_string(), doubling, Some("e0".into()), "person", None)).unwrap();
let id = sub["outcome"]["kept"].as_str().expect("the doubling is kept");
let n: Value = serde_json::from_str(&engine_discover_novelty(&spec, &sub["archive"].to_string(), id)).unwrap();
assert_eq!(n["entry"], id, "{n}");
assert!(n["rediscovers"].as_array().unwrap().iter().any(|r| r["name"] == "GHZ, by doubling" && r["route"] == "the same construction"), "{n}");
assert!(n["unasked"].is_array(), "{n}");
assert!(engine_discover_novelty(&spec, &sub["archive"].to_string(), "e99").contains("no such entry"));
}
/// A study in the page: a protocol sealed, the page's condition, a probe
/// scored and a record sealed with the page's key and measured.
#[test]
fn a_study_runs_in_the_page() {
let e = QuantumEngine::new(&[9; 32], 64).unwrap();
let protocol = json!({ "study": "s", "hypotheses": ["h"], "primary": "unassisted", "conditions": [{ "name": "a" }, { "name": "b", "flags": { "taste": false } }], "control": "a", "analysis": { "resamples": 200, "seed": 1, "level": 0.95 } });
let sealed: Value = serde_json::from_str(&e.study("seal_protocol", &json!({ "protocol": protocol }).to_string())).unwrap();
let open: Value = serde_json::from_str(&e.study("open_protocol", &json!({ "sealed": sealed }).to_string())).unwrap();
let digest = open["digest"].as_str().unwrap().to_string();
let me: Value = serde_json::from_str(&e.study("assign", &json!({ "sealed": sealed, "participant": e.signer_did() }).to_string())).unwrap();
let s: Value = serde_json::from_str(&e.study("score_probe", &json!({ "probe": "swap", "qasm": "OPENQASM 3.0;\nqubit[2] q;\ncx q[0], q[1];\ncx q[1], q[0];\ncx q[0], q[1];\n" }).to_string())).unwrap();
assert_eq!(s["score"], 1.0, "{s}");
let rec: Value = serde_json::from_str(&e.study("seal_record", &json!({ "record": { "protocol": digest, "condition": me["condition"], "probes": [{ "probe": "swap", "source": "OPENQASM 3.0;\nqubit[2] q;\ncx q[0], q[1];\ncx q[1], q[0];\ncx q[0], q[1];\n" }] } }).to_string())).unwrap();
let report: Value = serde_json::from_str(&e.study("cohort", &json!({ "sealed": sealed, "records": [rec] }).to_string())).unwrap();
assert_eq!(report["included"], 1, "{report}");
assert!(e.study("nonsense", "{}").contains("no such call"));
}
/// The convergence monitor in the page, on a history the page keeps.
#[test]
fn convergence_is_measured_in_the_page() {
let e = QuantumEngine::new(&[9; 32], 64).unwrap();
let start = "OPENQASM 3.0;\nqubit[2] q;\n";
let model = "OPENQASM 3.0;\nqubit[2] q;\nh q[0];\ncx q[0], q[1];\n";
let r: Value = serde_json::from_str(&e.history("start", &json!({ "source": start, "by": { "kind": "person" }, "at": 1 }).to_string())).unwrap();
let r: Value = serde_json::from_str(&e.history("propose", &json!({ "history": r["history"], "parent": "v0", "proposed": model, "accepted": [0], "by": { "kind": "assistant", "name": "m" }, "at": 2 }).to_string())).unwrap();
let r: Value = serde_json::from_str(&e.history("commit", &json!({ "history": r["history"], "parent": "v1", "source": format!("{model}x q[1];\n"), "by": { "kind": "person" }, "at": 3 }).to_string())).unwrap();
let c: Value = serde_json::from_str(&engine_converge("history", &json!({ "history": r["history"] }).to_string())).unwrap();
assert_eq!((c["converging"].as_bool(), c["series"].as_array().map(Vec::len)), (Some(true), Some(1)), "{c}");
assert!(engine_converge("cohort", "{}").contains("programs"));
}
/// The rewrites in the page: each one the program admits as an edit to
/// its lines, and an optimisation explained as a chain.
#[test]
fn rewrites_are_offered_and_explained_in_the_page() {
let src = "OPENQASM 3.0;\nqubit[2] q;\nx q[1];\ncx q[0], q[1];\nx q[1];\n";
let o: Value = serde_json::from_str(&engine_rewrite("options", &json!({ "qasm": src }).to_string())).unwrap();
assert!(o["options"].as_array().unwrap().iter().any(|x| x["rule"] == "through" && x["id"] == "through:3,5"), "{o}");
let e: Value = serde_json::from_str(&engine_rewrite("explain", &json!({ "a": src, "b": "OPENQASM 3.0;\nqubit[2] q;\ncx q[0], q[1];\n" }).to_string())).unwrap();
assert_eq!(e["found"], true, "{e}");
assert!(engine_rewrite("nonsense", "{}").contains("no such call"));
}
/// The taste model in the page: a choice between programs the engine
/// proves equal is kept in the profile the page holds, and ranks.
#[test]
fn taste_is_learned_and_ranks_in_the_page() {
let bell = "OPENQASM 3.0;\nqubit[2] q;\nh q[0];\ncx q[0], q[1];\n";
let padded = format!("{bell}cx q[0], q[1];\ncx q[0], q[1];\n");
let r: Value = serde_json::from_str(&engine_taste("choose", &json!({ "chosen": bell, "other": padded, "part": "economy" }).to_string())).unwrap();
assert_eq!(r["summary"]["choices"], 1, "{r}");
let ranked: Value = serde_json::from_str(&engine_taste("rank", &json!({ "profile": r["profile"], "candidates": [{ "name": "padded", "qasm": padded }, { "name": "bell", "qasm": bell }] }).to_string())).unwrap();
assert_eq!(ranked["ranked"][0]["name"], "bell", "{ranked}");
assert!(engine_taste("choose", &json!({ "chosen": bell, "other": "OPENQASM 3.0;\nqubit[2] q;\n" }).to_string()).contains("does not prove"));
}
fn bell(extra: &str) -> String {
format!("{{\"qasm\": \"OPENQASM 3.0; qubit[2] q; h q[0]; cx q[0], q[1];\"{extra}}}")
}
/// A job run in the tab is the service's form, signed with the page's key,
/// and its receipt checks there; a changed result does not.
#[test]
fn a_job_runs_signs_and_verifies_in_the_page() {
let e = QuantumEngine::new(&[9u8; 32], 512).unwrap();
let body: Value = serde_json::from_str(&e.run(&bell(", \"shots\": 500, \"observables\": [\"Z0 Z1\"]"))).unwrap();
assert_eq!(body["method"], "stabilizer", "{body}");
assert_eq!(body["result"]["expectations"][0]["value"], 1.0);
assert_eq!(body["result"]["energy"]["unmetered"], UNMETERED);
let v: Value = serde_json::from_str(&engine_verify(&body.to_string())).unwrap();
assert_eq!(v["valid"], true, "{v}");
assert_eq!(v["signer"], e.signer_did());
let mut forged = body.clone();
forged["result"]["expectations"][0]["value"] = json!(-1.0);
let v: Value = serde_json::from_str(&engine_verify(&forged.to_string())).unwrap();
assert_eq!(v["valid"], false, "{v}");
}
/// Any angle runs, on the double-precision state vector.
#[test]
fn a_rotation_runs_on_the_state_vector() {
let e = QuantumEngine::new(&[9u8; 32], 512).unwrap();
let req = r#"{"qasm": "OPENQASM 3.0; qubit[1] q; rx(0.3) q[0];", "observables": ["Z0"]}"#;
let body: Value = serde_json::from_str(&e.run(req)).unwrap();
assert_eq!(body["method"], "statevector", "{body}");
assert!((body["result"]["expectations"][0]["value"].as_f64().unwrap() - 0.3f64.cos()).abs() < 1e-12, "{body}");
}
/// What the page cannot run says why: a job too large for the tab's
/// memory, a program the reader refuses, a request that is not JSON.
#[test]
fn what_does_not_run_says_why() {
let e = QuantumEngine::new(&[9u8; 32], 64).unwrap();
let wide = r#"{"qasm": "OPENQASM 3.0; qubit[30] q; rx(0.3) q; cx q[0], q[29];", "amplitudes": ["000000000000000000000000000000"], "method": "statevector"}"#;
let r: Value = serde_json::from_str(&e.run(wide)).unwrap();
assert!(r["error"].as_str().unwrap().contains("statevector holds at most"), "{r}");
let r: Value = serde_json::from_str(&e.run(r#"{"qasm": "qubit[1] q; foo q[0];"}"#)).unwrap();
assert!(r["error"].as_str().unwrap().contains("foo"), "{r}");
let r: Value = serde_json::from_str(&e.run("not json")).unwrap();
assert!(r["error"].as_str().unwrap().starts_with("the job is not JSON"), "{r}");
assert!(QuantumEngine::new(&[1u8; 31], 64).is_err());
}
#[test]
fn plan_lint_draw_and_methods_answer_as_json() {
let e = QuantumEngine::new(&[9u8; 32], 512).unwrap();
let p: Value = serde_json::from_str(&e.plan(&bell(""))).unwrap();
assert_eq!(p["method"], "stabilizer", "{p}");
let l: Value = serde_json::from_str(&engine_lint("qubit[1] q;\nfoo q[0];")).unwrap();
assert_eq!(l["line"], 2, "{l}");
let d: Value = serde_json::from_str(&engine_draw("qubit[2] q; h q[0]; cx q[0], q[1];", 80)).unwrap();
assert!(d["text"].as_str().unwrap().contains('⊕'), "{d}");
let l: Value = serde_json::from_str(&engine_layout("qubit[2] q; h q[0]; cx q[0], q[1];")).unwrap();
assert_eq!(l["columns"][1][0]["cells"], serde_json::json!([[0, "●"], [1, "⊕"]]), "{l}");
let m: Value = serde_json::from_str(&e.methods()).unwrap();
assert!(m["methods"].as_array().unwrap().iter().any(|x| x["method"] == "cutrank"), "{m}");
}
/// A run with an intent carries its verdict sealed; the page works the
/// same verdict out again, and one for an intent given after the run, which
/// it says is not sealed.
#[test]
fn a_verdict_is_sealed_in_the_page_and_worked_out_there_again() {
let e = QuantumEngine::new(&[9u8; 32], 512).unwrap();
let bell = "OPENQASM 3.0;\nqubit[2] q;\nbit[2] c;\nh q[0];\ncx q[0], q[1];\nc = measure q;\n";
let body: Value = serde_json::from_str(&e.run(&json!({ "qasm": bell, "shots": 50, "intent": { "distribution": { "00": 0.5, "11": 0.5 } } }).to_string())).unwrap();
let sealed = &body["result"]["verdict"];
assert_eq!((sealed["level"].as_str(), sealed["holds"].as_bool()), (Some("proof"), Some(true)), "{body}");
let again: Value = serde_json::from_str(&engine_verdict(&body.to_string(), "", 512)).unwrap();
assert_eq!((again["level"].as_str(), again["sealed"].as_bool()), (Some("proof"), Some(true)), "{again}");
// An intent given after the run: worked out here, not sealed.
let later: Value = serde_json::from_str(&engine_verdict(&body.to_string(), r#"{"distribution": {"00": 1.0}}"#, 512)).unwrap();
assert_eq!((later["level"].as_str(), later["holds"].as_bool(), later["sealed"].as_bool()), (Some("proof"), Some(false), Some(false)), "{later}");
// A refusal: its code, and with a verdict asked for, the verdict.
let refused: Value = serde_json::from_str(&e.run(&json!({ "qasm": "qubit[1] q; foo q[0];", "verdict": true }).to_string())).unwrap();
assert_eq!((refused["code"].as_str(), refused["verdict"]["level"].as_str()), (Some("Q103"), Some("refused")), "{refused}");
let from_error: Value = serde_json::from_str(&engine_verdict(&json!({ "request": { "qasm": "qubit[1] q; foo q[0];" }, "error": refused["error"] }).to_string(), "", 512)).unwrap();
assert_eq!(from_error["level"], "refused", "{from_error}");
assert!(engine_verdict("not json", "", 512).contains("error"));
}
#[test]
fn a_repair_keeps_to_the_flagged_lines_in_the_page() {
let r: Value = serde_json::from_str(&engine_repair("OPENQASM 3.0;\nqubit[1] q\nh q[0];\n", "")).unwrap();
assert_eq!((r["qasm"].as_str(), r["repairs"][0]["code"].as_str()), (Some("OPENQASM 3.0;\nqubit[1] q;\nh q[0];\n"), Some("Q004")), "{r}");
let x: Value = serde_json::from_str(&engine_repair("OPENQASM 3.0;\nqubit[1] q;\nfoo q[0];\n", r#"{"proposed": "OPENQASM 3.0;\nqubit[2] q;\nh q[0];\n"}"#)).unwrap();
assert_eq!(x["code"], "J021", "{x}");
let t: Value = serde_json::from_str(&engine_diagnostic_codes()).unwrap();
assert!(t["job_codes"].as_array().unwrap().iter().any(|c| c["code"] == "J021"), "{t}");
}
#[test]
fn the_readers_codes_and_its_whole_language_answer_in_the_page() {
let l: Value = serde_json::from_str(&engine_lint("qubit[1] q;\npow(0.5) @ U(0.1, 0.2, 0.3) q[0];")).unwrap();
assert_eq!((l["code"].as_str(), l["line"].as_u64(), l["column"].as_u64()), (Some("Q205"), Some(2), Some(1)), "{l}");
let t: Value = serde_json::from_str(&engine_diagnostic_codes()).unwrap();
assert!(t["codes"].as_array().unwrap().iter().any(|c| c["code"] == "Q205" && c["outcome"] == "refused"), "{t}");
// A subroutine, an inverse and a power, run in the page.
let e = QuantumEngine::new(&[9u8; 32], 512).unwrap();
let src = "OPENQASM 3.1;\nqubit[2] q;\nbit[2] c;\ndef bell(qubit a, qubit b) { h a; cx a, b; }\nbell(q[0], q[1]);\ninv @ cx q[0], q[1];\ninv @ h q[0];\npow(2) @ x q[1];\nc = measure q;";
let body: Value = serde_json::from_str(&e.run(&json!({ "qasm": src, "shots": 50 }).to_string())).unwrap();
assert_eq!(body["result"]["counts"], json!({ "00": 50 }), "{body}");
}
/// The QIR the conformance set pins for its Clifford+T program
/// (`wai/quantum-conformance/formats/qasm/clifford_t.qasm`), which every
/// build writes to the same bytes.
pub(super) const CLIFFORD_T: &str = include_str!("../../quantum-conformance/formats/qasm/clifford_t.qasm");
pub(super) const CLIFFORD_T_QIR: &str = "967659b446471c62697f49df341972a45f47bef59d3b2fe26bfefc6670f6a50d";
/// A program carried between every pair of formats in the page, each
/// conversion checked, and a refusal with its code and line.
#[test]
fn a_program_converts_between_formats_in_the_page() {
let qir: Value = serde_json::from_str(&engine_convert(&json!({ "program": CLIFFORD_T, "to": "qir" }).to_string())).unwrap();
assert_eq!((qir["written"]["profile"].as_str(), qir["check"]["verdict"]["verdict"].as_str()), (Some("base"), Some("equivalent")), "{qir}");
assert_eq!(blake3::hash(qir["program"].as_str().unwrap().as_bytes()).to_hex().as_str(), CLIFFORD_T_QIR);
let jeff: Value = serde_json::from_str(&engine_convert(&json!({ "program": qir["program"], "to": "jeff" }).to_string())).unwrap();
assert_eq!((jeff["from"].as_str(), jeff["check"]["verdict"]["verdict"].as_str()), (Some("qir"), Some("equivalent")), "{jeff}");
let back: Value = serde_json::from_str(&engine_convert(&json!({ "program_base64": jeff["program_base64"], "to": "qasm" }).to_string())).unwrap();
assert_eq!(back["from"], "jeff", "{back}");
let e: Value = serde_json::from_str(&engine_equivalent(back["program"].as_str().unwrap(), CLIFFORD_T)).unwrap();
assert_eq!(e["verdict"], "equivalent", "{e}");
let r: Value = serde_json::from_str(&engine_convert(&json!({ "program": "define void @main() {\nentry:\n call void @__quantum__qis__foo__body(ptr null)\n ret void\n}\n", "from": "qir", "to": "qasm" }).to_string())).unwrap();
assert_eq!(r["code"], "Q706", "{r}");
assert!(r["error"].as_str().unwrap().starts_with("line 3: "), "{r}");
}
#[test]
fn critique_equivalence_and_variants_answer_as_json() {
let src = "qubit[2] q;\nh q[0];\nh q[0];\ncx q[0], q[1];\n";
let c: Value = serde_json::from_str(&engine_critique(src)).unwrap();
assert_eq!((c["gates"].as_u64(), c["smells"][0]["kind"].as_str()), (Some(3), Some("cancels")), "{c}");
let e: Value = serde_json::from_str(&engine_equivalent("qubit[1] q; h q[0]; x q[0]; h q[0];", "qubit[1] q; z q[0];")).unwrap();
assert_eq!(e["verdict"], "equivalent", "{e}");
let v: Value = serde_json::from_str(&engine_variants(src)).unwrap();
assert_eq!(v["candidates"][0]["measures"]["gates"], 1, "{v}");
let l: Value = serde_json::from_str(&engine_layout(src)).unwrap();
assert_eq!(l["columns"][0][0]["op"], 0, "{l}");
}
/// The debugger in the page: teleportation's four branches, a quarter
/// each exactly, and one of them replayed to where q2 holds the state q0
/// held.
#[test]
fn the_debugger_steps_and_branches_in_the_page() {
let tele = "OPENQASM 3.0;\nqubit[3] q;\nbit[3] c;\nh q[0];\nh q[1];\ncx q[1], q[2];\ncx q[0], q[1];\nh q[0];\nc[0] = measure q[0];\nc[1] = measure q[1];\nif (c[1]) x q[2];\nif (c[0]) z q[2];\nc[2] = measure q[2];\n";
let b: Value = serde_json::from_str(&engine_debug("branches", &json!({ "qasm": tele }).to_string())).unwrap();
let leaves = b["leaves"].as_array().unwrap();
assert!(leaves.len() == 4 && leaves.iter().all(|l| l["weight_exact"] == "1/4"), "{b}");
let s: Value = serde_json::from_str(&engine_debug("step", &json!({ "qasm": tele, "line": 13, "outcomes": [1, 0] }).to_string())).unwrap();
assert!((s["bloch"][2]["x"].as_f64().unwrap() - 1.0).abs() < 1e-8, "{s}");
assert!(engine_debug("step", &json!({ "qasm": "OPENQASM 3.0;\nqubit[17] q;\nh q[0];\n" }).to_string()).contains("at most 16"));
assert!(engine_debug("step", "not json").contains("not JSON"));
}
/// A drawing's edit is a change to the program's text, and the drawing
/// is kept as SVG or LaTeX, or read out in words.
#[test]
fn a_drawing_s_edit_and_its_pictures_are_the_engine_s_in_the_page() {
let bell = "OPENQASM 3.0;\nqubit[2] q;\nh q[0];\ncx q[0], q[1];\n";
let e: Value = serde_json::from_str(&engine_visual_edit(bell, &json!({ "op": "insert", "name": "t", "qubits": [1], "before": 1 }).to_string())).unwrap();
assert_eq!(e["qasm"], "OPENQASM 3.0;\nqubit[2] q;\nh q[0];\nt q[1];\ncx q[0], q[1];\n", "{e}");
assert_eq!((e["edit"]["from_utf16"].as_u64(), e["edit"]["insert"].as_str()), (Some(34), Some("t q[1];\n")), "{e}");
let svg: Value = serde_json::from_str(&engine_picture(bell, "svg")).unwrap();
assert!(svg["svg"].as_str().unwrap().starts_with("<svg"), "{svg}");
let tex: Value = serde_json::from_str(&engine_picture(bell, "latex")).unwrap();
assert!(tex["latex"].as_str().unwrap().contains("\\begin{tikzpicture}"), "{tex}");
let words: Value = serde_json::from_str(&engine_picture(bell, "description")).unwrap();
assert!(words["description"].as_str().unwrap().starts_with("A circuit on 2 qubits"), "{words}");
assert!(engine_picture(bell, "gif").contains("error"));
assert!(engine_visual_edit(bell, &json!({ "op": "delete", "gate": 7 }).to_string()).contains("no gate 7"));
}
/// The targets in the page: listed, shown with what the Studio draws,
/// read from a snapshot's text, a program placed on one, and a job on one
/// run and sealed with the target's hash.
#[test]
fn device_targets_are_listed_shown_placed_and_run_in_the_page() {
let l: Value = serde_json::from_str(&engine_targets()).unwrap();
assert_eq!(l["targets"].as_array().unwrap().len(), 4, "{l}");
let s: Value = serde_json::from_str(&engine_target("synthetic-heavy-hex-27")).unwrap();
assert_eq!(s["view"]["qubits"].as_array().unwrap().len(), 27, "{s}");
let hash = s["summary"]["hash"].as_str().unwrap().to_string();
let again: Value = serde_json::from_str(&engine_target(&s["document"].to_string())).unwrap();
assert_eq!(again["summary"]["hash"], hash);
assert!(engine_target("a-device-elsewhere").contains("no built-in target"));
let bell = "OPENQASM 3.0; qubit[2] q; bit[2] c; h q[0]; cx q[0], q[1]; c = measure q;";
let p: Value = serde_json::from_str(&engine_target_place(bell, "\"synthetic-heavy-hex-27\"")).unwrap();
assert_eq!(p["hash"], hash, "{p}");
assert_eq!(p["placement"]["layout"].as_array().unwrap().len(), 2, "{p}");
let e = QuantumEngine::new(&[9; 32], 512).unwrap();
let body: Value = serde_json::from_str(&e.run(&json!({ "qasm": bell, "shots": 100, "target": "synthetic-heavy-hex-27" }).to_string())).unwrap();
assert_eq!(body["result"]["target"]["hash"], hash, "{body}");
assert_eq!(body["result"]["target"]["placement"]["layout"], p["placement"]["layout"]);
let v: Value = serde_json::from_str(&engine_verify(&body.to_string())).unwrap();
assert_eq!(v["valid"], true, "{v}");
}
/// Error correction answers in the page, sealed with its key, and a job
/// that mitigates its values carries the mitigation.
#[test]
fn error_correction_and_mitigation_answer_in_the_page() {
let e = QuantumEngine::new(&[4u8; 32], 512).unwrap();
let code: Value = serde_json::from_str(&e.qec("code", r#"{"code": "color:5"}"#)).unwrap();
assert_eq!(code["result"]["certificate"]["distance"], 5, "{code}");
let v: Value = serde_json::from_str(&engine_verify(&code.to_string())).unwrap();
assert_eq!(v["valid"], true, "{v}");
let d: Value = serde_json::from_str(&e.qec("decode", r#"{"code": "surface:3", "error": [4]}"#)).unwrap();
assert_eq!(d["result"]["residual"]["logical"], false, "{d}");
let bad: Value = serde_json::from_str(&e.qec("decode", r#"{"code": "surface:4"}"#)).unwrap();
assert_eq!(bad["code"], "J009", "{bad}");
let job: Value = serde_json::from_str(&e.run(&json!({ "qasm": "OPENQASM 3.0;\nqubit[2] q;\nh q[0];\ncx q[0], q[1];\nrz(0.3) q[1];\n", "observables": ["Z0 Z1"], "noise": { "depolarizing_2q": 0.02 }, "mitigate": "vd" }).to_string())).unwrap();
assert_eq!(job["result"]["mitigation"]["method"], "vd", "{job}");
}
/// A pulse program's schedule draws in the page, its run is a job of
/// the method pulse whose bits are the engine's, and the run checks.
#[test]
fn a_pulse_program_draws_runs_and_checks_in_the_page() {
let e = QuantumEngine::new(&[4u8; 32], 512).unwrap();
let s: Value = serde_json::from_str(&e.pulse("schedule", &json!({ "qasm": PULSE_XM }).to_string())).unwrap();
assert_eq!((s["result"]["duration"].as_u64(), s["result"]["frames"].as_array().map(Vec::len)), (Some(264), Some(3)), "{s}");
let v: Value = serde_json::from_str(&engine_verify(&s.to_string())).unwrap();
assert_eq!(v["valid"], true, "{v}");
let job: Value = serde_json::from_str(&e.run(&json!({ "qasm": PULSE_XM, "method": "pulse", "shots": 100 }).to_string())).unwrap();
assert_eq!((job["method"].as_str(), job["result"]["pulse"]["density_hash"].as_str()), (Some("pulse"), Some(PULSE_XM_DENSITY)), "{job}");
let c: Value = serde_json::from_str(&e.pulse("check", &job.to_string())).unwrap();
assert_eq!(c["result"]["verified"], true, "{c}");
let bad: Value = serde_json::from_str(&e.pulse("schedule", r#"{"qasm": "OPENQASM 3.0;\ncal { play(f, constant(0.1, 1dt)); }\n"}"#)).unwrap();
assert_eq!(bad["code"], "Q102", "{bad}");
}
/// A gradient whose answer every build gives as the same bytes (the
/// engine's own pinned request, `engine::variational`'s tests).
pub(super) const GRADIENT_REQUEST: &str = r#"{"qasm": "OPENQASM 3.0;\ninclude \"stdgates.inc\";\ninput float a;\ninput float b;\nqubit[3] q;\nh q;\nrx(a) q[0];\ncrz(b) q[0], q[1];\nu(a, b, 0.2) q[2];\nrzz(a * b) q[1], q[2];\nry(sin(b)) q[0];\n", "params": {"a": 0.3, "b": -0.7}, "hamiltonian": ["Z0 Z1", "0.5 X2", "-0.3 Y0 Y2"], "gradient": "adjoint"}"#;
/// BLAKE3 of that answer's canonical text less its `engine`, pinned by the
/// engine on x86_64 Linux and arm64 macOS.
pub(super) const GRADIENT_DIGEST: &str = "6f13392bac0a5b652c68d6b98715a7555f7497cd31bb468579ca1fbfc0be7bef";
pub(super) fn digest_less_engine(sealed: &str) -> String {
let mut v: Value = serde_json::from_str(sealed).unwrap();
let r = v["result"].as_object_mut().unwrap();
r.remove("engine");
r.remove("receipt");
blake3::hash(&wai::engine::receipt::canonical(&v["result"])).to_hex().to_string()
}
/// The variational and algorithm library in the page: a gradient to the
/// engine's pinned bytes, an optimisation whose chain and re-run hold, a
/// program built and checked, each sealed with the page's key, and a
/// refusal with its code.
#[test]
fn the_variational_library_answers_in_the_page() {
let e = QuantumEngine::new(&[4u8; 32], 512).unwrap();
let g = e.variational("gradient", GRADIENT_REQUEST);
assert_eq!(digest_less_engine(&g), GRADIENT_DIGEST, "{g}");
let v: Value = serde_json::from_str(&engine_verify(&g)).unwrap();
assert_eq!(v["valid"], true, "{v}");
let o: Value = serde_json::from_str(&e.variational("optimize", r#"{"qasm": "OPENQASM 3.0;\ninput float t;\nqubit q;\nrx(t) q;\n", "params": {"t": 0.5}, "hamiltonian": ["Z0"], "optimizer": "spsa", "steps": 20, "step_size": 1.0}"#)).unwrap();
assert_eq!(wai::engine::variational::verify(&o)["valid"], true, "{o}");
let b: Value = serde_json::from_str(&e.variational("build", r#"{"algorithm": "qpe", "counting": 3, "phase": 0.375}"#)).unwrap();
assert_eq!(b["result"]["check"]["verdict"], "equivalent", "{b}");
let bad: Value = serde_json::from_str(&e.variational("gradient", r#"{"qasm": "OPENQASM 3.0;\ninput float t;\nqubit q;\nrx(t) q;\n", "hamiltonian": ["Z0"]}"#)).unwrap();
assert_eq!(bad["code"], "J050", "{bad}");
}
#[test]
fn the_classical_shortcuts_answer_as_json() {
let s: Value = serde_json::from_str(&engine_shortcuts("qubit[40] q;\nh q[0];\ncx q[0], q[39];\n", false)).unwrap();
assert!(s["summary"].as_str().unwrap().starts_with("Classically easy"), "{s}");
let t: Value = serde_json::from_str(&engine_shortcuts("qubit[6] q;\nh q;\nrx(0.3) q;\ncz q[0], q[1];\ncz q[2], q[3];\n", true)).unwrap();
let tn = t["routes"].as_array().unwrap().iter().find(|r| r["route"] == "tensor_network").unwrap();
assert!(tn["log2_work"].is_number(), "{t}");
}
}
/// The engine compiled to wasm32 and run under Node, as a page runs it: no
/// clock std can read and no threads, on every method a tab holds.
#[cfg(all(test, target_arch = "wasm32"))]
mod wasm_tests {
use super::*;
use wasm_bindgen_test::*;
fn run(e: &QuantumEngine, req: Value) -> Value {
serde_json::from_str(&e.run(&req.to_string())).unwrap()
}
#[wasm_bindgen_test]
fn a_job_runs_and_verifies_in_wasm() {
let e = QuantumEngine::new(&[9u8; 32], 512).unwrap();
let body = run(&e, json!({ "qasm": "OPENQASM 3.0; qubit[2] q; h q[0]; cx q[0], q[1];", "shots": 200 }));
assert_eq!(body["method"], "stabilizer", "{body}");
// A tab has no clock std reads, so no time is claimed.
assert!(body["result"].get("elapsed_ms").is_none(), "{body}");
let v: Value = serde_json::from_str(&engine_verify(&body.to_string())).unwrap();
assert_eq!(v["valid"], true, "{v}");
}
/// The conversion the native test makes, to the same QIR bytes.
#[wasm_bindgen_test]
fn a_program_converts_between_formats_in_wasm_to_the_native_bytes() {
use super::tests::{CLIFFORD_T, CLIFFORD_T_QIR};
let qir: Value = serde_json::from_str(&engine_convert(&json!({ "program": CLIFFORD_T, "to": "qir" }).to_string())).unwrap();
assert_eq!(qir["check"]["verdict"]["verdict"], "equivalent", "{qir}");
assert_eq!(blake3::hash(qir["program"].as_str().unwrap().as_bytes()).to_hex().as_str(), CLIFFORD_T_QIR);
let jeff: Value = serde_json::from_str(&engine_convert(&json!({ "program": qir["program"], "to": "jeff" }).to_string())).unwrap();
assert_eq!(jeff["check"]["verdict"]["verdict"], "equivalent", "{jeff}");
}
#[wasm_bindgen_test]
fn critique_equivalence_and_variants_run_in_wasm() {
let c: Value = serde_json::from_str(&engine_critique("qubit[2] q; h q[0]; rz(0.3) q[1]; cx q[0], q[1];")).unwrap();
assert_eq!((c["depth"].as_u64(), c["non_clifford"].as_u64()), (Some(2), Some(1)), "{c}");
// Wide and not Clifford: proved by rewriting, the merge checked on its one qubit.
let e: Value = serde_json::from_str(&engine_equivalent("qubit[12] q; h q; rx(0.25) q[3]; rx(0.5) q[3];", "qubit[12] q; h q; rx(0.75) q[3];")).unwrap();
assert_eq!((e["verdict"].as_str(), e["how"].as_str()), (Some("equivalent"), Some("rewrites")), "{e}");
// A swap written as three cx is no pair that cancels or merges: random inputs decide it.
let e: Value = serde_json::from_str(&engine_equivalent("qubit[12] q; h q; swap q[3], q[9]; rz(1.1) q[11];", "qubit[12] q; h q; cx q[3], q[9]; cx q[9], q[3]; cx q[3], q[9]; rz(1.1) q[11];")).unwrap();
assert_eq!((e["verdict"].as_str(), e["how"].as_str()), (Some("equivalent"), Some("random")), "{e}");
let v: Value = serde_json::from_str(&engine_variants("qubit[1] q;\nrz(0.5) q[0];\nrz(-0.5) q[0];\nh q[0];\n")).unwrap();
assert_eq!(v["candidates"][0]["qasm"], "qubit[1] q;\nh q[0];\n", "{v}");
}
/// The engine's pinned gradient, to the same bytes in wasm32, and a
/// program built and checked.
#[wasm_bindgen_test]
fn the_variational_library_runs_in_wasm_to_the_native_bytes() {
let e = QuantumEngine::new(&[4u8; 32], 512).unwrap();
let g = e.variational("gradient", super::tests::GRADIENT_REQUEST);
assert_eq!(super::tests::digest_less_engine(&g), super::tests::GRADIENT_DIGEST, "{g}");
let b: Value = serde_json::from_str(&e.variational("build", r#"{"algorithm": "adder", "bits": 2}"#)).unwrap();
assert_eq!(b["result"]["check"]["verdict"], "equivalent", "{b}");
}
/// The same compile as the native test's, to the same bytes.
#[wasm_bindgen_test]
fn error_correction_runs_in_wasm() {
let e = QuantumEngine::new(&[4u8; 32], 512).unwrap();
let code: Value = serde_json::from_str(&e.qec("code", r#"{"code": "surface:5"}"#)).unwrap();
assert_eq!(code["result"]["certificate"]["distance"], 5, "{code}");
let d: Value = serde_json::from_str(&e.qec("decode", r#"{"memory": {"distance": 3, "rounds": 3, "p": 0.004}, "shots": 300, "decoder": "correlated"}"#)).unwrap();
assert_eq!(d["result"]["shots"], 300, "{d}");
let c: Value = serde_json::from_str(&e.qec("decode", r#"{"code": "color:5", "error": [3, 11]}"#)).unwrap();
assert_eq!(c["result"]["residual"]["logical"], false, "{c}");
}
/// The same pulse run as the native test's, to the same bits: the
/// waveforms' exponentials, the carrier's sines and the integrator.
#[wasm_bindgen_test]
fn a_pulse_run_is_the_native_bits_in_wasm() {
let e = QuantumEngine::new(&[9u8; 32], 512).unwrap();
let job = run(&e, json!({ "qasm": super::tests::PULSE_XM, "method": "pulse", "shots": 100 }));
assert_eq!(job["result"]["pulse"]["density_hash"].as_str(), Some(super::tests::PULSE_XM_DENSITY), "{job}");
let v: Value = serde_json::from_str(&engine_verify(&job.to_string())).unwrap();
assert_eq!(v["valid"], true, "{v}");
}
#[wasm_bindgen_test]
fn a_compile_runs_in_wasm_to_the_native_bytes() {
let e = QuantumEngine::new(&[9u8; 32], 512).unwrap();
let out = e.compile(super::tests::COMPILE_REQUEST);
let v: Value = serde_json::from_str(&engine_verify(&out)).unwrap();
assert_eq!(v["valid"], true, "{v}");
assert_eq!(blake3::hash(out.as_bytes()).to_hex().as_str(), super::tests::COMPILE_DIGEST);
}
/// The same estimate as the native test's, to the same bytes: the
/// counts, each rotation's synthesis, the factory search, the frontier
/// and every seal.
#[wasm_bindgen_test]
fn an_estimate_runs_in_wasm_to_the_native_bytes() {
let e = QuantumEngine::new(&[9u8; 32], 512).unwrap();
let out = e.estimate(super::tests::ESTIMATE_REQUEST);
let r: Value = serde_json::from_str(&engine_estimate_verify(&out)).unwrap();
assert_eq!(r["valid"], true, "{r}");
assert_eq!(blake3::hash(out.as_bytes()).to_hex().as_str(), super::tests::ESTIMATE_DIGEST);
}
#[wasm_bindgen_test]
fn the_classical_shortcuts_run_in_wasm() {
// A Clifford ring then one rotation layer: the cut-rank sum, with its quick order search.
let mut q = String::from("qubit[16] q;\nh q;\n");
for i in 0..16 {
q += &format!("cz q[{i}], q[{}];\n", (i + 1) % 16);
}
q += "rz(0.3) q;\n";
let s: Value = serde_json::from_str(&engine_shortcuts(&q, true)).unwrap();
assert_eq!(s["ok"], true, "{s}");
let cut = s["routes"].as_array().unwrap().iter().find(|r| r["route"] == "cutrank").unwrap();
assert_eq!(cut["size"]["widest_cut"], 2, "a ring's graph state has cut-rank 2 along the ring: {s}");
assert!(s["routes"].as_array().unwrap().iter().any(|r| r["route"] == "tensor_network" && r["log2_work"].is_number()), "{s}");
}
/// The OpenQASM 3 conformance corpus in the page: every program refused
/// with its code or read with its warnings, and every program the
/// manifest gives one outcome for run to it (the distributions and
/// equivalences are checked natively, in wai-quantum's tests).
#[wasm_bindgen_test]
fn the_qasm3_corpus_reads_and_runs_in_wasm() {
let bundle: Value = serde_json::from_str(include_str!("../../quantum-conformance/qasm3/bundle.json")).unwrap();
let e = QuantumEngine::new(&[9u8; 32], 512).unwrap();
let mut ran = 0;
for c in bundle["cases"].as_array().unwrap() {
let (file, src, want) = (&c["file"], c["qasm"].as_str().unwrap(), &c["expect"]);
let lint: Value = match want["inputs"].as_object() {
Some(ins) => serde_json::from_str(&engine_lint_with(src, &Value::Object(ins.clone()).to_string())).unwrap(),
None => serde_json::from_str(&engine_lint(src)).unwrap(),
};
if let Some(code) = want["refused"].as_str() {
assert_eq!(lint["code"], code, "{file}: {lint}");
continue;
}
assert_eq!(lint["ok"], true, "{file}: {lint}");
let mut warns: Vec<&str> = lint["diagnostics"].as_array().map(|a| a.iter().filter_map(|d| d["code"].as_str()).collect()).unwrap_or_default();
warns.sort_unstable();
warns.dedup();
let expected: Vec<&str> = want["warns"].as_array().map(|a| a.iter().filter_map(Value::as_str).collect()).unwrap_or_default();
assert_eq!(warns, expected, "{file}");
if let (Some(bits), None) = (want["deterministic"].as_str(), want["inputs"].as_object()) {
let body = run(&e, json!({ "qasm": src, "shots": 32, "seed": 7 }));
assert_eq!(body["result"]["counts"], json!({ bits: 32 }), "{file}: {body}");
ran += 1;
}
}
assert!(ran >= 10, "{ran} programs run");
}
/// The intent conformance set in the page: every case run through the
/// page's engine to the verdict its manifest gives, and each verdict
/// worked out again by `engine_verdict` to the same level.
#[wasm_bindgen_test]
fn the_intent_set_gets_its_verdicts_in_wasm() {
let bundle: Value = serde_json::from_str(include_str!("../../quantum-conformance/intents/bundle.json")).unwrap();
let e = QuantumEngine::new(&[9u8; 32], 1024).unwrap();
let mut n = 0;
for c in bundle["cases"].as_array().unwrap() {
let (name, want) = (&c["name"], &c["expect"]);
let mut req = json!({ "qasm": c["qasm"] });
for (k, v) in c["run"].as_object().into_iter().flatten() {
req[k] = v.clone();
}
if let Some(i) = c.get("intent") {
req["intent"] = i.clone();
}
let body: Value = serde_json::from_str(&e.run(&req.to_string())).unwrap();
let v = match want["code"].as_str() {
Some(code) => {
assert_eq!(body["code"], code, "{name}: {body}");
body["verdict"].clone()
}
None => {
let v = body["result"]["verdict"].clone();
let again: Value = serde_json::from_str(&engine_verdict(&body.to_string(), "", 1024)).unwrap();
assert_eq!(again["level"], v["level"], "{name}");
v
}
};
assert_eq!(v["level"], want["level"], "{name}: {v}");
if want.get("holds").is_some() {
assert_eq!(v["holds"], want["holds"], "{name}: {v}");
}
for (g, w) in v["intent"].as_array().into_iter().flatten().zip(want["intents"].as_array().into_iter().flatten()) {
assert_eq!(g["outcome"], w["outcome"], "{name}: {g}");
if let Some(d) = w["distance"].as_f64() {
assert!((g["distance"].as_f64().unwrap() - d).abs() <= 1e-12, "{name}: {g}");
}
}
n += 1;
}
assert!(n >= 20, "{n} cases");
}
/// The answer conformance set in the page: each answer read to the codes,
/// root and order its manifest gives, and the stored answers' receipts
/// checked by running them again here, the same bytes as natively.
#[wasm_bindgen_test]
fn the_answer_set_reads_and_its_receipts_verify_in_wasm() {
let bundle: Value = serde_json::from_str(include_str!("../../quantum-conformance/answers/bundle.json")).unwrap();
let mut n = 0;
for c in bundle["cases"].as_array().unwrap() {
let (name, e, text) = (&c["name"], &c["expect"], c["answer"].as_str().unwrap());
let a: Value = serde_json::from_str(&engine_answer_parse(text)).unwrap();
let codes = |sev: &str| a["diagnostics"].as_array().unwrap().iter().filter(|d| d["severity"] == sev).map(|d| d["code"].clone()).collect::<Vec<_>>();
assert_eq!(Value::Array(codes("error")), e["errors"], "{name}");
assert_eq!(Value::Array(codes("warning")), e["warnings"], "{name}");
assert_eq!((&a["root"], &a["order"]), (&e["root"], &e["order"]), "{name}");
if let Some(valid) = e["stored"]["valid"].as_bool() {
let v: Value = serde_json::from_str(&engine_answer_verify(text, 512)).unwrap();
assert_eq!(v["valid"].as_bool(), Some(valid), "{name}: {v}");
}
n += 1;
}
assert!(n >= 18, "{n} cases");
}
#[wasm_bindgen_test]
fn a_repair_runs_in_wasm() {
let r: Value = serde_json::from_str(&engine_repair("OPENQASM 3.0;\nqubit[2] q;\nbit[2] c;\nh q[0];\nmeasure q;\n", "")).unwrap();
assert_eq!((r["qasm"].as_str(), r["verdict"]["level"].as_str()), (Some("OPENQASM 3.0;\nqubit[2] q;\nbit[2] c;\nh q[0];\nc = measure q;\n"), Some("parsed")), "{r}");
}
#[wasm_bindgen_test]
fn the_debugger_steps_back_and_branches_in_wasm() {
let tele = "OPENQASM 3.0;\nqubit[3] q;\nbit[3] c;\nh q[0];\nt q[0];\nh q[1];\ncx q[1], q[2];\ncx q[0], q[1];\nh q[0];\nc[0] = measure q[0];\nc[1] = measure q[1];\nif (c[1]) x q[2];\nif (c[0]) z q[2];\nc[2] = measure q[2];\n";
let b: Value = serde_json::from_str(&engine_debug("branches", &json!({ "qasm": tele }).to_string())).unwrap();
assert_eq!((b["method"].as_str(), b["leaves"].as_array().map(Vec::len)), (Some("exact"), Some(4)), "{b}");
// The same position asked twice is the same bits.
let at = |to: u64| -> Value { serde_json::from_str(&engine_debug("step", &json!({ "qasm": tele, "to": to, "outcomes": [1, 1] }).to_string())).unwrap() };
assert_eq!(at(9)["state"]["digest"], at(9)["state"]["digest"]);
assert_ne!(at(9)["state"]["digest"], at(8)["state"]["digest"]);
}
/// A job on a device target in wasm: placed, simulated under the
/// target's noise and sealed, the same bits as natively.
#[wasm_bindgen_test]
fn a_job_on_a_device_target_runs_in_wasm() {
let e = QuantumEngine::new(&[9u8; 32], 512).unwrap();
let body = run(&e, json!({ "qasm": "OPENQASM 3.0; qubit[3] q; bit[3] c; h q[0]; cx q[0], q[1]; cx q[1], q[2]; c = measure q;", "shots": 300, "target": "synthetic-line-5" }));
assert_eq!(body["method"], "density_matrix", "{body}");
let s: Value = serde_json::from_str(&engine_target("synthetic-line-5")).unwrap();
assert_eq!(body["result"]["target"]["hash"], s["summary"]["hash"], "{body}");
let v: Value = serde_json::from_str(&engine_verify(&body.to_string())).unwrap();
assert_eq!(v["valid"], true, "{v}");
}
/// The course's check in the page, to the native bytes.
#[wasm_bindgen_test]
fn the_course_is_checked_in_wasm_to_the_native_bytes() {
let (id, loc) = super::tests::COURSE_CHECK;
let out = engine_course_check(id, &super::tests::starter(id), loc, 512);
assert_eq!(blake3::hash(out.as_bytes()).to_hex().as_str(), super::tests::COURSE_DIGEST, "{out}");
let c: Value = serde_json::from_str(&engine_course("en")).unwrap();
assert_eq!(c["units"].as_array().unwrap().len(), 8, "{c}");
}
#[wasm_bindgen_test]
fn every_method_a_tab_holds_runs_in_wasm() {
let e = QuantumEngine::new(&[9u8; 32], 512).unwrap();
let ring = "OPENQASM 3.0; qubit[12] q; bit[12] c; h q; cz q[0], q[1]; cz q[1], q[2]; cz q[2], q[3]; cz q[3], q[4]; cz q[4], q[5]; cz q[5], q[6]; cz q[6], q[7]; cz q[7], q[8]; cz q[8], q[9]; cz q[9], q[10]; cz q[10], q[11]; t q; h q; c = measure q;";
let jobs = [
("exact", json!({ "qasm": "OPENQASM 3.0; qubit[3] q; h q[0]; t q[0]; cx q[0], q[1];", "shots": 100 })),
("statevector", json!({ "qasm": "OPENQASM 3.0; qubit[3] q; rx(0.3) q[0]; cx q[0], q[1];", "observables": ["Z0"] })),
("stabilizer", json!({ "qasm": "OPENQASM 3.0; qubit[40] q; h q[0]; cx q[0], q[39];", "shots": 100 })),
("mps", json!({ "qasm": "OPENQASM 3.0; qubit[30] q; rx(0.3) q; cx q[0], q[1];", "shots": 50, "method": "mps" })),
("pauli", json!({ "qasm": "OPENQASM 3.0; qubit[30] q; rx(0.3) q; cx q[0], q[1];", "observables": ["Z0 Z1"], "method": "pauli" })),
("tensor_network", json!({ "qasm": "OPENQASM 3.0; qubit[30] q; rx(0.3) q; cx q[0], q[1];", "amplitudes": ["0".repeat(30)], "method": "tensor_network" })),
("cutrank", json!({ "qasm": ring, "shots": 20, "method": "cutrank" })),
("density_matrix", json!({ "qasm": "OPENQASM 3.0; qubit[2] q; h q[0]; cx q[0], q[1];", "shots": 100, "noise": { "depolarizing_2q": 0.02 } })),
("trajectories", json!({ "qasm": "OPENQASM 3.0; qubit[3] q; h q[0]; cx q[0], q[1];", "shots": 100, "noise": { "depolarizing_1q": 0.01 }, "method": "trajectories" })),
("statevector", json!({ "qasm": "OPENQASM 3.0; qubit[2] q; bit[2] c; rx(0.4) q[0]; c[0] = measure q[0]; if (c[0]) x q[1]; c[1] = measure q[1];", "shots": 100 })),
];
for (want, req) in jobs {
let body = run(&e, req.clone());
assert_eq!(body["method"], want, "{req}: {body}");
assert_eq!(body["status"], "done", "{req}: {body}");
}
}
}