Skip to main content

aria_engine_core/
engine.rs

1//! Aria Engine — Spec-faithful state machine.
2//!
3//! Implements Init, Next, Spec per FORMAL_SPEC.md.
4//! Checks Inv1–4 after every apply.
5//! The scheduler is policy, not Spec.
6
7use std::fmt::Debug;
8
9use crate::action::Action;
10use crate::condition::Condition;
11use crate::config::AriaConfig;
12use crate::error::AriaError;
13use crate::graph::Graph;
14use crate::invariants;
15use crate::invariants::InvariantReport;
16use crate::policy::{DiffPolicy, MatchPolicy};
17use crate::scheduler::Scheduler;
18use crate::state::State;
19use crate::trace::Trace;
20
21/// Optical backend trait — PRD §5.3
22pub trait OpticalBackend: Debug + Send + Sync {
23    /// Apply unitary step: ψ' = U_t(ψ)
24    fn unitary_step(&self, t: u64, psi: &[num_complex::Complex64]) -> Vec<num_complex::Complex64>;
25    /// Field energy: ‖ψ‖₂
26    fn energy(&self, psi: &[num_complex::Complex64]) -> f64;
27}
28
29/// Predictor backend trait — PRD §5.3
30pub trait Predictor: Debug + Send + Sync {
31    /// Isometry I: H → Z
32    fn embed(&self, psi: &[num_complex::Complex64]) -> Vec<f64>;
33    /// Predictor P: Z × Condition → Z
34    fn predict(&self, z: &[f64], a: Condition) -> Vec<f64>;
35    /// Distance in latent space
36    fn dist(&self, a: &[f64], b: &[f64]) -> f64;
37}
38
39/// Graph backend trait — PRD §5.3
40pub trait GraphBackend: Debug + Send + Sync {
41    /// Edit graph: G' = ED(G ⊕ z, policy, G*)
42    fn edit(
43        &self,
44        g: &Graph,
45        z: &[f64],
46        policy: MatchPolicy,
47        target: Option<&Graph>,
48    ) -> Graph;
49    /// GraphOK check
50    fn ok(&self, g: &Graph) -> bool;
51}
52
53/// Diffuser backend trait — PRD §5.3
54pub trait Diffuser: Debug + Send + Sync {
55    /// Diffusion step: z' = Diff_G(z)
56    fn diffuse(&self, g: &Graph, z: &[f64], policy: DiffPolicy) -> Vec<f64>;
57}
58
59/// Aria Engine — the Spec state machine with pluggable backends.
60#[derive(Debug)]
61pub struct Engine<O, P, G, D>
62where
63    O: OpticalBackend,
64    P: Predictor,
65    G: GraphBackend,
66    D: Diffuser,
67{
68    config: AriaConfig,
69    optical: O,
70    predictor: P,
71    graph_backend: G,
72    diffuser: D,
73}
74
75impl<O, P, GB, D> Engine<O, P, GB, D>
76where
77    O: OpticalBackend,
78    P: Predictor,
79    GB: GraphBackend,
80    D: Diffuser,
81{
82    /// Create a new engine with backends and config.
83    pub fn new(config: AriaConfig, optical: O, predictor: P, graph_backend: GB, diffuser: D) -> Self {
84        Engine {
85            config,
86            optical,
87            predictor,
88            graph_backend,
89            diffuser,
90        }
91    }
92
93    /// Init: create the initial state per FORMAL_SPEC §5.
94    ///
95    /// ψ = ψ₀, z = I(ψ₀), G = G₀, t = 0,
96    /// prevRes = d(I(ψ₀), P(I(ψ₀), a(0)))
97    pub fn init(&self, psi0: Vec<num_complex::Complex64>, g0: Graph, a0: Condition) -> State {
98        let energy_0 = self.optical.energy(&psi0);
99        let z0 = self.predictor.embed(&psi0);
100        let p0 = self.predictor.predict(&z0, a0);
101        let prev_res = self.predictor.dist(&z0, &p0);
102
103        State {
104            psi: psi0,
105            z: z0,
106            g: g0,
107            t: 0,
108            prev_res,
109            energy_0,
110        }
111    }
112
113    /// Apply a single named action to the state.
114    ///
115    /// Returns the new state on success, or an invariant violation.
116    /// This is the Spec's Next relation turned into a deterministic function.
117    pub fn apply(
118        &self,
119        mut state: State,
120        action: Action,
121        a: Condition,
122    ) -> Result<State, AriaError> {
123        match action {
124            Action::OpticalStep => {
125                // ψ' = U_t(ψ); UNCHANGED ⟨z, G, t⟩ — FORMAL_SPEC §6.1
126                let prev_psi = state.psi.clone();
127                state.psi = self.optical.unitary_step(state.t, &state.psi);
128
129                // Update prevRes aux history
130                let residual = self.compute_residual(&state, a);
131                state.prev_res = residual;
132
133                // Check invariants
134                let report = invariants::check_all(&state, residual, self.config.eps, self.config.latent_dim);
135                if self.config.strict && !report.all_ok() {
136                    if let Some(v) = invariants::violation_from_report(
137                        &report, action, state.energy(), state.energy_0,
138                        residual, state.prev_res, self.config.eps,
139                    ) {
140                        state.psi = prev_psi; // rollback
141                        return Err(AriaError::InvariantViolation(v));
142                    }
143                }
144            }
145
146            Action::Predict => {
147                // z' = P(I(ψ), a_t); UNCHANGED ⟨ψ, G, t⟩ — FORMAL_SPEC §6.2
148                let prev_z = state.z.clone();
149                state.z = self.predictor.predict(&self.predictor.embed(&state.psi), a);
150
151                let residual = self.compute_residual(&state, a);
152                state.prev_res = residual;
153
154                let report = invariants::check_all(&state, residual, self.config.eps, self.config.latent_dim);
155                if self.config.strict && !report.all_ok() {
156                    if let Some(v) = invariants::violation_from_report(
157                        &report, action, state.energy(), state.energy_0,
158                        residual, state.prev_res, self.config.eps,
159                    ) {
160                        state.z = prev_z;
161                        return Err(AriaError::InvariantViolation(v));
162                    }
163                }
164            }
165
166            Action::Match => {
167                // G' = ED(G ⊕ z, G*); UNCHANGED ⟨ψ, z, t⟩ — FORMAL_SPEC §6.3
168                let prev_g = state.g.clone();
169                let mut g_with_z = state.g.clone();
170                g_with_z.add_node(
171                    format!("z_{}", state.t),
172                    state.z.clone(),
173                    Some("latent".into()),
174                );
175
176                // Enforce max graph size
177                if g_with_z.size() > self.config.max_graph_size {
178                    return Err(AriaError::Schedule(format!(
179                        "graph size {} exceeds max {}",
180                        g_with_z.size(),
181                        self.config.max_graph_size
182                    )));
183                }
184
185                state.g = self.graph_backend.edit(
186                    &g_with_z,
187                    &state.z,
188                    self.config.match_policy,
189                    None,
190                );
191
192                let residual = self.compute_residual(&state, a);
193                state.prev_res = residual;
194
195                let report = invariants::check_all(&state, residual, self.config.eps, self.config.latent_dim);
196                if self.config.strict && !report.all_ok() {
197                    if let Some(v) = invariants::violation_from_report(
198                        &report, action, state.energy(), state.energy_0,
199                        residual, state.prev_res, self.config.eps,
200                    ) {
201                        state.g = prev_g;
202                        return Err(AriaError::InvariantViolation(v));
203                    }
204                }
205            }
206
207            Action::Diffuse => {
208                // z' = Diff_G(z); t' = t+1; UNCHANGED ⟨ψ, G⟩ — FORMAL_SPEC §6.4
209                let prev_z = state.z.clone();
210                let prev_t = state.t;
211                state.z = self.diffuser.diffuse(&state.g, &state.z, self.config.diff_policy);
212                state.t += 1;
213
214                let residual = self.compute_residual(&state, a);
215                state.prev_res = residual;
216
217                let report = invariants::check_all(&state, residual, self.config.eps, self.config.latent_dim);
218                if self.config.strict && !report.all_ok() {
219                    if let Some(v) = invariants::violation_from_report(
220                        &report, action, state.energy(), state.energy_0,
221                        residual, state.prev_res, self.config.eps,
222                    ) {
223                        state.z = prev_z;
224                        state.t = prev_t;
225                        return Err(AriaError::InvariantViolation(v));
226                    }
227                }
228            }
229
230            Action::Stutter => {
231                // UNCHANGED all vars — TLA stuttering
232                // prevRes is also UNCHANGED (TLA encoding uses UNCHANGED vars including prevRes)
233                // But we still check Inv1-4 (they hold vacuously since nothing changed)
234                let residual = self.compute_residual(&state, a);
235                // prevRes is NOT updated on Stutter in the TLA encoding:
236                // Stutter == UNCHANGED vars (which includes prevRes)
237                // So we leave prevRes as-is
238
239                let report = invariants::check_all(&state, residual, self.config.eps, self.config.latent_dim);
240                if self.config.strict && !report.all_ok() {
241                    if let Some(v) = invariants::violation_from_report(
242                        &report, action, state.energy(), state.energy_0,
243                        residual, state.prev_res, self.config.eps,
244                    ) {
245                        return Err(AriaError::InvariantViolation(v));
246                    }
247                }
248            }
249        }
250
251        Ok(state)
252    }
253
254    /// Step one full Φ-cycle: OpticalStep → Predict → Match → Diffuse (𝐂4).
255    ///
256    /// This is the preferred schedule. Each sub-step checks invariants.
257    /// Returns the state after the full cycle, or the first invariant violation.
258    pub fn step_phi(&self, state: State, a: Condition) -> Result<State, AriaError> {
259        let s = state;
260        let s = self.apply(s, Action::OpticalStep, a)?;
261        let s = self.apply(s, Action::Predict, a)?;
262        let s = self.apply(s, Action::Match, a)?;
263        let s = self.apply(s, Action::Diffuse, a)?;
264        Ok(s)
265    }
266
267    /// Run the engine for a number of steps with a scheduler.
268    ///
269    /// Returns the final state and a trace of all steps.
270    pub fn run(
271        &self,
272        mut state: State,
273        scheduler: &mut Scheduler,
274        steps: u64,
275        a: Condition,
276    ) -> Result<(State, Trace), AriaError> {
277        let mut trace = Trace::new(self.config.n_modes, self.config.latent_dim, self.config.eps);
278
279        for _ in 0..steps {
280            let action = scheduler.next_action_budgeted();
281            let t_before = state.t;
282
283            state = self.apply(state, action, a)?;
284
285            let residual = self.compute_residual(&state, a);
286            let energy = state.energy();
287            trace.push(
288                t_before,
289                action,
290                residual,
291                energy,
292                state.g.size(),
293                &format!("{:?}", a).to_lowercase(),
294            );
295        }
296
297        Ok((state, trace))
298    }
299
300    /// Check all invariants on the current state without applying an action.
301    pub fn check(&self, state: &State, a: Condition) -> InvariantReport {
302        let residual = self.compute_residual(state, a);
303        invariants::check_all(state, residual, self.config.eps, self.config.latent_dim)
304    }
305
306    /// Compute JEPA residual: Res(ψ, z, t) = d(z, P(I(ψ), a_t))
307    fn compute_residual(&self, state: &State, a: Condition) -> f64 {
308        let embedded = self.predictor.embed(&state.psi);
309        let predicted = self.predictor.predict(&embedded, a);
310        self.predictor.dist(&state.z, &predicted)
311    }
312
313    /// Access config.
314    pub fn config(&self) -> &AriaConfig {
315        &self.config
316    }
317}