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