ruQu: Quantum Execution Intelligence Engine

February 12, 2026 · View on GitHub

Crates.io docs.rs Downloads

ruv.io RuVector

Modules Lines Backends P99 Latency License Rust

A full-stack quantum computing platform in pure Rust: simulate, optimize, execute, correct, and verify quantum workloads across heterogeneous backends.

From circuit construction to hardware dispatch. From noise modeling to error correction. From approximate simulation to auditable science.

OverviewLayersModulesTry ItCoherence GateTutorialsruv.io


Platform Overview

ruQu is not a simulator. It is a quantum execution intelligence engine -- a layered operating stack that decides how, where, and whether to run quantum workloads.

Most quantum frameworks do one thing: simulate circuits. ruQu does five:

CapabilityWhat It MeansHow It Works
SimulateRun circuits on the right backendCost-model planner selects StateVector, Stabilizer, TensorNetwork, or Clifford+T based on circuit structure
OptimizeCompile circuits for real hardwareTranspiler decomposes to native gate sets, routes qubits to physical topology, cancels redundant gates
ExecuteDispatch to IBM, IonQ, Rigetti, BraketHardware abstraction layer with automatic fallback to local simulation
CorrectDecode errors in real timeUnion-find and subpolynomial partitioned decoders with adaptive code distance
VerifyProve results are correctCross-backend comparison, statistical certification, tamper-evident audit trails

What Makes It Different

Hybrid decomposition. Large circuits are partitioned by entanglement structure -- Clifford-heavy regions run on the stabilizer backend (millions of qubits), low-entanglement regions run on tensor networks, and only the dense entangled core hits the exponential statevector. One 200-qubit circuit becomes three tractable simulations stitched probabilistically.

No mocks. Every module runs real math. Noise channels apply real Kraus operators. Decoders run real union-find with path compression. The Clifford+T backend performs genuine Bravyi-Gosset stabilizer rank decomposition. The benchmark suite doesn't assert "it works" -- it proves quantitative advantages.

Coherence gating. ruQu's original innovation: real-time structural health monitoring using boundary-to-boundary min-cut analysis. Before any operation, the system answers: "Is it safe to act?" This turns quantum computers from fragile experiments into self-aware machines.


The Five Layers

Layer 5: Proof Suite                        benchmark.rs
            |
Layer 4: Theory                             subpoly_decoder.rs, control_theory.rs
            |
Layer 3: QEC Control Plane                  decoder.rs, qec_scheduler.rs
            |
Layer 2: SOTA Differentiation               planner.rs, clifford_t.rs, decomposition.rs
            |
Layer 1: Scientific Instrument              noise.rs, mitigation.rs, transpiler.rs,
         (9 modules)                         hardware.rs, qasm.rs, replay.rs,
                                             witness.rs, confidence.rs, verification.rs
            |
Layer 0: Core Engine                        circuit.rs, gate.rs, state.rs, backend.rs,
         (existing)                          stabilizer.rs, tensor_network.rs, simulator.rs,
                                             simd.rs, optimizer.rs, types.rs, error.rs,
                                             mixed_precision.rs, circuit_analyzer.rs

Module Reference

Layer 0: Core Engine (13 modules)

The foundation: circuit construction, state evolution, and backend dispatch.

ModuleLinesDescription
circuit.rs185Quantum circuit builder with fluent API
gate.rs204Universal gate set: H, X, Y, Z, S, T, CNOT, CZ, SWAP, Rx, Ry, Rz, arbitrary unitaries
state.rs453Complex128 statevector with measurement and partial trace
backend.rs462Backend trait + auto-selector across StateVector, Stabilizer, TensorNetwork
stabilizer.rs774Gottesman-Knill tableau simulator for Clifford circuits (unlimited qubits)
tensor_network.rs863MPS-based tensor network with configurable bond dimension
simulator.rs221Unified execution entry point
simd.rs469AVX2/NEON vectorized gate kernels
optimizer.rs94Gate fusion and cancellation passes
mixed_precision.rs756f32/f64 adaptive precision for memory/speed tradeoff
circuit_analyzer.rs446Static analysis: gate counts, Clifford fraction, entanglement profile
types.rs263Shared type definitions
error.rs--Error types

Layer 1: Scientific Instrument (9 modules)

Everything needed to run quantum circuits as rigorous science.

ModuleLinesDescription
noise.rs1,174Kraus channel noise: depolarizing, amplitude damping (T1), phase damping (T2), readout error, thermal relaxation, crosstalk (ZZ coupling)
mitigation.rs1,275Zero-Noise Extrapolation via gate folding + Richardson extrapolation; measurement error correction via confusion matrix inversion; Clifford Data Regression
transpiler.rs1,210Basis gate decomposition (IBM/IonQ/Rigetti gate sets), BFS qubit routing on hardware topology, gate cancellation optimization
hardware.rs1,764Provider trait HAL with adapters for IBM Quantum, IonQ, Rigetti, Amazon Braket + local simulator fallback
qasm.rs967OpenQASM 3.0 export with ZYZ Euler decomposition for arbitrary single-qubit unitaries
replay.rs556Deterministic replay engine -- seeded RNG, state checkpoints, circuit hashing for exact reproducibility
witness.rs724SHA-256 hash-chain witness logging -- tamper-evident audit trail with JSON export and chain verification
confidence.rs932Wilson score intervals, Clopper-Pearson exact bounds, chi-squared goodness-of-fit, total variation distance, shot budget calculator
verification.rs1,190Automatic cross-backend comparison with statistical certification (exact/statistical/trend match levels)

Layer 2: SOTA Differentiation (3 modules)

Where ruQu separates from every other framework.

ModuleLinesDescription
planner.rs1,393Cost-model circuit router -- predicts memory, runtime, fidelity for each backend. Selects optimal execution plan with verification policy and mitigation strategy. Entanglement budget estimation.
clifford_t.rs996Extended stabilizer simulation via Bravyi-Gosset low-rank decomposition. T-gates double stabilizer terms (2^t scaling). Bridges the gap between Clifford-only (unlimited qubits) and statevector (32 qubits).
decomposition.rs1,409Hybrid circuit partitioning -- builds interaction graph, finds connected components, applies spatial/temporal decomposition. Classifies segments by gate composition. Probabilistic result stitching.

Layer 3: QEC Control Plane (2 modules)

Real-time quantum error correction infrastructure.

ModuleLinesDescription
decoder.rs1,923Union-find decoder O(n*alpha(n)) + partitioned tiled decoder for sublinear wall-clock scaling. Adaptive code distance controller. Logical qubit allocator for surface code patches. Built-in benchmarking.
qec_scheduler.rs1,443Surface code syndrome extraction scheduling, feed-forward optimization (eliminates unnecessary classical dependencies), dependency graph with critical path analysis.

Layer 4: Theoretical Foundations (2 modules)

Provable complexity results and formal analysis.

ModuleLinesDescription
subpoly_decoder.rs1,207HierarchicalTiledDecoder: recursive multi-scale tiling achieving O(d^(2-epsilon) * polylog(d)). RenormalizationDecoder: coarse-grain syndrome lattice across log(d) scales. SlidingWindowDecoder: streaming decode for real-time QEC. ComplexityAnalyzer: provable complexity certificates.
control_theory.rs433QEC as discrete-time control system -- stability conditions, resource optimization, latency budget planning, backlog simulation, scaling laws for classical overhead and logical error suppression.

Layer 5: Proof Suite (1 module)

Quantitative evidence that the architecture delivers measurable advantages.

ModuleLinesDescription
benchmark.rs790Proof 1: cost-model routing beats naive and heuristic selectors. Proof 2: entanglement budgeting enforced as compiler constraint. Proof 3: partitioned decoder shows measurable latency gains vs union-find. Proof 4: cross-backend certification with bounded TVD error guarantees.

Totals

MetricValue
Total modules30
Total lines of Rust24,676
New modules (execution engine)20
New lines (execution engine)~20,000
Simulation backends5 (StateVector, Stabilizer, TensorNetwork, Clifford+T, Hardware)
Hardware providers4 (IBM Quantum, IonQ, Rigetti, Amazon Braket)
Noise channels6 (depolarizing, amplitude damping, phase damping, readout, thermal, crosstalk)
Mitigation strategies3 (ZNE, MEC, CDR)
Decoder algorithms5 (union-find, tiled, hierarchical, renormalization, sliding-window)

Coherence Gating

ruQu's original capability: a classical nervous system for quantum machines. Real-time structural health monitoring that answers one question before every operation: "Is it safe to act?"

Syndrome Stream --> [Min-Cut Analysis] --> PERMIT / DEFER / DENY
                          |
                    "Is the error pattern
                     structurally safe?"
DecisionMeaningAction
PERMITErrors scattered, structure healthyFull-speed operation
DEFERBorderline, uncertainProceed with caution, reduce workload
DENYCorrelated errors, structural collapse riskQuarantine region, isolate failure

Why Coherence Gating Matters

Without ruQu: Quantum computer runs blind until logical failure -> full reset -> lose all progress.

With ruQu: Quantum computer detects structural degradation before failure -> isolates damaged region -> healthy regions keep running.

Validated Results

MetricResult (d=5, p=0.1%)
Median lead time4 cycles before failure
Recall85.7%
False alarms2.0 per 10k cycles
Actionable (2-cycle mitigation)100%

Performance

MetricTargetMeasured
Tick P99<4,000 ns468 ns
Tick Average<2,000 ns260 ns
Merge P99<10,000 ns3,133 ns
Min-cut query<5,000 ns1,026 ns
Throughput1M/sec3.8M/sec
Popcount (1024 bits)--13 ns (SIMD)

Try It in 5 Minutes

Option 1: Add to Your Project

cargo add ruqu --features structural
use ruqu::{QuantumFabric, FabricBuilder, GateDecision};

fn main() -> Result<(), ruqu::RuQuError> {
    let mut fabric = FabricBuilder::new()
        .num_tiles(256)
        .syndrome_buffer_depth(1024)
        .build()?;

    let syndrome_data = [0u8; 64]; // From your quantum hardware
    let decision = fabric.process_cycle(&syndrome_data)?;

    match decision {
        GateDecision::Permit => println!("Safe to proceed"),
        GateDecision::Defer => println!("Proceed with caution"),
        GateDecision::Deny => println!("Region unsafe"),
    }
    Ok(())
}

Option 2: Run the Interactive Demo

git clone https://github.com/ruvnet/ruvector
cd ruvector
cargo run -p ruqu --bin ruqu_demo --release -- --distance 5 --rounds 1000 --error-rate 0.01

Option 3: Use the Quantum Execution Engine (ruqu-core)

use ruqu_core::circuit::QuantumCircuit;
use ruqu_core::planner::{plan_execution, PlannerConfig};
use ruqu_core::decomposition::decompose;

// Build a circuit
let mut circ = QuantumCircuit::new(10);
circ.h(0);
for i in 0..9 { circ.cnot(i, i + 1); }

// Plan: auto-selects optimal backend
let plan = plan_execution(&circ, &PlannerConfig::default());

// Or decompose for multi-backend execution
let partition = decompose(&circ, 25);

Feature Flags

FeatureWhat It EnablesWhen to Use
structuralReal O(n^{o(1)}) min-cut algorithmDefault -- always recommended
decoderFusion-blossom MWPM decoderSurface code error correction
attention50% FLOPs reduction via coherence routingHigh-throughput systems
simdAVX2 vectorized bitmap operationsx86_64 performance
fullAll features enabledProduction deployments

Ecosystem

CrateDescription
ruquCoherence gating + top-level API
ruqu-coreQuantum execution engine (30 modules, 24K lines)
ruqu-algorithmsVQE, Grover, QAOA, surface code algorithms
ruqu-exoticQuantum-classical hybrid algorithms
ruqu-wasmWebAssembly bindings

Tutorials

Tutorial 1: Your First Coherence Gate

Setting Up a Basic Gate

use ruqu::{
    tile::{WorkerTile, TileZero, TileReport, GateDecision},
    syndrome::DetectorBitmap,
};

fn main() {
    // Create a worker tile (ID 1-255)
    let mut worker = WorkerTile::new(1);

    // Create TileZero (the coordinator)
    let mut coordinator = TileZero::new();

    // Simulate a syndrome measurement
    let mut detectors = DetectorBitmap::new(64);
    detectors.set(5, true);   // Detector 5 fired
    detectors.set(12, true);  // Detector 12 fired

    println!("Detectors fired: {}", detectors.fired_count());

    // Worker processes the syndrome
    let report = worker.tick(&detectors);
    println!("Worker report - cut_value: {}", report.local_cut);

    // Coordinator merges reports and decides
    let decision = coordinator.merge(&[report]);

    match decision {
        GateDecision::Permit => println!("System coherent, proceed"),
        GateDecision::Defer => println!("Borderline, use caution"),
        GateDecision::Deny => println!("Structural issue detected"),
    }
}

Key Concepts:

  • WorkerTile: Processes local patch of qubits
  • TileZero: Coordinates all workers, makes global decision
  • DetectorBitmap: Efficient representation of which detectors fired
Tutorial 2: Understanding the Three-Filter Pipeline

How Decisions Are Made

ruQu uses three filters that must all pass for a PERMIT decision:

Syndrome Data -> [Structural] -> [Shift] -> [Evidence] -> Decision
                    |              |             |
               Min-cut OK?    Distribution    E-value
                               stable?       accumulated?
FilterPurposePasses When
StructuralGraph connectivityMin-cut value > threshold
ShiftDistribution stabilityRecent stats match baseline
EvidenceAccumulated confidenceE-value in safe range
Tutorial 3: Cryptographic Audit Trail

Tamper-Evident Decision Logging

Every gate decision is logged in a Blake3 hash chain for audit compliance.

use ruqu::tile::{ReceiptLog, GateDecision};

fn main() {
    let mut log = ReceiptLog::new();

    log.append(GateDecision::Permit, 1, 1000000, [0u8; 32]);
    log.append(GateDecision::Permit, 2, 2000000, [1u8; 32]);
    log.append(GateDecision::Deny, 3, 3000000, [2u8; 32]);

    // Verify chain integrity
    assert!(log.verify_chain(), "Chain should be valid");

    // Retrieve specific entry
    if let Some(entry) = log.get(2) {
        println!("Decision at seq 2: {:?}", entry.decision);
        println!("Hash: {:x?}", &entry.hash[..8]);
    }
}

Security Properties:

  • Blake3 hashing: fast, cryptographically secure
  • Chain integrity: each entry links to previous
  • Constant-time verification: prevents timing attacks
Tutorial 4: Drift Detection for Noise Characterization

Detecting Changes in Error Rates Over Time

Based on arXiv:2511.09491, ruQu can detect when noise characteristics change without direct hardware access.

use ruqu::adaptive::{DriftDetector, DriftProfile};

let mut detector = DriftDetector::new(100); // 100-sample window
for sample in samples {
    detector.push(sample);
    if let Some(profile) = detector.detect() {
        match profile {
            DriftProfile::Stable => { /* Normal operation */ }
            DriftProfile::Linear { slope, .. } => { /* Compensate for trend */ }
            DriftProfile::StepChange { magnitude, .. } => { /* Alert: sudden shift */ }
            DriftProfile::Oscillating { .. } => { /* Periodic noise source */ }
            DriftProfile::VarianceExpansion { ratio } => { /* Increasing noise */ }
        }
    }
}
ProfileIndicatesTypical Cause
StableNormal--
LinearGradual degradationQubit aging, thermal drift
StepChangeSudden eventTLS defect, cosmic ray, cable fault
OscillatingPeriodic interferenceCryocooler, 60Hz, mechanical vibration
VarianceExpansionIncreasing chaosMulti-source interference
Tutorial 5: Model Export/Import for Reproducibility

Save and Load Learned Parameters

Export trained models as a compact 105-byte binary for reproducibility, testing, and deployment.

Offset  Size  Field
------------------------------
0       4     Magic "RUQU"
4       1     Version (1)
5       8     Seed (u64)
13      4     Code distance (u32)
17      8     Error rate (f64)
25      40    Learned thresholds (5 x f64)
65      40    Statistics (5 x f64)
------------------------------
Total: 105 bytes
// Export
let model_bytes = simulation_model.export(); // 105 bytes
std::fs::write("model.ruqu", &model_bytes)?;

// Import and reproduce
let imported = SimulationModel::import(&model_bytes)?;
assert_eq!(imported.seed, original.seed);

Architecture

System Diagram

                    +----------------------------+
                    |   Quantum Algorithms       |  (VQE, Grover, QAOA)
                    +-------------+--------------+
                                  |
          +-----------------------+------------------------+
          |                       |                        |
    +-----v------+   +-----------v----------+   +----------v--------+
    |  Planner   |   |   Decomposition      |   |   Clifford+T      |
    | cost-model |   |   hybrid partition    |   |   stabilizer rank |
    |  routing   |   |   graph min-cut       |   |   decomposition   |
    +-----+------+   +-----------+-----------+   +----------+--------+
          |                       |                        |
    +-----v-----------------------v------------------------v--------+
    |              Core Backends (existing + enhanced)               |
    |  StateVector | Stabilizer | TensorNetwork | MixedPrecision    |
    +-----+-----------------------+------------------------+--------+
          |                       |                        |
    +-----v------+   +-----------v----------+   +----------v--------+
    |   Noise    |   |   Mitigation         |   |   Transpiler      |
    |  channels  |   |   ZNE / CDR / MEC    |   |   routing + opt   |
    +------------+   +----------------------+   +-------------------+
          |                       |                        |
    +-----v-----------------------v------------------------v--------+
    |              Scientific Instrument Layer                       |
    |  Replay | Witness | Confidence | Verification | QASM          |
    +-----------------------------+--------------------------------+
                                  |
    +-----------------------------v--------------------------------+
    |              QEC Control Plane                                |
    |  Decoder | Scheduler | SubpolyDecoder | ControlTheory        |
    +-----------------------------+--------------------------------+
                                  |
                    +-------------v--------------+
                    |   Hardware Providers        |
                    |  IBM | IonQ | Rigetti |     |
                    |  Braket | Local Sim         |
                    +----------------------------+

256-Tile Fabric (Coherence Gating)

                    +---------------+
                    |   TileZero    |
                    | (Coordinator) |
                    +-------+-------+
                            |
           +----------------+----------------+
           |                |                |
    +------+------+  +------+------+  +------+------+
    | WorkerTile 1|  | WorkerTile 2|  |WorkerTile255|
    |   (64KB)    |  |   (64KB)    |  |   (64KB)    |
    +-------------+  +-------------+  +-------------+
           |                |                |
    [Patch Graph]    [Patch Graph]    [Patch Graph]
    [Syndrome Buf]   [Syndrome Buf]   [Syndrome Buf]
    [Evidence Acc]   [Evidence Acc]   [Evidence Acc]

Security

ComponentAlgorithmPurpose
Hash chainBlake3Tamper-evident audit trail
Token signingEd25519Unforgeable permit tokens
Witness logSHA-256 chainExecution provenance
ComparisonsConstant-timeTiming attack prevention

Application Domains

DomainHow ruQu Helps
HealthcareLonger, patient-specific quantum simulations for protein folding and drug interactions. Coherence gating prevents silent corruption in clinical-grade computation.
FinanceContinuous portfolio risk modeling with real-time stability monitoring. Auditable execution trails for regulated environments.
QEC ResearchFull decoder pipeline with 5 algorithms from union-find to subpolynomial partitioned decoding. Benchmarkable scaling claims.
Cloud QuantumMulti-backend workload routing. Automatic degraded-mode operation via coherence-aware scheduling.
Hardware VendorsTranspiler targets IBM/IonQ/Rigetti/Braket gate sets. Noise characterization and drift detection without direct hardware access.

Limitations

LimitationImpactPath Forward
Simulation-only validationHardware behavior may differHardware partner integration
Greedy spatial partitioningNot optimal min-cutStoer-Wagner / spectral bisection
No end-to-end pipelineModules exist independentlyCompose decompose -> execute -> stitch -> certify
CliffordT not in classifierBridge layer disconnected from auto-routingIntegrate T-rank into planner decisions
No fidelity-aware stitchingCut error unboundedModel Schmidt coefficient loss at partition boundaries

Roadmap

PhaseGoalStatus
v0.1Core coherence gate with min-cutDone
v0.2Predictive early warning, drift detectionDone
v0.3Quantum execution engine (20 modules)Done
v0.4Formal hybrid decomposition with scaling proofNext
v0.5Hardware integration + end-to-end pipelinePlanned
v1.0Production-ready with hardware validationPlanned

References

Academic

Project


License

MIT OR Apache-2.0


ruQu -- Quantum execution intelligence in pure Rust.

ruv.ioRuVectorIssues

Built by ruv.io