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::gates::{GateMonitor, GateReport};
14use crate::graph::Graph;
15use crate::invariants;
16use crate::invariants::InvariantReport;
17use crate::policy::{DiffPolicy, MatchPolicy};
18use crate::scheduler::Scheduler;
19use crate::state::State;
20use crate::trace::Trace;
21
22/// Optical backend trait — PRD §5.3
23pub trait OpticalBackend: Debug + Send + Sync {
24    /// Apply unitary step: ψ' = U_t(ψ)
25    fn unitary_step(&self, t: u64, psi: &[num_complex::Complex64]) -> Vec<num_complex::Complex64>;
26    /// Field energy: ‖ψ‖₂
27    fn energy(&self, psi: &[num_complex::Complex64]) -> f64;
28}
29
30/// Predictor backend trait — PRD §5.3
31pub trait Predictor: Debug + Send + Sync {
32    /// Isometry I: H → Z
33    fn embed(&self, psi: &[num_complex::Complex64]) -> Vec<f64>;
34    /// Predictor P: Z × Condition → Z
35    fn predict(&self, z: &[f64], a: Condition) -> Vec<f64>;
36    /// Distance in latent space
37    fn dist(&self, a: &[f64], b: &[f64]) -> f64;
38}
39
40/// Graph backend trait — PRD §5.3
41pub trait GraphBackend: Debug + Send + Sync {
42    /// Edit graph: G' = ED(G ⊕ z, policy, G*)
43    fn edit(
44        &self,
45        g: &Graph,
46        z: &[f64],
47        policy: MatchPolicy,
48        target: Option<&Graph>,
49    ) -> Graph;
50    /// GraphOK check
51    fn ok(&self, g: &Graph) -> bool;
52}
53
54/// Diffuser backend trait — PRD §5.3
55pub trait Diffuser: Debug + Send + Sync {
56    /// Diffusion step: z' = Diff_G(z)
57    fn diffuse(&self, g: &Graph, z: &[f64], policy: DiffPolicy) -> Vec<f64>;
58}
59
60/// Aria Engine — the Spec state machine with pluggable backends.
61#[derive(Debug)]
62pub struct Engine<O, P, G, D>
63where
64    O: OpticalBackend,
65    P: Predictor,
66    G: GraphBackend,
67    D: Diffuser,
68{
69    config: AriaConfig,
70    optical: O,
71    predictor: P,
72    graph_backend: G,
73    diffuser: D,
74}
75
76impl<O, P, GB, D> Engine<O, P, GB, D>
77where
78    O: OpticalBackend,
79    P: Predictor,
80    GB: GraphBackend,
81    D: Diffuser,
82{
83    /// Create a new engine with backends and config.
84    pub fn new(config: AriaConfig, optical: O, predictor: P, graph_backend: GB, diffuser: D) -> Self {
85        Engine {
86            config,
87            optical,
88            predictor,
89            graph_backend,
90            diffuser,
91        }
92    }
93
94    /// Init: create the initial state per FORMAL_SPEC §5.
95    ///
96    /// ψ = ψ₀, z = I(ψ₀), G = G₀, t = 0,
97    /// prevRes = d(I(ψ₀), P(I(ψ₀), a(0)))
98    ///
99    /// Validates shapes up front: a field of the wrong length is a config
100    /// error, not a downstream panic or a silently truncated mat-vec.
101    pub fn init(
102        &self,
103        psi0: Vec<num_complex::Complex64>,
104        g0: Graph,
105        a0: Condition,
106    ) -> Result<State, AriaError> {
107        if self.config.n_modes == 0 {
108            return Err(AriaError::Config("n_modes must be ≥ 1".into()));
109        }
110        if self.config.latent_dim == 0 {
111            return Err(AriaError::Config("latent_dim must be ≥ 1".into()));
112        }
113        if psi0.len() != self.config.n_modes {
114            return Err(AriaError::Config(format!(
115                "ψ₀ has {} modes but config.n_modes = {}",
116                psi0.len(),
117                self.config.n_modes
118            )));
119        }
120        for (i, c) in psi0.iter().enumerate() {
121            if !c.re.is_finite() || !c.im.is_finite() {
122                return Err(AriaError::Config(format!(
123                    "ψ₀[{}] = {} is not finite",
124                    i, c
125                )));
126            }
127        }
128
129        let energy_0 = self.optical.energy(&psi0);
130        let z0 = self.predictor.embed(&psi0);
131        if z0.len() != self.config.latent_dim {
132            return Err(AriaError::Config(format!(
133                "embed(ψ₀) has dim {} but config.latent_dim = {} — backend/config mismatch",
134                z0.len(),
135                self.config.latent_dim
136            )));
137        }
138        let p0 = self.predictor.predict(&z0, a0);
139        if p0.len() != self.config.latent_dim {
140            return Err(AriaError::Config(format!(
141                "P(z) has dim {} but config.latent_dim = {} — backend/config mismatch",
142                p0.len(),
143                self.config.latent_dim
144            )));
145        }
146        let prev_res = self.predictor.dist(&z0, &p0);
147
148        Ok(State {
149            psi: psi0,
150            z: z0,
151            g: g0,
152            t: 0,
153            prev_res,
154            energy_0,
155        })
156    }
157
158    /// Apply a single named action to the state.
159    ///
160    /// Returns the new state on success, or an invariant violation.
161    /// This is the Spec's Next relation turned into a deterministic function.
162    pub fn apply(
163        &self,
164        mut state: State,
165        action: Action,
166        a: Condition,
167    ) -> Result<State, AriaError> {
168        match action {
169            Action::OpticalStep => {
170                // ψ' = U_t(ψ); UNCHANGED ⟨z, G, t⟩ — FORMAL_SPEC §6.1
171                let prev_psi = state.psi.clone();
172                let prev_prev_res = state.prev_res;
173                let pre_residual = self.compute_residual(&state, a);
174
175                state.psi = self.optical.unitary_step(state.t, &state.psi);
176                // TLA history obligation: prevRes' = Res(psi, z, t)
177                state.prev_res = pre_residual;
178
179                let post_residual = self.compute_residual(&state, a);
180                let report = invariants::check_all(
181                    &state,
182                    post_residual,
183                    self.config.eps,
184                    self.config.n_modes,
185                    self.config.latent_dim,
186                );
187                if self.config.strict && !report.all_ok() {
188                    if let Some(v) = invariants::violation_from_report(
189                        &report, action, state.energy(), state.energy_0,
190                        post_residual, state.prev_res, self.config.eps,
191                    ) {
192                        state.psi = prev_psi;
193                        state.prev_res = prev_prev_res;
194                        return Err(AriaError::InvariantViolation(v));
195                    }
196                }
197            }
198
199            Action::Predict => {
200                // z' = P(I(ψ), a_t); UNCHANGED ⟨ψ, G, t⟩ — FORMAL_SPEC §6.2
201                let prev_z = state.z.clone();
202                let prev_prev_res = state.prev_res;
203                let pre_residual = self.compute_residual(&state, a);
204
205                state.z = self.predictor.predict(&self.predictor.embed(&state.psi), a);
206                state.prev_res = pre_residual;
207
208                let post_residual = self.compute_residual(&state, a);
209                let report = invariants::check_all(
210                    &state,
211                    post_residual,
212                    self.config.eps,
213                    self.config.n_modes,
214                    self.config.latent_dim,
215                );
216                if self.config.strict && !report.all_ok() {
217                    if let Some(v) = invariants::violation_from_report(
218                        &report, action, state.energy(), state.energy_0,
219                        post_residual, state.prev_res, self.config.eps,
220                    ) {
221                        state.z = prev_z;
222                        state.prev_res = prev_prev_res;
223                        return Err(AriaError::InvariantViolation(v));
224                    }
225                }
226            }
227
228            Action::Match => {
229                // G' = ED(G ⊕ z, G*); UNCHANGED ⟨ψ, z, t⟩ — FORMAL_SPEC §6.3
230                let prev_g = state.g.clone();
231                let prev_prev_res = state.prev_res;
232                let pre_residual = self.compute_residual(&state, a);
233
234                let mut g_with_z = state.g.clone();
235                g_with_z.add_node(
236                    format!("z_{}", state.t),
237                    state.z.clone(),
238                    Some("latent".into()),
239                );
240
241                // Enforce max graph size
242                if g_with_z.size() > self.config.max_graph_size {
243                    return Err(AriaError::Schedule(format!(
244                        "graph size {} exceeds max {}",
245                        g_with_z.size(),
246                        self.config.max_graph_size
247                    )));
248                }
249
250                state.g = self.graph_backend.edit(
251                    &g_with_z,
252                    &state.z,
253                    self.config.match_policy,
254                    None,
255                );
256                state.prev_res = pre_residual;
257
258                let post_residual = self.compute_residual(&state, a);
259                let report = invariants::check_all(
260                    &state,
261                    post_residual,
262                    self.config.eps,
263                    self.config.n_modes,
264                    self.config.latent_dim,
265                );
266                if self.config.strict && !report.all_ok() {
267                    if let Some(v) = invariants::violation_from_report(
268                        &report, action, state.energy(), state.energy_0,
269                        post_residual, state.prev_res, self.config.eps,
270                    ) {
271                        state.g = prev_g;
272                        state.prev_res = prev_prev_res;
273                        return Err(AriaError::InvariantViolation(v));
274                    }
275                }
276            }
277
278            Action::Diffuse => {
279                // z' = Diff_G(z); t' = t+1; UNCHANGED ⟨ψ, G⟩ — FORMAL_SPEC §6.4
280                let prev_z = state.z.clone();
281                let prev_t = state.t;
282                let prev_prev_res = state.prev_res;
283                let pre_residual = self.compute_residual(&state, a);
284
285                state.z = self.diffuser.diffuse(&state.g, &state.z, self.config.diff_policy);
286                state.t = state
287                    .t
288                    .checked_add(1)
289                    .ok_or_else(|| AriaError::Backend("t overflowed u64".into()))?;
290                state.prev_res = pre_residual;
291
292                let post_residual = self.compute_residual(&state, a);
293                let report = invariants::check_all(
294                    &state,
295                    post_residual,
296                    self.config.eps,
297                    self.config.n_modes,
298                    self.config.latent_dim,
299                );
300                if self.config.strict && !report.all_ok() {
301                    if let Some(v) = invariants::violation_from_report(
302                        &report, action, state.energy(), state.energy_0,
303                        post_residual, state.prev_res, self.config.eps,
304                    ) {
305                        state.z = prev_z;
306                        state.t = prev_t;
307                        state.prev_res = prev_prev_res;
308                        return Err(AriaError::InvariantViolation(v));
309                    }
310                }
311            }
312
313            Action::Stutter => {
314                // UNCHANGED all vars — TLA stuttering (including prevRes)
315                let residual = self.compute_residual(&state, a);
316
317                let report = invariants::check_all(
318                    &state,
319                    residual,
320                    self.config.eps,
321                    self.config.n_modes,
322                    self.config.latent_dim,
323                );
324                if self.config.strict && !report.all_ok() {
325                    if let Some(v) = invariants::violation_from_report(
326                        &report, action, state.energy(), state.energy_0,
327                        residual, state.prev_res, self.config.eps,
328                    ) {
329                        return Err(AriaError::InvariantViolation(v));
330                    }
331                }
332            }
333        }
334
335        Ok(state)
336    }
337
338    /// Step one full Φ-cycle: OpticalStep → Predict → Match → Diffuse (𝐂4).
339    ///
340    /// This is the preferred schedule. Each sub-step checks invariants.
341    /// Returns the state after the full cycle, or the first invariant violation.
342    pub fn step_phi(&self, state: State, a: Condition) -> Result<State, AriaError> {
343        let s = state;
344        let s = self.apply(s, Action::OpticalStep, a)?;
345        let s = self.apply(s, Action::Predict, a)?;
346        let s = self.apply(s, Action::Match, a)?;
347        let s = self.apply(s, Action::Diffuse, a)?;
348        Ok(s)
349    }
350
351    /// Run the engine for a number of steps with a scheduler.
352    ///
353    /// Returns the final state and a trace of all steps.
354    pub fn run(
355        &self,
356        state: State,
357        scheduler: &mut Scheduler,
358        steps: u64,
359        a: Condition,
360    ) -> Result<(State, Trace), AriaError> {
361        let (state, trace, _) = self.run_monitored(state, scheduler, steps, a)?;
362        Ok((state, trace))
363    }
364
365    /// Run the engine, additionally monitoring the optional Inv5–Inv11 gates.
366    ///
367    /// The monitor is a passive observer: it sees each completed step and can
368    /// only report. Enabling a gate never changes which actions are taken, so
369    /// the set of admissible behaviors is exactly the same as for [`run`].
370    pub fn run_monitored(
371        &self,
372        mut state: State,
373        scheduler: &mut Scheduler,
374        steps: u64,
375        a: Condition,
376    ) -> Result<(State, Trace, GateReport), AriaError> {
377        let mut trace = Trace::new(self.config.n_modes, self.config.latent_dim, self.config.eps);
378        let mut monitor = GateMonitor::new(self.config.gates.clone());
379
380        for _ in 0..steps {
381            let action = scheduler.next_action_budgeted();
382            let t_before = state.t;
383
384            state = self.apply(state, action, a)?;
385
386            let residual = self.compute_residual(&state, a);
387            let energy = state.energy();
388            trace.push(
389                t_before,
390                action,
391                residual,
392                energy,
393                state.g.size(),
394                &format!("{:?}", a).to_lowercase(),
395            );
396            monitor.observe(action, &state, residual, self.config.eps);
397        }
398
399        Ok((state, trace, monitor.finish()))
400    }
401
402    /// Check all invariants on the current state without applying an action.
403    pub fn check(&self, state: &State, a: Condition) -> InvariantReport {
404        let residual = self.compute_residual(state, a);
405        invariants::check_all(state, residual, self.config.eps, self.config.n_modes, self.config.latent_dim)
406    }
407
408    /// Compute JEPA residual: Res(ψ, z, t) = d(z, P(I(ψ), a_t))
409    fn compute_residual(&self, state: &State, a: Condition) -> f64 {
410        let embedded = self.predictor.embed(&state.psi);
411        let predicted = self.predictor.predict(&embedded, a);
412        self.predictor.dist(&state.z, &predicted)
413    }
414
415    /// Access config.
416    pub fn config(&self) -> &AriaConfig {
417        &self.config
418    }
419}