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, GraphOp, UndoOp};
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/// [`Engine::run_monitored_with_latents`] return type — factored out so the
23/// signature stays inside clippy's type-complexity budget.
24pub type MonitoredLatents = (State, Trace, GateReport, Vec<Vec<f64>>);
25
26/// Optical backend trait — PRD §5.3
27pub trait OpticalBackend: Debug + Send + Sync {
28    /// Apply unitary step: ψ' = U_t(ψ)
29    fn unitary_step(&self, t: u64, psi: &[num_complex::Complex64]) -> Vec<num_complex::Complex64>;
30    /// Field energy: ‖ψ‖₂ — Neumaier-compensated (spec §0.2, plan WS2).
31    ///
32    /// One shared default so every backend measures the Inv1 quantity with
33    /// the same summation; the pre-WS2 per-backend uncompensated sums are gone.
34    fn energy(&self, psi: &[num_complex::Complex64]) -> f64 {
35        crate::state::field_energy(psi)
36    }
37}
38
39/// Predictor backend trait — PRD §5.3
40pub trait Predictor: Debug + Send + Sync {
41    /// Isometry I: H → Z
42    fn embed(&self, psi: &[num_complex::Complex64]) -> Vec<f64>;
43    /// Predictor P: Z × Condition → Z
44    fn predict(&self, z: &[f64], a: Condition) -> Vec<f64>;
45    /// Distance in latent space
46    fn dist(&self, a: &[f64], b: &[f64]) -> f64;
47}
48
49/// Graph backend trait — PRD §5.3
50///
51/// # Ops, not graphs (plan WS3)
52///
53/// v0.1.0 returned a whole new `Graph`, which cost two clones of `G` per Match
54/// and made every run `O(T²)` in graph size. A backend now *proposes* the
55/// atomic ops of `ED(G ⊕ z, G*)` and the engine applies them transactionally
56/// against a snapshot journal (𝕃6), so a step costs the size of its edit, not
57/// the size of memory.
58pub trait GraphBackend: Debug + Send + Sync {
59    /// Propose the ops realizing `G' = ED(G ⊕ z, policy, G*)` at clock `t`.
60    ///
61    /// Absorbing `z` is part of Match, so the ops include it: a policy that
62    /// merges `z` into an existing node emits `MergeNodes`, one that appends
63    /// emits `AddNode`. Allocate new ids from [`Graph::next_id`].
64    fn edit_ops(
65        &self,
66        g: &Graph,
67        z: &[f64],
68        policy: MatchPolicy,
69        target: Option<&Graph>,
70        t: u64,
71    ) -> Vec<GraphOp>;
72
73    /// GraphOK check
74    fn ok(&self, g: &Graph) -> bool;
75
76    /// Mirror committed ops into auxiliary structures (e.g. a vector index).
77    ///
78    /// `g` is the **post**-state, so a merge's EMA-updated embedding is
79    /// readable. Default: nothing to mirror.
80    fn commit_ops(&self, _ops: &[GraphOp], _g: &Graph) {}
81
82    /// Mirror a rollback, so auxiliary structures never diverge from `G`.
83    ///
84    /// `journal` is the undo record that was just replayed; `g` is the restored
85    /// graph. Default: nothing to mirror.
86    fn revert_ops(&self, _journal: &[UndoOp], _g: &Graph) {}
87}
88
89/// Diffuser backend trait — PRD §5.3
90pub trait Diffuser: Debug + Send + Sync {
91    /// Diffusion step: z' = Diff_G(z)
92    fn diffuse(&self, g: &Graph, z: &[f64], policy: DiffPolicy) -> Vec<f64>;
93}
94
95/// Aria Engine — the Spec state machine with pluggable backends.
96#[derive(Debug)]
97pub struct Engine<O, P, G, D>
98where
99    O: OpticalBackend,
100    P: Predictor,
101    G: GraphBackend,
102    D: Diffuser,
103{
104    config: AriaConfig,
105    optical: O,
106    predictor: P,
107    graph_backend: G,
108    diffuser: D,
109}
110
111impl<O, P, GB, D> Engine<O, P, GB, D>
112where
113    O: OpticalBackend,
114    P: Predictor,
115    GB: GraphBackend,
116    D: Diffuser,
117{
118    /// Create a new engine with backends and config.
119    pub fn new(config: AriaConfig, optical: O, predictor: P, graph_backend: GB, diffuser: D) -> Self {
120        Engine {
121            config,
122            optical,
123            predictor,
124            graph_backend,
125            diffuser,
126        }
127    }
128
129    /// Init: create the initial state per FORMAL_SPEC §5.
130    ///
131    /// ψ = ψ₀, z = I(ψ₀), G = G₀, t = 0,
132    /// prevRes = d(I(ψ₀), P(I(ψ₀), a(0)))
133    ///
134    /// Validates shapes up front: a field of the wrong length is a config
135    /// error, not a downstream panic or a silently truncated mat-vec.
136    pub fn init(
137        &self,
138        psi0: Vec<num_complex::Complex64>,
139        g0: Graph,
140        a0: Condition,
141    ) -> Result<State, AriaError> {
142        // The 𝒮 hard bounds (spec §0.1/§0.4) gate every engine construction;
143        // the per-clause messages say exactly which bound was violated.
144        self.config.validate()?;
145        if psi0.len() != self.config.n_modes {
146            return Err(AriaError::Config(format!(
147                "ψ₀ has {} modes but config.n_modes = {}",
148                psi0.len(),
149                self.config.n_modes
150            )));
151        }
152        for (i, c) in psi0.iter().enumerate() {
153            if !c.re.is_finite() || !c.im.is_finite() {
154                return Err(AriaError::Config(format!(
155                    "ψ₀[{i}] = {c} is not finite"
156                )));
157            }
158        }
159
160        let energy_0 = self.optical.energy(&psi0);
161        let z0 = self.predictor.embed(&psi0);
162        if z0.len() != self.config.latent_dim {
163            return Err(AriaError::Config(format!(
164                "embed(ψ₀) has dim {} but config.latent_dim = {} — backend/config mismatch",
165                z0.len(),
166                self.config.latent_dim
167            )));
168        }
169        let p0 = self.predictor.predict(&z0, a0);
170        if p0.len() != self.config.latent_dim {
171            return Err(AriaError::Config(format!(
172                "P(z) has dim {} but config.latent_dim = {} — backend/config mismatch",
173                p0.len(),
174                self.config.latent_dim
175            )));
176        }
177        let prev_res = self.predictor.dist(&z0, &p0);
178
179        Ok(State {
180            psi: psi0,
181            z: z0,
182            g: g0,
183            t: 0,
184            prev_res,
185            energy_0,
186        })
187    }
188
189    /// Apply a single named action to the state.
190    ///
191    /// Returns the new state on success, or an invariant violation.
192    /// This is the Spec's Next relation turned into a deterministic function.
193    // One match arm per named action, mirroring FORMAL_SPEC §6 one-to-one;
194    // splitting the Next relation across helpers would hurt Spec readability.
195    // The Match arm is restructured in plan_v0.2.0.md WS3 (edit-ops journal).
196    #[allow(clippy::too_many_lines)]
197    pub fn apply(
198        &self,
199        mut state: State,
200        action: Action,
201        a: Condition,
202    ) -> Result<State, AriaError> {
203        match action {
204            Action::OpticalStep => {
205                // ψ' = U_t(ψ); UNCHANGED ⟨z, G, t⟩ — FORMAL_SPEC §6.1
206                let prev_psi = state.psi.clone();
207                let prev_prev_res = state.prev_res;
208                let pre_residual = self.compute_residual(&state, a);
209
210                state.psi = self.optical.unitary_step(state.t, &state.psi);
211                // TLA history obligation: prevRes' = Res(psi, z, t)
212                state.prev_res = pre_residual;
213
214                let post_residual = self.compute_residual(&state, a);
215                let report = invariants::check_all(
216                    &state,
217                    post_residual,
218                    self.config.eps,
219                    self.config.eps_energy,
220                    self.config.n_modes,
221                    self.config.latent_dim,
222                );
223                if self.config.strict && !report.all_ok() {
224                    if let Some(v) = invariants::violation_from_report(
225                        &report, action, state.energy(), state.energy_0,
226                        post_residual, state.prev_res, self.config.eps,
227                    ) {
228                        state.psi = prev_psi;
229                        state.prev_res = prev_prev_res;
230                        return Err(AriaError::InvariantViolation(v));
231                    }
232                }
233            }
234
235            Action::Predict => {
236                // z' = P(I(ψ), a_t); UNCHANGED ⟨ψ, G, t⟩ — FORMAL_SPEC §6.2
237                let prev_z = state.z.clone();
238                let prev_prev_res = state.prev_res;
239                let pre_residual = self.compute_residual(&state, a);
240
241                state.z = self.predictor.predict(&self.predictor.embed(&state.psi), a);
242                state.prev_res = pre_residual;
243
244                let post_residual = self.compute_residual(&state, a);
245                let report = invariants::check_all(
246                    &state,
247                    post_residual,
248                    self.config.eps,
249                    self.config.eps_energy,
250                    self.config.n_modes,
251                    self.config.latent_dim,
252                );
253                if self.config.strict && !report.all_ok() {
254                    if let Some(v) = invariants::violation_from_report(
255                        &report, action, state.energy(), state.energy_0,
256                        post_residual, state.prev_res, self.config.eps,
257                    ) {
258                        state.z = prev_z;
259                        state.prev_res = prev_prev_res;
260                        return Err(AriaError::InvariantViolation(v));
261                    }
262                }
263            }
264
265            Action::Match => {
266                // G' = ED(G ⊕ z, G*); UNCHANGED ⟨ψ, z, t⟩ — FORMAL_SPEC §6.3
267                //
268                // Transactional, clone-free (plan WS3): the backend proposes
269                // atomic ops, `apply_ops` commits them all-or-nothing against a
270                // snapshot journal, and any failure below replays that journal.
271                // `panic = "abort"` in release forbids unwind-based cleanup, so
272                // every rollback here is explicit data.
273                let prev_prev_res = state.prev_res;
274                let pre_residual = self.compute_residual(&state, a);
275
276                let ops = self.graph_backend.edit_ops(
277                    &state.g,
278                    &state.z,
279                    self.config.match_policy,
280                    None,
281                    state.t,
282                );
283
284                let journal = state
285                    .g
286                    .apply_ops(&ops, self.config.latent_dim)
287                    .map_err(|e| AriaError::Backend(format!("Match op refused: {e}")))?;
288
289                // Enforce max graph size — the projected size is the committed
290                // one, so an over-cap edit is rolled back rather than pre-guessed.
291                if state.g.size() > self.config.max_graph_size {
292                    let size = state.g.size();
293                    state.g.undo_ops(&journal);
294                    self.graph_backend.revert_ops(&journal, &state.g);
295                    return Err(AriaError::Schedule(format!(
296                        "graph size {} exceeds max {}",
297                        size, self.config.max_graph_size
298                    )));
299                }
300
301                self.graph_backend.commit_ops(&ops, &state.g);
302                state.prev_res = pre_residual;
303
304                let post_residual = self.compute_residual(&state, a);
305                let report = invariants::check_all(
306                    &state,
307                    post_residual,
308                    self.config.eps,
309                    self.config.eps_energy,
310                    self.config.n_modes,
311                    self.config.latent_dim,
312                );
313                if self.config.strict && !report.all_ok() {
314                    if let Some(v) = invariants::violation_from_report(
315                        &report, action, state.energy(), state.energy_0,
316                        post_residual, state.prev_res, self.config.eps,
317                    ) {
318                        state.g.undo_ops(&journal);
319                        self.graph_backend.revert_ops(&journal, &state.g);
320                        state.prev_res = prev_prev_res;
321                        return Err(AriaError::InvariantViolation(v));
322                    }
323                }
324            }
325
326            Action::Diffuse => {
327                // z' = Diff_G(z); t' = t+1; UNCHANGED ⟨ψ, G⟩ — FORMAL_SPEC §6.4
328                let prev_z = state.z.clone();
329                let prev_t = state.t;
330                let prev_prev_res = state.prev_res;
331                let pre_residual = self.compute_residual(&state, a);
332
333                state.z = self.diffuser.diffuse(&state.g, &state.z, self.config.diff_policy);
334                state.t = state
335                    .t
336                    .checked_add(1)
337                    .ok_or_else(|| AriaError::Backend("t overflowed u64".into()))?;
338                state.prev_res = pre_residual;
339
340                let post_residual = self.compute_residual(&state, a);
341                let report = invariants::check_all(
342                    &state,
343                    post_residual,
344                    self.config.eps,
345                    self.config.eps_energy,
346                    self.config.n_modes,
347                    self.config.latent_dim,
348                );
349                if self.config.strict && !report.all_ok() {
350                    if let Some(v) = invariants::violation_from_report(
351                        &report, action, state.energy(), state.energy_0,
352                        post_residual, state.prev_res, self.config.eps,
353                    ) {
354                        state.z = prev_z;
355                        state.t = prev_t;
356                        state.prev_res = prev_prev_res;
357                        return Err(AriaError::InvariantViolation(v));
358                    }
359                }
360            }
361
362            Action::Stutter => {
363                // UNCHANGED all vars — TLA stuttering (including prevRes)
364                let residual = self.compute_residual(&state, a);
365
366                let report = invariants::check_all(
367                    &state,
368                    residual,
369                    self.config.eps,
370                    self.config.eps_energy,
371                    self.config.n_modes,
372                    self.config.latent_dim,
373                );
374                if self.config.strict && !report.all_ok() {
375                    if let Some(v) = invariants::violation_from_report(
376                        &report, action, state.energy(), state.energy_0,
377                        residual, state.prev_res, self.config.eps,
378                    ) {
379                        return Err(AriaError::InvariantViolation(v));
380                    }
381                }
382            }
383        }
384
385        Ok(state)
386    }
387
388    /// Step one full Φ-cycle: OpticalStep → Predict → Match → Diffuse (𝐂4).
389    ///
390    /// This is the preferred schedule. Each sub-step checks invariants.
391    /// Returns the state after the full cycle, or the first invariant violation.
392    pub fn step_phi(&self, state: State, a: Condition) -> Result<State, AriaError> {
393        let s = state;
394        let s = self.apply(s, Action::OpticalStep, a)?;
395        let s = self.apply(s, Action::Predict, a)?;
396        let s = self.apply(s, Action::Match, a)?;
397        let s = self.apply(s, Action::Diffuse, a)?;
398        Ok(s)
399    }
400
401    /// Run the engine for a number of steps with a scheduler.
402    ///
403    /// Returns the final state and a trace of all steps.
404    pub fn run(
405        &self,
406        state: State,
407        scheduler: &mut Scheduler,
408        steps: u64,
409        a: Condition,
410    ) -> Result<(State, Trace), AriaError> {
411        let (state, trace, _) = self.run_monitored(state, scheduler, steps, a)?;
412        Ok((state, trace))
413    }
414
415    /// Run the engine, additionally monitoring the optional Inv5–Inv11 gates.
416    ///
417    /// The monitor is a passive observer: it sees each completed step and can
418    /// only report. Enabling a gate never changes which actions are taken, so
419    /// the set of admissible behaviors is exactly the same as for [`run`].
420    pub fn run_monitored(
421        &self,
422        mut state: State,
423        scheduler: &mut Scheduler,
424        steps: u64,
425        a: Condition,
426    ) -> Result<(State, Trace, GateReport), AriaError> {
427        let mut trace = Trace::new(self.config.n_modes, self.config.latent_dim, self.config.eps);
428        let mut monitor = GateMonitor::new(self.config.gates.clone());
429
430        for _ in 0..steps {
431            let action = scheduler.next_action_budgeted();
432            let t_before = state.t;
433
434            state = self.apply(state, action, a)?;
435
436            let residual = self.compute_residual(&state, a);
437            let energy = state.energy();
438            trace.push(
439                t_before,
440                action,
441                residual,
442                energy,
443                state.g.size(),
444                &format!("{a:?}").to_lowercase(),
445            );
446            monitor.observe(action, &state, residual, self.config.eps);
447        }
448
449        Ok((state, trace, monitor.finish()))
450    }
451
452    /// Same loop as [`Self::run_monitored`], plus the post-step latent `z`.
453    ///
454    /// Used by the post-hoc `aria emit` surface to recover the z-sequence of
455    /// a completed run without writing `z` into the JSONL — so the default
456    /// trace stays byte-stable and emit cannot feed anything back into Φ.
457    /// Collecting `z` is state observation, not a Φ operator.
458    pub fn run_monitored_with_latents(
459        &self,
460        mut state: State,
461        scheduler: &mut Scheduler,
462        steps: u64,
463        a: Condition,
464    ) -> Result<MonitoredLatents, AriaError> {
465        let mut trace = Trace::new(self.config.n_modes, self.config.latent_dim, self.config.eps);
466        let mut monitor = GateMonitor::new(self.config.gates.clone());
467        let mut latents = Vec::with_capacity(usize::try_from(steps).unwrap_or(0));
468
469        for _ in 0..steps {
470            let action = scheduler.next_action_budgeted();
471            let t_before = state.t;
472
473            state = self.apply(state, action, a)?;
474
475            let residual = self.compute_residual(&state, a);
476            let energy = state.energy();
477            trace.push(
478                t_before,
479                action,
480                residual,
481                energy,
482                state.g.size(),
483                &format!("{a:?}").to_lowercase(),
484            );
485            monitor.observe(action, &state, residual, self.config.eps);
486            latents.push(state.z.clone());
487        }
488
489        Ok((state, trace, monitor.finish(), latents))
490    }
491
492    /// Check all invariants on the current state without applying an action.
493    pub fn check(&self, state: &State, a: Condition) -> InvariantReport {
494        let residual = self.compute_residual(state, a);
495        invariants::check_all(state, residual, self.config.eps, self.config.eps_energy, self.config.n_modes, self.config.latent_dim)
496    }
497
498    /// JEPA residual Res(ψ, z, t) = d(z, P(I(ψ), a_t)).
499    ///
500    /// Public so the WS6 streaming verifier can audit Inv2 / X4 without
501    /// retaining a full in-memory [`crate::trace::Trace`].
502    pub fn residual(&self, state: &State, a: Condition) -> f64 {
503        self.compute_residual(state, a)
504    }
505
506    /// Compute JEPA residual: Res(ψ, z, t) = d(z, P(I(ψ), a_t))
507    fn compute_residual(&self, state: &State, a: Condition) -> f64 {
508        let embedded = self.predictor.embed(&state.psi);
509        let predicted = self.predictor.predict(&embedded, a);
510        self.predictor.dist(&state.z, &predicted)
511    }
512
513    /// Access config.
514    pub fn config(&self) -> &AriaConfig {
515        &self.config
516    }
517
518    /// Access the graph backend.
519    ///
520    /// Read-only: the backend owns policy-layer state (the metric index) whose
521    /// consistency with `G` is maintained through `commit_ops`/`revert_ops`, so
522    /// callers may inspect it but never mutate it behind the engine's back.
523    pub fn graph_backend(&self) -> &GB {
524        &self.graph_backend
525    }
526}