Merge commit 'd803bfe2b1fe7f5e219e50ac20d6801a0a58ac75' as 'vendor/ruvector'
This commit is contained in:
816
vendor/ruvector/docs/architecture/quantum-engine/quantum-engine-ddd-integration.md
vendored
Normal file
816
vendor/ruvector/docs/architecture/quantum-engine/quantum-engine-ddd-integration.md
vendored
Normal file
@@ -0,0 +1,816 @@
|
||||
# Quantum Simulation Engine: Domain-Driven Design - Integration Patterns
|
||||
|
||||
**Version**: 0.1
|
||||
**Date**: 2026-02-06
|
||||
**Status**: Draft
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
This document defines the cross-domain integration patterns, anti-corruption layers, shared kernel, and context mapping that connect the quantum simulation engine (`ruqu-core`, `ruqu-algorithms`, `ruqu-wasm`) to the existing ruVector subsystems. It specifies how the simulation domain communicates with the coherence engine, agent system, graph database, and WASM platform without contaminating bounded context boundaries.
|
||||
|
||||
---
|
||||
|
||||
## Context Map
|
||||
|
||||
```
|
||||
+-------------------------------------------------------------------+
|
||||
| CONTEXT MAP |
|
||||
| |
|
||||
| +--------------------+ Shared Kernel +------------------+ |
|
||||
| | |<----(ruvector-math)--->| | |
|
||||
| | Quantum Sim | | Coherence | |
|
||||
| | Engine | | Engine | |
|
||||
| | (ruqu-core, | Anti-Corruption | (ruvector- | |
|
||||
| | ruqu-algorithms) |<----(CoherenceBridge) | coherence) | |
|
||||
| | | | | |
|
||||
| +--------+-----------+ +------------------+ |
|
||||
| | ^ |
|
||||
| | Customer-Supplier | |
|
||||
| v | |
|
||||
| +--------------------+ +---------+--------+ |
|
||||
| | | Partnership | | |
|
||||
| | Agent System |<----------------->| Graph Database | |
|
||||
| | (claude-flow) | | (ruvector-graph)| |
|
||||
| | | | | |
|
||||
| +--------------------+ +------------------+ |
|
||||
| | |
|
||||
| | Conformist |
|
||||
| v |
|
||||
| +--------------------+ Published Language |
|
||||
| | |<----(OpenQASM 3.0) |
|
||||
| | WASM Platform | |
|
||||
| | (ruqu-wasm) | |
|
||||
| | | |
|
||||
| +--------------------+ |
|
||||
+-------------------------------------------------------------------+
|
||||
```
|
||||
|
||||
### Relationship Summary
|
||||
|
||||
| Upstream | Downstream | Pattern | Shared Artifact |
|
||||
|----------|------------|---------|-----------------|
|
||||
| Quantum Engine | Coherence Engine | Anti-Corruption Layer | `CoherenceBridge` trait |
|
||||
| ruvector-math | Quantum Engine, Coherence Engine | Shared Kernel | `Complex<f64>`, SIMD traits |
|
||||
| Quantum Engine | Agent System | Customer-Supplier | `SimulationContract` |
|
||||
| ruvector-graph | Quantum Engine | Partnership | Adjacency structures |
|
||||
| External tools | Quantum Engine | Published Language | OpenQASM 3.0 |
|
||||
| WASM platform | ruqu-wasm | Conformist | WASM constraints accepted |
|
||||
|
||||
---
|
||||
|
||||
## 1. Anti-Corruption Layer: Coherence Bridge
|
||||
|
||||
The Coherence Bridge translates between the quantum simulation domain language and the ruQu coherence domain. It prevents internal types from either domain from leaking into the other.
|
||||
|
||||
### Purpose
|
||||
|
||||
- Map syndrome bitstrings produced by surface code experiments into the `SyndromeFilter` input format expected by the coherence engine
|
||||
- Map decoder correction outputs (Pauli operators) to gate operations the simulation can apply
|
||||
- Translate coherence scores into the `CoherenceScore` value object used by simulation sessions
|
||||
- Isolate the quantum simulation engine from changes in the coherence engine's internal API
|
||||
|
||||
### Interface
|
||||
|
||||
```rust
|
||||
/// Anti-corruption layer between quantum simulation and coherence engine.
|
||||
///
|
||||
/// All translation between bounded contexts passes through this trait.
|
||||
/// Neither domain's internal types appear on the wrong side of this boundary.
|
||||
pub trait CoherenceBridge: Send + Sync {
|
||||
/// Translate a quantum syndrome into a coherence engine filter input.
|
||||
///
|
||||
/// The simulation produces `SyndromeBits`; the coherence engine expects
|
||||
/// `DetectorBitmap` with specific tile routing. This method handles the
|
||||
/// mapping, including stabilizer-to-detector index translation.
|
||||
fn syndrome_to_filter_input(
|
||||
&self,
|
||||
syndrome: &SyndromeBits,
|
||||
code_distance: u32,
|
||||
) -> Result<CoherenceFilterInput, BridgeError>;
|
||||
|
||||
/// Translate a coherence decoder correction into Pauli gate operations.
|
||||
///
|
||||
/// The coherence engine's decoder outputs correction vectors in its own
|
||||
/// format. This method maps them to `PauliOp` sequences that the
|
||||
/// simulation engine can apply as gate operations.
|
||||
fn correction_to_pauli_ops(
|
||||
&self,
|
||||
correction: &CoherenceCorrectionOutput,
|
||||
) -> Result<Vec<(QubitIndex, PauliOp)>, BridgeError>;
|
||||
|
||||
/// Query the current coherence score for a simulation region.
|
||||
///
|
||||
/// Returns a domain-native `CoherenceScore` value object, hiding
|
||||
/// the coherence engine's internal energy representation.
|
||||
fn query_coherence_score(
|
||||
&self,
|
||||
region_id: &str,
|
||||
) -> Result<CoherenceScore, BridgeError>;
|
||||
|
||||
/// Submit simulation metrics to the coherence monitoring system.
|
||||
///
|
||||
/// Translates `SimulationMetrics` into the coherence engine's
|
||||
/// signal ingestion format without exposing internal types.
|
||||
fn report_simulation_metrics(
|
||||
&self,
|
||||
session_id: &str,
|
||||
metrics: &SimulationMetrics,
|
||||
) -> Result<(), BridgeError>;
|
||||
}
|
||||
|
||||
/// Opaque input type for the coherence filter (ACL boundary type).
|
||||
pub struct CoherenceFilterInput {
|
||||
pub detector_bitmap: Vec<u64>,
|
||||
pub tile_id: u8,
|
||||
pub round_id: u64,
|
||||
}
|
||||
|
||||
/// Opaque output type from the coherence decoder (ACL boundary type).
|
||||
pub struct CoherenceCorrectionOutput {
|
||||
pub corrections: Vec<(u32, u8)>, // (qubit_index, pauli_code)
|
||||
pub confidence: f64,
|
||||
}
|
||||
|
||||
/// Errors specific to the bridge translation layer.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum BridgeError {
|
||||
#[error("syndrome dimension mismatch: expected {expected}, got {actual}")]
|
||||
SyndromeDimensionMismatch { expected: usize, actual: usize },
|
||||
|
||||
#[error("unknown correction code: {0}")]
|
||||
UnknownCorrectionCode(u8),
|
||||
|
||||
#[error("coherence engine unavailable: {0}")]
|
||||
CoherenceUnavailable(String),
|
||||
|
||||
#[error("tile routing failed for code distance {0}")]
|
||||
TileRoutingFailed(u32),
|
||||
}
|
||||
```
|
||||
|
||||
### Implementation Sketch
|
||||
|
||||
```rust
|
||||
/// Production implementation backed by the ruQu coherence engine.
|
||||
pub struct RuQuCoherenceBridge {
|
||||
/// Reference to the coherence engine's filter pipeline.
|
||||
filter_pipeline: Arc<dyn FilterPipelineAccess>,
|
||||
/// Stabilizer-to-detector mapping, precomputed per code distance.
|
||||
detector_maps: HashMap<u32, StabilizerDetectorMap>,
|
||||
}
|
||||
|
||||
impl CoherenceBridge for RuQuCoherenceBridge {
|
||||
fn syndrome_to_filter_input(
|
||||
&self,
|
||||
syndrome: &SyndromeBits,
|
||||
code_distance: u32,
|
||||
) -> Result<CoherenceFilterInput, BridgeError> {
|
||||
let map = self.detector_maps.get(&code_distance)
|
||||
.ok_or(BridgeError::TileRoutingFailed(code_distance))?;
|
||||
|
||||
let mut bitmap = vec![0u64; (map.detector_count + 63) / 64];
|
||||
for (stab_idx, &fired) in syndrome.0.iter().enumerate() {
|
||||
if fired {
|
||||
let det_idx = map.stabilizer_to_detector(stab_idx);
|
||||
bitmap[det_idx / 64] |= 1u64 << (det_idx % 64);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(CoherenceFilterInput {
|
||||
detector_bitmap: bitmap,
|
||||
tile_id: map.tile_for_distance(code_distance),
|
||||
round_id: 0, // Filled by caller
|
||||
})
|
||||
}
|
||||
|
||||
fn correction_to_pauli_ops(
|
||||
&self,
|
||||
correction: &CoherenceCorrectionOutput,
|
||||
) -> Result<Vec<(QubitIndex, PauliOp)>, BridgeError> {
|
||||
correction.corrections.iter()
|
||||
.map(|(qubit, code)| {
|
||||
let op = match code {
|
||||
0 => PauliOp::I,
|
||||
1 => PauliOp::X,
|
||||
2 => PauliOp::Y,
|
||||
3 => PauliOp::Z,
|
||||
other => return Err(BridgeError::UnknownCorrectionCode(*other)),
|
||||
};
|
||||
Ok((QubitIndex(*qubit), op))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn query_coherence_score(
|
||||
&self,
|
||||
region_id: &str,
|
||||
) -> Result<CoherenceScore, BridgeError> {
|
||||
let energy = self.filter_pipeline.current_energy(region_id)
|
||||
.map_err(|e| BridgeError::CoherenceUnavailable(e.to_string()))?;
|
||||
// Invert: high energy = low coherence
|
||||
Ok(CoherenceScore(1.0 / (1.0 + energy as f64)))
|
||||
}
|
||||
|
||||
fn report_simulation_metrics(
|
||||
&self,
|
||||
_session_id: &str,
|
||||
_metrics: &SimulationMetrics,
|
||||
) -> Result<(), BridgeError> {
|
||||
// Translate to coherence signal format and submit
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. Shared Kernel: ruvector-math
|
||||
|
||||
Both the quantum simulation engine and the coherence engine depend on a shared mathematical foundation. Changes to `ruvector-math` must be validated against both domains before release.
|
||||
|
||||
### Shared Types
|
||||
|
||||
```rust
|
||||
// ruvector-math provides these types used by both domains:
|
||||
|
||||
/// Complex number with f64 components (re, im).
|
||||
/// Used by quantum state vectors AND coherence restriction maps.
|
||||
pub struct Complex<T> {
|
||||
pub re: T,
|
||||
pub im: T,
|
||||
}
|
||||
|
||||
/// Cache-line-aligned vector for SIMD operations.
|
||||
/// Used by both state vector operations and residual computation.
|
||||
#[repr(align(64))]
|
||||
pub struct AlignedVec<T> {
|
||||
data: Vec<T>,
|
||||
}
|
||||
|
||||
/// SIMD dispatch trait: implementations select AVX2, NEON, or scalar
|
||||
/// at runtime depending on platform capabilities.
|
||||
pub trait SimdOps {
|
||||
fn dot_product_f64(a: &[f64], b: &[f64]) -> f64;
|
||||
fn complex_multiply(a: &[Complex<f64>], b: &[Complex<f64>], out: &mut [Complex<f64>]);
|
||||
fn norm_squared(v: &[Complex<f64>]) -> f64;
|
||||
fn axpy(alpha: f64, x: &[f64], y: &mut [f64]);
|
||||
}
|
||||
```
|
||||
|
||||
### Change Coordination Protocol
|
||||
|
||||
1. Any proposed change to `ruvector-math` must include tests for both the quantum engine use case and the coherence engine use case.
|
||||
2. The CI pipeline runs `cargo test -p ruqu-core` and `cargo test -p ruvector-coherence` after any change to `ruvector-math`.
|
||||
3. Breaking changes require a version bump and simultaneous updates to both downstream crates.
|
||||
4. Performance regressions in SIMD operations must be caught by benchmarks in both domains.
|
||||
|
||||
### Boundary
|
||||
|
||||
Only the types and functions listed above cross the shared kernel boundary. Internal implementation details of `ruvector-math` (e.g., specific SIMD intrinsics, platform detection) are not shared.
|
||||
|
||||
---
|
||||
|
||||
## 3. Customer-Supplier: Agent System Integration
|
||||
|
||||
The ruVector agent system (powered by claude-flow) acts as the customer, invoking the quantum simulation engine as a supplier. The contract defines what the agent can request and what it receives in return.
|
||||
|
||||
### Contract
|
||||
|
||||
```rust
|
||||
/// Contract for agent system access to the quantum simulation engine.
|
||||
///
|
||||
/// The agent system (customer) invokes these operations.
|
||||
/// The quantum engine (supplier) fulfills them.
|
||||
pub trait SimulationContract: Send + Sync {
|
||||
/// Build a circuit from a high-level description.
|
||||
fn build_circuit(&self, spec: CircuitSpec) -> Result<CircuitHandle, ContractError>;
|
||||
|
||||
/// Run a simulation and return results.
|
||||
fn run_simulation(&self, circuit: CircuitHandle, config: RunConfig)
|
||||
-> Result<SimulationOutput, ContractError>;
|
||||
|
||||
/// Run a VQE optimization and return the ground state energy.
|
||||
fn run_vqe(&self, spec: VQESpec) -> Result<VQEOutput, ContractError>;
|
||||
|
||||
/// Query resource requirements before committing to a run.
|
||||
fn estimate_resources(&self, circuit: CircuitHandle) -> Result<ResourceEstimate, ContractError>;
|
||||
}
|
||||
|
||||
/// High-level circuit specification from the agent.
|
||||
pub struct CircuitSpec {
|
||||
pub qubit_count: u32,
|
||||
pub gate_sequence: Vec<GateSpec>,
|
||||
pub parameters: HashMap<String, f64>,
|
||||
}
|
||||
|
||||
/// Agent-facing gate specification (simplified from internal Gate).
|
||||
pub struct GateSpec {
|
||||
pub gate_type: String,
|
||||
pub target: u32,
|
||||
pub control: Option<u32>,
|
||||
pub angle: Option<f64>,
|
||||
}
|
||||
|
||||
/// Configuration limits the agent can set.
|
||||
pub struct RunConfig {
|
||||
pub max_shots: u32,
|
||||
pub max_memory_mb: u32,
|
||||
pub timeout_seconds: u32,
|
||||
pub backend_preference: Option<String>,
|
||||
}
|
||||
|
||||
/// Results returned to the agent.
|
||||
pub struct SimulationOutput {
|
||||
pub measurement_counts: HashMap<String, u32>,
|
||||
pub expectation_values: Vec<(String, f64)>,
|
||||
pub metrics: SimulationMetrics,
|
||||
}
|
||||
|
||||
/// VQE-specific results.
|
||||
pub struct VQEOutput {
|
||||
pub ground_state_energy: f64,
|
||||
pub optimal_parameters: Vec<f64>,
|
||||
pub iterations: u32,
|
||||
pub converged: bool,
|
||||
}
|
||||
|
||||
/// Resource estimate before execution.
|
||||
pub struct ResourceEstimate {
|
||||
pub memory_bytes: usize,
|
||||
pub estimated_time_ms: f64,
|
||||
pub qubit_count: u32,
|
||||
pub gate_count: u32,
|
||||
}
|
||||
```
|
||||
|
||||
### Agent Integration Flow
|
||||
|
||||
```
|
||||
Agent Context Quantum Engine Result
|
||||
| | |
|
||||
| 1. build_circuit() | |
|
||||
|--------------------->| |
|
||||
| CircuitHandle | |
|
||||
|<---------------------| |
|
||||
| | |
|
||||
| 2. estimate_resources| |
|
||||
|--------------------->| |
|
||||
| ResourceEstimate | |
|
||||
|<---------------------| |
|
||||
| | |
|
||||
| 3. run_simulation() | |
|
||||
|--------------------->| |
|
||||
| | [executes internally]|
|
||||
| |---+ |
|
||||
| | | circuit -> state |
|
||||
| | | gates -> measure |
|
||||
| |<--+ |
|
||||
| SimulationOutput | |
|
||||
|<---------------------| |
|
||||
| | |
|
||||
| 4. Agent acts on | |
|
||||
| results | |
|
||||
v v v
|
||||
```
|
||||
|
||||
### Resource Limits
|
||||
|
||||
The supplier enforces resource limits set by the customer:
|
||||
|
||||
- Memory: Capped at `max_memory_mb`; returns error if state vector exceeds budget
|
||||
- Time: Monitored per-step; simulation aborted if `timeout_seconds` exceeded
|
||||
- Qubits: Platform limit (30 for state vector, higher for tensor network) communicated via `estimate_resources`
|
||||
|
||||
---
|
||||
|
||||
## 4. Published Language: OpenQASM Compatibility
|
||||
|
||||
A future integration point for importing and exporting circuits in the OpenQASM 3.0 standard, enabling interoperability with IBM Qiskit, Google Cirq, and other quantum frameworks.
|
||||
|
||||
### Translation Layer
|
||||
|
||||
```rust
|
||||
/// Trait for OpenQASM import/export.
|
||||
pub trait OpenQASMTranslator {
|
||||
/// Parse an OpenQASM 3.0 string into the internal circuit representation.
|
||||
fn import(&self, qasm: &str) -> Result<QuantumCircuit, TranslationError>;
|
||||
|
||||
/// Export an internal circuit to OpenQASM 3.0 format.
|
||||
fn export(&self, circuit: &QuantumCircuit) -> Result<String, TranslationError>;
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum TranslationError {
|
||||
#[error("unsupported gate in OpenQASM: {0}")]
|
||||
UnsupportedGate(String),
|
||||
|
||||
#[error("parse error at line {line}: {message}")]
|
||||
ParseError { line: u32, message: String },
|
||||
|
||||
#[error("circuit uses features not supported by OpenQASM 3.0: {0}")]
|
||||
UnsupportedFeature(String),
|
||||
}
|
||||
```
|
||||
|
||||
### Scope
|
||||
|
||||
- Phase 1: Import basic gate circuits (H, CNOT, Rz, measure)
|
||||
- Phase 2: Export circuits with parameter bindings
|
||||
- Phase 3: Support custom gate definitions and classical control flow
|
||||
|
||||
---
|
||||
|
||||
## 5. Conformist: WASM Platform
|
||||
|
||||
The `ruqu-wasm` crate conforms to WASM platform constraints without attempting to work around them. Limitations are accepted as-is, with graceful degradation where capabilities are reduced.
|
||||
|
||||
### Accepted Constraints
|
||||
|
||||
| Constraint | Impact | Mitigation |
|
||||
|------------|--------|------------|
|
||||
| No native threads | Single-threaded execution | Sequential gate application; no rayon |
|
||||
| 4GB memory limit | Max ~25 qubits (state vector) | Tensor network backend for larger circuits |
|
||||
| No filesystem | Cannot persist results | Return all data via JS callbacks |
|
||||
| No system clock | Timing metrics unavailable | Use `performance.now()` via JS bridge |
|
||||
| No SIMD (some runtimes) | Slower math | Feature-gated SIMD; scalar fallback |
|
||||
|
||||
### WASM API Surface
|
||||
|
||||
```rust
|
||||
/// Public API exposed to JavaScript via wasm-bindgen.
|
||||
///
|
||||
/// This is the conformist boundary: we accept WASM constraints
|
||||
/// and expose only what the platform allows.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub mod wasm_api {
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub struct WasmSimulator {
|
||||
session: SimulationSession,
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
impl WasmSimulator {
|
||||
/// Create a new simulator for the given qubit count.
|
||||
#[wasm_bindgen(constructor)]
|
||||
pub fn new(qubit_count: u32) -> Result<WasmSimulator, JsValue> {
|
||||
// Enforce WASM-specific qubit limit
|
||||
if qubit_count > 25 {
|
||||
return Err(JsValue::from_str(
|
||||
"WASM platform supports at most 25 qubits in state vector mode"
|
||||
));
|
||||
}
|
||||
// ... construction
|
||||
Ok(WasmSimulator { session: todo!() })
|
||||
}
|
||||
|
||||
/// Add a gate to the circuit.
|
||||
pub fn add_gate(&mut self, gate_type: &str, target: u32, control: Option<u32>)
|
||||
-> Result<(), JsValue> { Ok(()) }
|
||||
|
||||
/// Run the simulation and return measurement counts as JSON.
|
||||
pub fn run(&mut self, shots: u32) -> Result<String, JsValue> {
|
||||
Ok("{}".to_string())
|
||||
}
|
||||
|
||||
/// Get memory usage estimate in bytes.
|
||||
pub fn memory_estimate(&self) -> usize { 0 }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. Partnership: Graph Database Integration
|
||||
|
||||
The `ruvector-graph` crate and the quantum simulation engine have a bidirectional partnership around graph-structured problems, particularly QAOA and MaxCut.
|
||||
|
||||
### Data Flow
|
||||
|
||||
```rust
|
||||
/// Graph data provided by ruvector-graph for quantum optimization.
|
||||
pub struct GraphProblem {
|
||||
pub vertex_count: u32,
|
||||
pub edges: Vec<(u32, u32, f64)>, // (source, target, weight)
|
||||
pub problem_type: GraphProblemType,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum GraphProblemType { MaxCut, GraphColoring, TSP }
|
||||
|
||||
/// Results returned to ruvector-graph for annotation.
|
||||
pub struct QuantumGraphResult {
|
||||
pub objective_value: CutValue,
|
||||
pub partition: Vec<bool>,
|
||||
pub confidence: f64,
|
||||
pub circuit_depth: CircuitDepth,
|
||||
}
|
||||
|
||||
/// Partnership interface: both sides contribute and consume.
|
||||
pub trait GraphQuantumPartnership {
|
||||
/// Graph -> Quantum: convert graph problem to QAOA circuit.
|
||||
fn graph_to_qaoa_circuit(
|
||||
&self,
|
||||
problem: &GraphProblem,
|
||||
layers: u32,
|
||||
) -> Result<QuantumCircuit, DomainError>;
|
||||
|
||||
/// Quantum -> Graph: feed optimization results back as graph annotations.
|
||||
fn annotate_graph_with_result(
|
||||
&self,
|
||||
problem: &GraphProblem,
|
||||
result: &QuantumGraphResult,
|
||||
) -> Result<GraphAnnotation, DomainError>;
|
||||
|
||||
/// Shared interest: partition graph using ruvector-mincut for subproblem decomposition.
|
||||
fn decompose_problem(
|
||||
&self,
|
||||
problem: &GraphProblem,
|
||||
max_subproblem_qubits: u32,
|
||||
) -> Result<Vec<GraphProblem>, DomainError>;
|
||||
}
|
||||
|
||||
/// Annotation written back to the graph database.
|
||||
pub struct GraphAnnotation {
|
||||
pub vertex_labels: HashMap<u32, String>,
|
||||
pub edge_labels: HashMap<(u32, u32), String>,
|
||||
pub metadata: HashMap<String, String>,
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Cross-Cutting Concerns
|
||||
|
||||
### Error Handling Across Boundaries
|
||||
|
||||
Each bounded context defines its own error type. At integration boundaries, errors are translated through the ACL rather than propagated directly.
|
||||
|
||||
```rust
|
||||
/// Integration boundary error: wraps domain errors from either side.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum IntegrationError {
|
||||
#[error("quantum engine error: {0}")]
|
||||
QuantumEngine(#[from] DomainError),
|
||||
|
||||
#[error("coherence bridge error: {0}")]
|
||||
CoherenceBridge(#[from] BridgeError),
|
||||
|
||||
#[error("contract violation: {0}")]
|
||||
ContractViolation(String),
|
||||
|
||||
#[error("resource limit exceeded: {0}")]
|
||||
ResourceLimit(String),
|
||||
}
|
||||
```
|
||||
|
||||
### Observability
|
||||
|
||||
Distributed tracing spans cross crate boundaries with a shared trace context.
|
||||
|
||||
- Each integration call propagates a `TraceId` through the ACL
|
||||
- The coherence bridge logs translation events at `DEBUG` level
|
||||
- Agent contract calls log at `INFO` with duration and resource usage
|
||||
- WASM calls use `console.log` via the JS bridge when tracing is enabled
|
||||
|
||||
### Resource Management
|
||||
|
||||
Memory and thread resources are coordinated with the ruVector runtime.
|
||||
|
||||
- State vector allocation checks the global memory budget before proceeding
|
||||
- Tensor network contractions respect thread pool limits shared with rayon
|
||||
- WASM mode has a fixed 4GB ceiling enforced at the conformist boundary
|
||||
- All resource allocation events emit `MemoryAllocated` / `MemoryReleased` domain events
|
||||
|
||||
### Configuration Propagation
|
||||
|
||||
Configuration flows from the ruVector root config into the quantum engine.
|
||||
|
||||
```rust
|
||||
/// Quantum engine configuration derived from ruVector global config.
|
||||
pub struct QuantumEngineConfig {
|
||||
pub max_qubits: u32,
|
||||
pub default_backend: BackendType,
|
||||
pub memory_budget_bytes: usize,
|
||||
pub thread_count: usize,
|
||||
pub coherence_bridge_enabled: bool,
|
||||
pub wasm_mode: bool,
|
||||
}
|
||||
|
||||
impl From<&RuVectorConfig> for QuantumEngineConfig {
|
||||
fn from(global: &RuVectorConfig) -> Self {
|
||||
Self {
|
||||
max_qubits: global.quantum.max_qubits.unwrap_or(30),
|
||||
default_backend: global.quantum.backend.parse().unwrap_or(BackendType::StateVector),
|
||||
memory_budget_bytes: global.memory.budget_bytes,
|
||||
thread_count: global.runtime.thread_count,
|
||||
coherence_bridge_enabled: global.coherence.enabled,
|
||||
wasm_mode: cfg!(target_arch = "wasm32"),
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Event Flow Diagrams
|
||||
|
||||
### 1. VQE Optimization Flow
|
||||
|
||||
```
|
||||
Agent CircuitBuilder SimSession QuantumState Optimizer
|
||||
| | | | |
|
||||
| build_circuit(spec) | | | |
|
||||
|-------------------->| | | |
|
||||
| CircuitHandle | | | |
|
||||
|<--------------------| | | |
|
||||
| | | | |
|
||||
| run_vqe(spec) | | | |
|
||||
|-------------------------------------------------------------->| |
|
||||
| | | | init(params) |
|
||||
| | | |<---------------|
|
||||
| | | | |
|
||||
| | +-----|---LOOP----------|--------+ |
|
||||
| | | | | | |
|
||||
| | | start() | | |
|
||||
| | | |----->| | | |
|
||||
| | | | apply_gates() | | |
|
||||
| | | | |---------->| | |
|
||||
| | | | | expectation_value | |
|
||||
| | | | |---------->| | |
|
||||
| | | | | energy | | |
|
||||
| | | |<----|-----------| | |
|
||||
| | | | | update(grad) |
|
||||
| | | | |------->| |
|
||||
| | | | | new_params |
|
||||
| | | | |<-------| |
|
||||
| | +-----|---END LOOP------|--------+ |
|
||||
| | | | |
|
||||
| VQEOutput(energy, params) | | |
|
||||
|<-------------------------------------------------------------| |
|
||||
| | | | |
|
||||
```
|
||||
|
||||
### 2. Surface Code QEC with Coherence Bridge
|
||||
|
||||
```
|
||||
SurfaceCodeExp NoiseService CoherenceBridge ruQu Filters Decoder
|
||||
| | | | |
|
||||
| run_cycle() | | | |
|
||||
|--+ | | | |
|
||||
| | inject_errors() | | | |
|
||||
| |---------------->| | | |
|
||||
| | error_list | | | |
|
||||
| |<----------------| | | |
|
||||
| | | | | |
|
||||
| | extract_syndrome() | | |
|
||||
| |--+ | | | |
|
||||
| | | SyndromeBits | | | |
|
||||
| |<-+ | | | |
|
||||
| | | | | |
|
||||
| | syndrome_to_filter_input() | | |
|
||||
| |--------------------------------->| | |
|
||||
| | | FilterInput | | |
|
||||
| | | | process() | |
|
||||
| | | |----------------->| |
|
||||
| | | | Verdict | |
|
||||
| | | |<-----------------| |
|
||||
| | | | | |
|
||||
| | | correction_to_pauli_ops() | |
|
||||
| |<---------------------------------| | |
|
||||
| | | | | |
|
||||
| | decode(syndrome)| | | |
|
||||
| |------------------------------------------------------------------>|
|
||||
| | correction | | | |
|
||||
| |<------------------------------------------------------------------|
|
||||
| | | | | |
|
||||
| | check_logical_error() | | |
|
||||
| |--+ | | | |
|
||||
| | | bool | | | |
|
||||
| |<-+ | | | |
|
||||
| | | | | |
|
||||
| CycleReport | | | |
|
||||
|<-+ | | | |
|
||||
```
|
||||
|
||||
### 3. WASM Deployment Flow
|
||||
|
||||
```
|
||||
Browser JS ruqu-wasm (WASM) ruqu-core Results
|
||||
| | | |
|
||||
| new WasmSimulator(n) | | |
|
||||
|--------------------->| | |
|
||||
| | QuantumState::new(n)| |
|
||||
| |-------------------->| |
|
||||
| | state | |
|
||||
| |<--------------------| |
|
||||
| WasmSimulator | | |
|
||||
|<---------------------| | |
|
||||
| | | |
|
||||
| add_gate("h", 0) | | |
|
||||
|--------------------->| | |
|
||||
| | circuit.add_gate() | |
|
||||
| |-------------------->| |
|
||||
| Ok | | |
|
||||
|<---------------------| | |
|
||||
| | | |
|
||||
| add_gate("cx", 1, 0) | | |
|
||||
|--------------------->| | |
|
||||
| | circuit.add_gate() | |
|
||||
| |-------------------->| |
|
||||
| Ok | | |
|
||||
|<---------------------| | |
|
||||
| | | |
|
||||
| run(1000) | | |
|
||||
|--------------------->| | |
|
||||
| | session.start() | |
|
||||
| |-------------------->| |
|
||||
| | run_to_completion() | |
|
||||
| |-------------------->| |
|
||||
| | | [gate loop] |
|
||||
| | |---+ |
|
||||
| | | | apply_gate() |
|
||||
| | |<--+ |
|
||||
| | | measure() |
|
||||
| | |---+ |
|
||||
| | | | outcomes |
|
||||
| | |<--+ |
|
||||
| | SimulationMetrics | |
|
||||
| |<--------------------| |
|
||||
| | | |
|
||||
| | JSON.serialize(counts) |
|
||||
| |---------------------------------------->|
|
||||
| "{\"00\": 503, \"11\": 497}" | |
|
||||
|<---------------------| | |
|
||||
| | | |
|
||||
| [JS callback with results] | |
|
||||
| | | |
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Migration Strategy
|
||||
|
||||
### Phase 1: Standalone ruqu-core
|
||||
|
||||
**Goal**: A self-contained crate with no external dependencies except `ruvector-math`.
|
||||
|
||||
- Implement `QuantumCircuit`, `QuantumState`, `SimulationSession` aggregates
|
||||
- Implement `CircuitBuilder`, `GateFusionService`, `NoiseInjectionService`
|
||||
- All value objects and domain events defined
|
||||
- Unit tests and property-based tests for normalization, gate unitarity
|
||||
- No coherence bridge, no agent integration, no WASM
|
||||
|
||||
**Dependency**: `ruvector-math` (shared kernel only)
|
||||
|
||||
### Phase 2: ruqu-algorithms + Coherence Integration
|
||||
|
||||
**Goal**: Add VQE, surface code experiments, and the coherence bridge.
|
||||
|
||||
- Implement `VQEOptimization`, `SurfaceCodeExperiment` aggregates
|
||||
- Implement `TensorNetworkState` for circuits exceeding state vector limits
|
||||
- Build `CoherenceBridge` anti-corruption layer
|
||||
- Integrate with ruQu `FilterPipeline` and `MWPMDecoder`
|
||||
- Add `PauliExpectationService`, `ContractionPathOptimizer`
|
||||
- Integration tests: VQE convergence, surface code logical error rate vs theory
|
||||
|
||||
**Dependencies**: `ruqu-core`, `ruvector-math`, `ruqu` (coherence bridge target)
|
||||
|
||||
### Phase 3: ruqu-wasm
|
||||
|
||||
**Goal**: Deploy to browser environments with graceful degradation.
|
||||
|
||||
- Implement `WasmSimulator` conformist wrapper
|
||||
- Add `wasm-bindgen` API surface
|
||||
- Enforce WASM constraints (25-qubit limit, no threads, no filesystem)
|
||||
- JavaScript test harness running circuits in headless browser
|
||||
- Performance benchmarks: gate throughput in WASM vs native
|
||||
|
||||
**Dependencies**: `ruqu-core`, `wasm-bindgen`, `wasm-pack`
|
||||
|
||||
### Phase 4: Full Agent System Integration
|
||||
|
||||
**Goal**: Complete customer-supplier integration with the claude-flow agent system.
|
||||
|
||||
- Implement `SimulationContract` trait and production adapter
|
||||
- Add resource estimation and budget enforcement
|
||||
- Implement `GraphQuantumPartnership` for QAOA/MaxCut
|
||||
- Integration with `ruvector-graph` for graph problem decomposition
|
||||
- End-to-end tests: agent builds circuit, runs simulation, acts on results
|
||||
- OpenQASM import/export (published language)
|
||||
|
||||
**Dependencies**: All previous phases, `ruvector-graph`, `claude-flow` agent SDK
|
||||
|
||||
---
|
||||
|
||||
## References
|
||||
|
||||
1. Evans, E. (2003). "Domain-Driven Design: Tackling Complexity in the Heart of Software."
|
||||
2. Vernon, V. (2013). "Implementing Domain-Driven Design." Chapter 13: Integrating Bounded Contexts.
|
||||
3. Coherence Engine DDD: `docs/architecture/coherence-engine-ddd.md`
|
||||
4. ruQu crate: `crates/ruQu/`
|
||||
5. ruvector-math: shared kernel for SIMD and complex number operations
|
||||
6. OpenQASM 3.0 specification: https://openqasm.com/
|
||||
530
vendor/ruvector/docs/architecture/quantum-engine/quantum-engine-ddd-strategic.md
vendored
Normal file
530
vendor/ruvector/docs/architecture/quantum-engine/quantum-engine-ddd-strategic.md
vendored
Normal file
@@ -0,0 +1,530 @@
|
||||
# Quantum Simulation Engine: Domain-Driven Design - Strategic Design
|
||||
|
||||
**Version**: 0.1
|
||||
**Date**: 2026-02-06
|
||||
**Status**: Draft
|
||||
|
||||
---
|
||||
|
||||
## Domain Vision
|
||||
|
||||
The Quantum Simulation Engine provides **on-device quantum algorithm experimentation** within ruVector's always-on, agentic environment. It enables hybrid classical-quantum research on edge devices, allowing agents to leverage quantum algorithms (VQE, Grover, QAOA, QEC) without cloud services.
|
||||
|
||||
> **This is not a cloud quantum API.** The engine answers: "What does this quantum circuit produce?" entirely on the local device, using classical state-vector simulation with SIMD acceleration.
|
||||
|
||||
The engine follows ruVector's event-driven model: **inert when idle, activated on demand, resources released immediately**. A 20-qubit simulation allocates 16 MiB of state vector on activation and frees it the moment the circuit completes. No background threads, no persistent memory, no warm pools.
|
||||
|
||||
### The Universal Simulation Object
|
||||
|
||||
The power lies in a **single underlying state-vector engine** inside ruqu-sim. Once the linear algebra is fixed, everything else becomes interpretation:
|
||||
|
||||
| Domain | Qubits Become | Gates Become | Measurement Becomes | Circuit Becomes |
|
||||
|--------|---------------|--------------|---------------------|-----------------|
|
||||
| **Chemistry** | Molecular orbitals | Fermionic operators | Energy estimates | VQE ansatz |
|
||||
| **Optimization** | Decision variables | Mixing/cost ops | Cut values | QAOA circuit |
|
||||
| **Search** | Database indices | Oracle + diffusion | Found element | Grover iterations |
|
||||
| **Error Correction** | Data + ancilla qubits | Stabilizer checks | Syndrome bits | QEC cycle |
|
||||
| **Cryptography** | Key register bits | Quantum Fourier transform | Period estimate | Shor subroutine |
|
||||
| **Machine Learning** | Feature dimensions | Parameterized rotations | Classification | Quantum kernel |
|
||||
|
||||
**Same linear algebra, different interpretations. Same state vector = superposition. Same measurement = probabilistic collapse with Born rule.**
|
||||
|
||||
---
|
||||
|
||||
## Strategic Design
|
||||
|
||||
### Core Domain
|
||||
|
||||
**Quantum State Simulation** - The heart of the system, managing quantum state vectors, applying unitary gate operations, and performing projective measurements. This is where the primary complexity and innovation reside. **Most circuits run in a single fast pass; only large entangled states or iterative variational loops require sustained computation.**
|
||||
|
||||
### Supporting Domains
|
||||
|
||||
1. **Circuit Construction** - Building, validating, and optimizing quantum circuits
|
||||
2. **State Management** - State vector lifecycle, entanglement tracking, memory gating
|
||||
3. **Measurement & Observation** - Projective measurement, expectation values, syndrome extraction
|
||||
4. **Algorithm Execution** - High-level quantum algorithm implementations (VQE, Grover, QAOA, QEC)
|
||||
5. **Optimization & Backend** - SIMD acceleration, gate fusion, tensor network backends
|
||||
6. **Deployment & Integration** - WASM compilation, agent bridge, coherence bridge to ruQu
|
||||
|
||||
### Generic Domains
|
||||
|
||||
1. **Linear Algebra** - Complex number math, matrix-vector products, Kronecker products (via `ruvector-math`)
|
||||
2. **Random Sampling** - Measurement outcome sampling, noise injection (via `rand` crate)
|
||||
3. **Logging/Tracing** - Event recording, performance metrics (via `tracing` crate + `ruvector-metrics`)
|
||||
|
||||
### Application Evolution
|
||||
|
||||
| Timeline | Capabilities | Key Value |
|
||||
|----------|-------------|-----------|
|
||||
| **Phase 1 (Now)** | State vector sim, basic gates, VQE/Grover/QAOA | Local quantum experimentation without cloud |
|
||||
| **Phase 2 (6mo)** | Tensor networks, noise models, surface code cycles | Error correction research on edge devices |
|
||||
| **Phase 3 (12mo)** | GPU acceleration, OpenQASM 3.0 import, 30+ qubits | Production-grade quantum algorithm research |
|
||||
| **Phase 4 (24mo)** | Quantum hardware bridge, hybrid cloud-local execution | Real quantum device integration |
|
||||
|
||||
> **Edge-First Quantum**: The system eventually enables agents to reason about quantum algorithms without any network dependency.
|
||||
|
||||
---
|
||||
|
||||
## Ecosystem Integration Map
|
||||
|
||||
```
|
||||
+---------------------------------------------------------------------------+
|
||||
| QUANTUM SIMULATION ENGINE |
|
||||
| |
|
||||
| +-------------------------------------------------------------------+ |
|
||||
| | CIRCUIT CONSTRUCTION DOMAIN | |
|
||||
| | QuantumCircuit | Gate | GateSchedule | CircuitOptimizer | |
|
||||
| | Parameterized templates (VQE ansatz, QAOA mixer, Grover oracle) | |
|
||||
| +-------------------------------------------------------------------+ |
|
||||
| | |
|
||||
| v |
|
||||
| +-----------------------------+ +-----------------------------+ |
|
||||
| | CORE: QUANTUM STATE | | STATE MANAGEMENT | |
|
||||
| | SIMULATION |<-| DOMAIN | |
|
||||
| | | | | |
|
||||
| | * State vector engine | | * Allocation / deallocation | |
|
||||
| | * Gate application (SIMD) | | * Entanglement tracking | |
|
||||
| | * Unitary evolution | | * Memory gating (zero-idle) | |
|
||||
| | * Tensor contraction | | * State checkpointing | |
|
||||
| +-----------------------------+ +-----------------------------+ |
|
||||
| | | | |
|
||||
| v v v |
|
||||
| +-----------------------------+ +-----------------------------+ |
|
||||
| | MEASUREMENT & | | ALGORITHM EXECUTION | |
|
||||
| | OBSERVATION DOMAIN | | DOMAIN | |
|
||||
| | | | | |
|
||||
| | * Projective measurement | | * VQE + classical optimizer | |
|
||||
| | * Expectation values | | * Grover auto-iteration | |
|
||||
| | * Shot-based sampling | | * QAOA graph-based circuits | |
|
||||
| | * Syndrome extraction | | * Surface code + decoder | |
|
||||
| +-----------------------------+ +-----------------------------+ |
|
||||
| | |
|
||||
| v |
|
||||
| +-----------------------------+ +-----------------------------+ |
|
||||
| | OPTIMIZATION & | | DEPLOYMENT & | |
|
||||
| | BACKEND DOMAIN | | INTEGRATION DOMAIN | |
|
||||
| | | | | |
|
||||
| | * SIMD dispatch | | * WASM bindings (ruqu-wasm) | |
|
||||
| | * Gate fusion | | * Agent bridge (activation) | |
|
||||
| | * Tensor network backend | | * Observability / metrics | |
|
||||
| | * Cache-local strategies | | * Coherence bridge (ruQu) | |
|
||||
| +-----------------------------+ +-----------------------------+ |
|
||||
| |
|
||||
+---------------------------------------------------------------------------+
|
||||
|
|
||||
+--------------------+---------------------+
|
||||
| | |
|
||||
v v v
|
||||
+--------------+ +-----------------+ +------------------+
|
||||
| ruvector- | | ruvector- | | ruQu |
|
||||
| math (SIMD) | | metrics | | (decoder bridge) |
|
||||
+--------------+ +-----------------+ +------------------+
|
||||
| |
|
||||
v v
|
||||
+--------------+ +-----------------+ +------------------+
|
||||
| ruvector- | | ruvector- | | cognitum-gate- |
|
||||
| graph | | nervous-system | | kernel (tiles) |
|
||||
+--------------+ +-----------------+ +------------------+
|
||||
| |
|
||||
v v
|
||||
+--------------+ +-----------------+
|
||||
| ruvector- | | sona (adaptive |
|
||||
| mincut | | learning) |
|
||||
+--------------+ +-----------------+
|
||||
```
|
||||
|
||||
### Crate-to-Context Mapping
|
||||
|
||||
| Bounded Context | Primary Crate | Supporting Crates |
|
||||
|-----------------|---------------|-------------------|
|
||||
| Circuit Construction | `ruqu-sim` (new) | - |
|
||||
| Quantum State Simulation (Core) | `ruqu-sim` (new) | `ruvector-math` |
|
||||
| State Management | `ruqu-sim` (new) | - |
|
||||
| Measurement & Observation | `ruqu-sim` (new) | `rand` |
|
||||
| Algorithm Execution | `ruqu-sim` (new) | `ruvector-graph` (QAOA) |
|
||||
| Optimization & Backend | `ruqu-sim` (new) | `ruvector-math` (SIMD) |
|
||||
| Deployment & Integration | `ruqu-wasm` (new) | `ruqu`, `ruvector-metrics`, `ruvector-nervous-system` |
|
||||
|
||||
---
|
||||
|
||||
## Context Map
|
||||
|
||||
```
|
||||
+-----------------------------------------------------------------------+
|
||||
| QUANTUM ENGINE CONTEXT MAP |
|
||||
| |
|
||||
| [Published Language] |
|
||||
| OpenQASM 3.0 format |
|
||||
| | |
|
||||
| v |
|
||||
| +------------------+ +------------------+ |
|
||||
| | | Shared | | |
|
||||
| | CIRCUIT | Kernel | STATE | |
|
||||
| | CONSTRUCTION |<------->| MANAGEMENT | |
|
||||
| | | (Gate, | | |
|
||||
| | Builds circuits | QubitIdx| Allocates and | |
|
||||
| | Validates gates | types) | tracks state | |
|
||||
| +--------+---------+ +--------+---------+ |
|
||||
| | | |
|
||||
| | Customer | Customer |
|
||||
| | Supplier | Supplier |
|
||||
| v v |
|
||||
| +------------------+ +------------------+ |
|
||||
| | | | | |
|
||||
| | MEASUREMENT & |-------->| ALGORITHM | |
|
||||
| | OBSERVATION |Supplier | EXECUTION | |
|
||||
| | |Customer | | |
|
||||
| | Measures states | | Runs VQE/QAOA/ | |
|
||||
| | Extracts syndr. | | Grover/QEC | |
|
||||
| +--------+---------+ +--------+---------+ |
|
||||
| | | |
|
||||
| +------------+---------------+ |
|
||||
| | |
|
||||
| v |
|
||||
| +------------------+ +------------------+ |
|
||||
| | | | | |
|
||||
| | OPTIMIZATION & | | DEPLOYMENT & | |
|
||||
| | BACKEND | | INTEGRATION | |
|
||||
| | | | | |
|
||||
| | SIMD, fusion, | | WASM, agents, | |
|
||||
| | tensor networks | | ruQu bridge | |
|
||||
| +------------------+ +--------+---------+ |
|
||||
| | |
|
||||
| Conformist | Anti-Corruption |
|
||||
| (ruVector | Layer |
|
||||
| APIs) | (ruQu decoder) |
|
||||
| | |
|
||||
+--------------------------------------------------+---------------------+
|
||||
|
|
||||
v
|
||||
[Existing ruVector Ecosystem]
|
||||
|
||||
Context Relationships:
|
||||
<-------> Shared Kernel (shared types across boundary)
|
||||
-------> Customer-Supplier (downstream depends on upstream)
|
||||
Conformist: Deployment conforms to existing ruVector APIs
|
||||
ACL: CoherenceBridge wraps ruQu decoder behind anti-corruption layer
|
||||
Published Language: OpenQASM 3.0 for circuit interchange
|
||||
Open Host Service: ruqu-wasm exposes JS API
|
||||
```
|
||||
|
||||
### Relationship Summary
|
||||
|
||||
| Upstream | Downstream | Pattern | Shared Types |
|
||||
|----------|------------|---------|-------------|
|
||||
| Circuit Construction | State Management | **Shared Kernel** | `Gate`, `QubitIndex`, `GateMatrix` |
|
||||
| Measurement & Observation | Algorithm Execution | **Customer-Supplier** | `MeasurementOutcome`, `ExpectationValue` |
|
||||
| State Management | Algorithm Execution | **Customer-Supplier** | `QuantumState`, `StateCheckpoint` |
|
||||
| State Management | Measurement & Observation | **Customer-Supplier** | `QuantumState`, `Amplitude` |
|
||||
| Optimization & Backend | Core Simulation | **Partnership** | `FusedGateMatrix`, `OptimizationHint` |
|
||||
| Existing ruVector APIs | Deployment & Integration | **Conformist** | ruVector event types, metric types |
|
||||
| ruQu decoder API | Deployment & Integration | **Anti-Corruption Layer** | Isolated behind `CoherenceBridge` |
|
||||
| Circuit Construction | External tools | **Published Language** | OpenQASM 3.0 circuit format |
|
||||
| Deployment & Integration | JS consumers | **Open Host Service** | `ruqu-wasm` JS API |
|
||||
|
||||
---
|
||||
|
||||
## Ubiquitous Language
|
||||
|
||||
### Quantum Fundamentals
|
||||
|
||||
| Term | Definition |
|
||||
|------|------------|
|
||||
| **Qubit** | Fundamental unit of quantum information existing in superposition of |0> and |1> basis states |
|
||||
| **Amplitude** | Complex number representing probability amplitude of a basis state; measurement probability is its squared modulus |
|
||||
| **State Vector** | Array of 2^n complex amplitudes representing the full quantum state of an n-qubit register |
|
||||
| **Basis State** | One of 2^n classical bit-string configurations; each has an associated amplitude |
|
||||
| **Superposition** | State where multiple basis states have nonzero amplitude |
|
||||
| **Entanglement** | Quantum correlation preventing independent per-qubit factorization of the joint state |
|
||||
| **Born Rule** | Measurement probability equals squared modulus of amplitude: P(x) = |alpha_x|^2 |
|
||||
|
||||
### Circuit Model
|
||||
|
||||
| Term | Definition |
|
||||
|------|------------|
|
||||
| **Gate** | Unitary matrix operation acting on 1 or 2 qubits; transforms state via matrix-vector multiply |
|
||||
| **Circuit** | Ordered sequence of gates applied to a qubit register; the program of a quantum computation |
|
||||
| **Gate Matrix** | Unitary matrix defining gate action; must satisfy U * U_dagger = I |
|
||||
| **Qubit Index** | Zero-based integer identifying a qubit; determines which amplitude pairs a gate addresses |
|
||||
| **Circuit Depth** | Maximum sequential gate layers; primary determinant of simulation time |
|
||||
| **Parameterized Gate** | Gate whose matrix depends on continuous real parameters (e.g., Ry(theta)) |
|
||||
| **Gate Fusion** | Combining adjacent gates on same qubits into a single matrix multiply |
|
||||
| **Gate Schedule** | Topologically sorted gate-to-timestep assignment respecting qubit-sharing constraints |
|
||||
|
||||
### Measurement & Algorithms
|
||||
|
||||
| Term | Definition |
|
||||
|------|------------|
|
||||
| **Measurement** | Projective observation collapsing superposition to a basis state per the Born rule |
|
||||
| **Mid-Circuit Measurement** | Measurement during (not only at end of) circuit execution |
|
||||
| **Shot** | Single circuit execution + measurement; repeated shots build statistics |
|
||||
| **Expectation Value** | Observable average over quantum state: <psi|H|psi> |
|
||||
| **Pauli String** | Tensor product of per-qubit Pauli operators (I/X/Y/Z) with coefficient |
|
||||
| **Hamiltonian** | Hermitian operator (weighted sum of Pauli strings) representing total energy |
|
||||
| **Syndrome** | Classical bits from ancilla measurements indicating error presence and location |
|
||||
| **Ansatz** | Parameterized circuit template encoding the variational search space |
|
||||
| **VQE** | Variational Quantum Eigensolver; iteratively minimizes Hamiltonian expectation |
|
||||
| **QAOA** | Quantum Approximate Optimization Algorithm; alternating cost/mixer unitaries |
|
||||
| **Grover Search** | Amplitude amplification finding marked items in O(sqrt(N)) queries |
|
||||
| **Oracle** | Black-box gate marking target states by phase flip |
|
||||
| **Surface Code** | 2D topological QEC code with stabilizer checks on lattice faces/vertices |
|
||||
| **Logical Error Rate** | Undetected logical error probability per QEC cycle |
|
||||
| **Decoder** | Classical algorithm mapping syndromes to corrections; bridge to ruQu |
|
||||
|
||||
### Simulation Infrastructure
|
||||
|
||||
| Term | Definition |
|
||||
|------|------------|
|
||||
| **State Allocator** | On-demand allocation/deallocation enforcing zero-idle policy |
|
||||
| **Memory Estimate** | Predicted bytes: 2^n * 16; gating threshold for allocation |
|
||||
| **Entanglement Tracker** | Tracks qubit correlations enabling subsystem splitting |
|
||||
| **State Checkpoint** | Serialized state snapshot for mid-circuit save/restore |
|
||||
| **Tensor Network** | Alternative representation via contracted tensor factors; efficient for low entanglement |
|
||||
| **Contraction Path** | Tensor contraction order minimizing total FLOPs |
|
||||
|
||||
---
|
||||
|
||||
## Bounded Context Details
|
||||
|
||||
### Context 1: Circuit Construction Domain
|
||||
|
||||
**Purpose**: Language for expressing quantum computations. Validation, scheduling, optimization, OpenQASM interchange.
|
||||
|
||||
| Entity / Value Object | Type | Responsibility |
|
||||
|----------------------|------|---------------|
|
||||
| **QuantumCircuit** | Aggregate Root | Ordered gate collection with register metadata |
|
||||
| **Gate** | Entity | Single unitary with target qubits and optional parameters |
|
||||
| **GateSchedule** | Entity | Time-step assignment for parallel execution analysis |
|
||||
| **CircuitOptimizer** | Domain Service | Fusion, cancellation, and commutation rules |
|
||||
| GateId, QubitIndex, GateMatrix, ParameterBinding, GateType | Value Objects | Immutable circuit building blocks |
|
||||
|
||||
**Events**: `CircuitCreated`, `GateAppended`, `CircuitOptimized`, `CircuitValidated`, `ParametersBound`
|
||||
|
||||
**Invariants**: (1) Gate unitarity. (2) Qubit indices within bounds. (3) No duplicate targets per gate. (4) All parameters bound before execution.
|
||||
|
||||
---
|
||||
|
||||
### Context 2: State Management Domain
|
||||
|
||||
**Purpose**: State vector lifecycle following zero-idle model. Entanglement tracking. Memory gating.
|
||||
|
||||
| Entity / Value Object | Type | Responsibility |
|
||||
|----------------------|------|---------------|
|
||||
| **QuantumState** | Aggregate Root | Owns the 2^n complex amplitude array |
|
||||
| **EntanglementTracker** | Entity | Bipartite entanglement graph for subsystem analysis |
|
||||
| **StateAllocator** | Domain Service | On-demand allocation, immediate deallocation |
|
||||
| Amplitude, QubitCount, MemoryEstimate, StateCheckpoint | Value Objects | State representation primitives |
|
||||
|
||||
**Events**: `StateAllocated`, `StateDeallocated`, `EntanglementDetected`, `SubsystemSplit`, `CheckpointCreated`, `MemoryLimitExceeded`
|
||||
|
||||
**Invariants**: (1) Normalization preserved. (2) Zero-idle: no state persists beyond execution. (3) Allocation gated by device capacity. (4) Checkpoint restore reproduces exact amplitudes.
|
||||
|
||||
---
|
||||
|
||||
### Context 3: Measurement & Observation Domain
|
||||
|
||||
**Purpose**: Projective measurement with collapse. Analytical expectation values. Syndrome extraction for QEC.
|
||||
|
||||
| Entity / Value Object | Type | Responsibility |
|
||||
|----------------------|------|---------------|
|
||||
| **MeasurementEngine** | Aggregate Root | Born-rule sampling and state collapse |
|
||||
| **ExpectationCalculator** | Entity | Analytical <psi|H|psi> from Pauli decomposition |
|
||||
| **SyndromeExtractor** | Entity | Ancilla measurement and classical bit extraction |
|
||||
| MeasurementOutcome, PauliString, Hamiltonian, SyndromeBits, ShotResult | Value Objects | Measurement data types |
|
||||
|
||||
**Events**: `MeasurementPerformed`, `ExpectationComputed`, `SyndromeExtracted`, `ShotsCompleted`
|
||||
|
||||
**Invariants**: (1) Born rule: probabilities sum to 1.0. (2) Post-measurement collapse to definite state. (3) Hamiltonian Hermiticity. (4) Syndrome bit count matches code.
|
||||
|
||||
---
|
||||
|
||||
### Context 4: Algorithm Execution Domain
|
||||
|
||||
**Purpose**: High-level quantum algorithms as orchestrated loops over circuits, states, and measurements.
|
||||
|
||||
| Entity / Value Object | Type | Responsibility |
|
||||
|----------------------|------|---------------|
|
||||
| **VQERunner** | Entity | Iterative ansatz parameter optimization to minimize energy |
|
||||
| **GroverSearch** | Entity | Oracle + diffusion with auto-computed iteration count |
|
||||
| **QAOASolver** | Entity | Graph-based cost/mixer circuit construction and angle optimization |
|
||||
| **SurfaceCodeSimulator** | Entity | Stabilizer cycles, syndrome extraction, decoder invocation |
|
||||
| AlgorithmResult, OptimizationTrace, CutValue, LogicalErrorRate, ConvergenceCriteria | Value Objects | Algorithm output types |
|
||||
|
||||
**Events**: `VQEIterationCompleted`, `VQEConverged`, `GroverSearchCompleted`, `QAOARoundCompleted`, `SurfaceCodeCycleCompleted`, `LogicalErrorDetected`
|
||||
|
||||
**Invariants**: (1) Grover iteration count = floor(pi/4 * sqrt(N/M)). (2) VQE energy is upper bound on ground state. (3) QAOA cost/mixer alternate with correct parameter count. (4) Surface code distance matches lattice.
|
||||
|
||||
---
|
||||
|
||||
### Context 5: Optimization & Backend Domain
|
||||
|
||||
**Purpose**: Performance backends that accelerate simulation without altering semantics. SIMD, fusion, tensor networks.
|
||||
|
||||
| Entity / Value Object | Type | Responsibility |
|
||||
|----------------------|------|---------------|
|
||||
| **SimulationBackend** | Aggregate Root | Selects optimal execution strategy |
|
||||
| **GateFuser** | Entity | Combines compatible gate sequences into single operations |
|
||||
| **TensorContractor** | Entity | Tensor network decomposition for low-entanglement states |
|
||||
| **SIMDDispatcher** | Entity | Platform detection and optimized kernel dispatch |
|
||||
| OptimizationHint, ContractionPath, FusedGateMatrix, PlatformCapabilities | Value Objects | Backend selection metadata |
|
||||
|
||||
**Events**: `BackendSelected`, `GatesFused`, `TensorNetworkContracted`, `SIMDKernelDispatched`
|
||||
|
||||
**Invariants**: (1) Fused gates produce identical results to sequential. (2) Tensor contraction matches state-vector. (3) SIMD falls back to scalar if unavailable. (4) Intermediates stay within memory budget.
|
||||
|
||||
---
|
||||
|
||||
### Context 6: Deployment & Integration Domain
|
||||
|
||||
**Purpose**: WASM compilation, agent activation bridge, ruQu decoder anti-corruption layer, observability.
|
||||
|
||||
| Entity / Value Object | Type | Responsibility |
|
||||
|----------------------|------|---------------|
|
||||
| **WASMBindings** | Entity | Open Host Service via wasm-bindgen JS API |
|
||||
| **AgentBridge** | Entity | ruvector-nervous-system integration for context-triggered activation |
|
||||
| **MetricsReporter** | Entity | Publishes SimulationMetrics to ruvector-metrics |
|
||||
| **CoherenceBridge** | Entity | ACL translating syndromes to ruQu's DetectorBitmap/SyndromeRound |
|
||||
| PlatformCapabilities, QubitLimit, SimulationMetrics, DecoderResult | Value Objects | Integration data types |
|
||||
|
||||
**Events**: `SimulationRequested`, `SimulationCompleted`, `ResourcesReleased`, `DecoderInvoked`, `MetricsPublished`
|
||||
|
||||
**Integration Patterns**:
|
||||
- **Anti-Corruption Layer**: CoherenceBridge isolates engine from ruQu's internal DDD model
|
||||
- **Conformist**: Deployment conforms to existing ruVector event types and metric schemas
|
||||
- **Open Host Service**: ruqu-wasm exposes clean JS/TS API for browser experimentation
|
||||
- **Published Language**: OpenQASM 3.0 for circuit interchange with external tools
|
||||
|
||||
---
|
||||
|
||||
## Cross-Cutting Concerns
|
||||
|
||||
### Zero-Idle Resource Model
|
||||
|
||||
```
|
||||
IDLE (0 bytes) --> ACTIVATE (allocate 2^n * 16 bytes) --> COMPUTE --> RELEASE (0 bytes)
|
||||
```
|
||||
|
||||
No warm pools, no pre-allocated buffers, no background threads.
|
||||
|
||||
### Memory Gating
|
||||
|
||||
| Qubits | State Vector Size | Decision |
|
||||
|--------|-------------------|----------|
|
||||
| 10 | 16 KiB | Always permit |
|
||||
| 15 | 512 KiB | Always permit |
|
||||
| 20 | 16 MiB | Permit on most devices |
|
||||
| 25 | 512 MiB | Gate: check available RAM |
|
||||
| 30 | 16 GiB | Gate: likely refuse on edge |
|
||||
| 35+ | 512 GiB+ | Always refuse (state vector); consider tensor network |
|
||||
|
||||
### Error Model
|
||||
|
||||
| Context | Error | Severity | Recovery |
|
||||
|---------|-------|----------|----------|
|
||||
| Circuit Construction | Non-unitary gate | Fatal | Reject circuit |
|
||||
| State Management | Memory limit exceeded | Recoverable | Try tensor network or refuse |
|
||||
| State Management | Normalization drift | Warning | Renormalize |
|
||||
| Measurement | Zero-probability outcome | Warning | Return uniform |
|
||||
| Algorithm Execution | VQE non-convergence | Recoverable | Return best-so-far |
|
||||
| Deployment | WASM memory limit | Fatal | Report to agent |
|
||||
| Deployment | ruQu decoder unavailable | Recoverable | Skip correction, log |
|
||||
|
||||
### Observability
|
||||
|
||||
All simulation runs produce `SimulationMetrics` (circuit name, qubit count, gate count, depth, shots, backend type, wall time, peak memory, SIMD utilization) flowing through `ruvector-metrics` for unified dashboard integration.
|
||||
|
||||
### Security
|
||||
|
||||
| Concern | Mitigation |
|
||||
|---------|------------|
|
||||
| Timing side channels in measurement | Constant-time sampling via rejection method |
|
||||
| Memory contents after deallocation | Zero-fill on deallocation (SecureAllocator mode) |
|
||||
| Denial-of-service via large qubit counts | Memory gating with hard upper bound per request |
|
||||
| Untrusted OpenQASM input | Parser validates unitarity and qubit bounds before execution |
|
||||
| WASM sandbox escape | No file I/O, no network; pure computation within WASM sandbox |
|
||||
|
||||
---
|
||||
|
||||
## Module Structure
|
||||
|
||||
```
|
||||
crates/ruqu-sim/src/
|
||||
+-- lib.rs # Public API
|
||||
+-- circuit/ # Circuit Construction context
|
||||
| +-- quantum_circuit.rs # QuantumCircuit aggregate
|
||||
| +-- gate.rs # Gate entity, GateType enum
|
||||
| +-- schedule.rs # GateSchedule
|
||||
| +-- optimizer.rs # CircuitOptimizer (fusion, cancel)
|
||||
| +-- openqasm.rs # OpenQASM 3.0 import/export
|
||||
+-- state/ # State Management context
|
||||
| +-- quantum_state.rs # QuantumState aggregate
|
||||
| +-- allocator.rs # StateAllocator (zero-idle)
|
||||
| +-- entanglement.rs # EntanglementTracker
|
||||
| +-- checkpoint.rs # StateCheckpoint
|
||||
+-- measurement/ # Measurement & Observation context
|
||||
| +-- engine.rs # MeasurementEngine
|
||||
| +-- expectation.rs # ExpectationCalculator
|
||||
| +-- syndrome.rs # SyndromeExtractor
|
||||
+-- algorithms/ # Algorithm Execution context
|
||||
| +-- vqe.rs, grover.rs # VQERunner, GroverSearch
|
||||
| +-- qaoa.rs # QAOASolver
|
||||
| +-- surface_code.rs # SurfaceCodeSimulator
|
||||
+-- backend/ # Optimization & Backend context
|
||||
| +-- simulation_backend.rs # SimulationBackend
|
||||
| +-- gate_fuser.rs # GateFuser
|
||||
| +-- tensor_network.rs # TensorContractor
|
||||
| +-- simd_dispatch.rs # SIMDDispatcher
|
||||
| +-- kernels/ # avx2.rs, avx512.rs, neon.rs, wasm_simd.rs, scalar.rs
|
||||
+-- types.rs, events.rs, error.rs
|
||||
|
||||
crates/ruqu-wasm/src/
|
||||
+-- lib.rs # wasm-bindgen entry
|
||||
+-- js_api.rs # JS-facing API
|
||||
+-- agent_bridge.rs # ruvector-nervous-system integration
|
||||
+-- coherence_bridge.rs # ACL for ruQu decoder
|
||||
+-- metrics.rs # ruvector-metrics export
|
||||
```
|
||||
|
||||
### Dependency Graph
|
||||
|
||||
```
|
||||
ruqu-sim
|
||||
+-- ruvector-math (SIMD kernels, complex math)
|
||||
+-- rand (measurement sampling)
|
||||
+-- ruvector-graph (QAOA graph input)
|
||||
|
||||
ruqu-wasm
|
||||
+-- ruqu-sim (core simulation)
|
||||
+-- ruqu (coherence bridge ACL)
|
||||
+-- ruvector-metrics (observability)
|
||||
+-- ruvector-nervous-system (agent activation)
|
||||
+-- wasm-bindgen (JS bindings)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Performance Targets
|
||||
|
||||
| Metric | Target |
|
||||
|--------|--------|
|
||||
| Single-gate (1q, 20-qubit register) | < 50 us |
|
||||
| Full circuit (100 gates, 15 qubits) | < 10 ms |
|
||||
| Hamiltonian expectation (10q, 50 terms) | < 1 ms |
|
||||
| SIMD speedup over scalar | > 3x (AVX2), > 6x (AVX-512) |
|
||||
| Grover (20 qubits, 1 target) | < 500 ms |
|
||||
| VQE convergence (H2, 4 qubits) | < 5s, < 100 iterations |
|
||||
| State allocation/deallocation | < 10 us / < 1 us |
|
||||
| WASM circuit (10 qubits, 50 gates) | < 50 ms |
|
||||
|
||||
---
|
||||
|
||||
## References
|
||||
|
||||
1. Evans, E. (2003). "Domain-Driven Design: Tackling Complexity in the Heart of Software."
|
||||
2. Vernon, V. (2013). "Implementing Domain-Driven Design."
|
||||
3. Nielsen, M. A. & Chuang, I. L. (2010). "Quantum Computation and Quantum Information."
|
||||
4. Peruzzo, A. et al. (2014). "A variational eigenvalue solver on a photonic quantum processor."
|
||||
5. Farhi, E. et al. (2014). "A Quantum Approximate Optimization Algorithm."
|
||||
6. Fowler, A. G. et al. (2012). "Surface codes: Towards practical large-scale quantum computation."
|
||||
7. ruQu crate: Existing coherence assessment and syndrome processing in ruVector.
|
||||
8. Coherence Engine DDD: `/docs/architecture/coherence-engine-ddd.md`
|
||||
1426
vendor/ruvector/docs/architecture/quantum-engine/quantum-engine-ddd-tactical.md
vendored
Normal file
1426
vendor/ruvector/docs/architecture/quantum-engine/quantum-engine-ddd-tactical.md
vendored
Normal file
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user