Skip to main content

aria_engine_core/
gates.rs

1//! Optional operating gates Inv5–Inv11 — Phase 4, configurable, never Spec.
2//!
3//! FORMAL_SPEC §2.6 lists Inv5–Inv11 as *documentation candidates*. The primary
4//! inductive set stays Inv1–Inv4 and nothing here may enlarge it. These gates
5//! are therefore:
6//!
7//! * **off by default** — a run with no `gates` configured behaves exactly as
8//!   it did in Phase 1;
9//! * **observers, not transitions** — a monitor watches the action stream the
10//!   scheduler and engine already produce and never proposes or blocks a step;
11//! * **window properties** — several (Inv6, Inv8, Inv11) are only meaningful
12//!   over a horizon, so they are evaluated across a sliding window rather than
13//!   pointwise;
14//! * **separately reported** — a gate breach is a [`GateReport`] entry, not an
15//!   `InvViolation`. Only Inv1–4 can abort an `apply`.
16
17use serde::{Deserialize, Serialize};
18
19use crate::action::Action;
20use crate::state::State;
21
22/// One optional operating gate.
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
24pub enum Gate {
25    /// Inv5 — consecutive Stutter ≤ K (𝐂5).
26    #[serde(rename = "inv5")]
27    Inv5StutterBudget,
28    /// Inv6 — if Res > ε, a productive action follows within the window (𝐂6).
29    #[serde(rename = "inv6")]
30    Inv6ResidualProductivity,
31    /// Inv7 — the Match policy keeps the dependency spine acyclic (𝐋3).
32    #[serde(rename = "inv7")]
33    Inv7MergeAcyclicity,
34    /// Inv8 — mean residual trend ≥ −tol over the horizon (winning condition).
35    #[serde(rename = "inv8")]
36    Inv8JepaWindowTrend,
37    /// Inv9 — energy conserved under *every* Next disjunct, Stutter included.
38    #[serde(rename = "inv9")]
39    Inv9EnergyEveryAction,
40    /// Inv10 — Match implies GraphOK ∧ TypeOK (ℙ3).
41    #[serde(rename = "inv10")]
42    Inv10MatchWellTyped,
43    /// Inv11 — productive actions are not starved on a fair window.
44    #[serde(rename = "inv11")]
45    Inv11FairProductivity,
46}
47
48impl Gate {
49    pub const ALL: [Gate; 7] = [
50        Gate::Inv5StutterBudget,
51        Gate::Inv6ResidualProductivity,
52        Gate::Inv7MergeAcyclicity,
53        Gate::Inv8JepaWindowTrend,
54        Gate::Inv9EnergyEveryAction,
55        Gate::Inv10MatchWellTyped,
56        Gate::Inv11FairProductivity,
57    ];
58
59    pub fn name(&self) -> &'static str {
60        match self {
61            Gate::Inv5StutterBudget => "inv5",
62            Gate::Inv6ResidualProductivity => "inv6",
63            Gate::Inv7MergeAcyclicity => "inv7",
64            Gate::Inv8JepaWindowTrend => "inv8",
65            Gate::Inv9EnergyEveryAction => "inv9",
66            Gate::Inv10MatchWellTyped => "inv10",
67            Gate::Inv11FairProductivity => "inv11",
68        }
69    }
70
71    pub fn parse(s: &str) -> Option<Gate> {
72        match s.trim().to_lowercase().as_str() {
73            "inv5" => Some(Gate::Inv5StutterBudget),
74            "inv6" => Some(Gate::Inv6ResidualProductivity),
75            "inv7" => Some(Gate::Inv7MergeAcyclicity),
76            "inv8" => Some(Gate::Inv8JepaWindowTrend),
77            "inv9" => Some(Gate::Inv9EnergyEveryAction),
78            "inv10" => Some(Gate::Inv10MatchWellTyped),
79            "inv11" => Some(Gate::Inv11FairProductivity),
80            _ => None,
81        }
82    }
83}
84
85/// Tunables for the window-based gates.
86#[derive(Debug, Clone, Serialize, Deserialize)]
87pub struct GateConfig {
88    /// Which gates are enabled. Empty means "no gates" — the Phase 1 behavior.
89    #[serde(default)]
90    pub enabled: Vec<Gate>,
91    /// Inv5: maximum consecutive Stutters (𝐂5, default K = 2).
92    #[serde(default = "default_stutter_k")]
93    pub stutter_k: u64,
94    /// Inv6 / Inv11: window length in steps.
95    #[serde(default = "default_window")]
96    pub window: usize,
97    /// Inv8: horizon over which the residual trend is measured.
98    #[serde(default = "default_horizon")]
99    pub horizon: usize,
100    /// Inv8: allowed *relative* rise in the mean residual across the horizon.
101    ///
102    /// Inv8 detects a sustained increase, not sampling noise. Comparing the
103    /// two half-window means of a stationary residual series already swings by
104    /// ~12% at `horizon = 32`, so an absolute or very small tolerance would
105    /// fire constantly and mean nothing. The default 0.25 sits well clear of
106    /// that noise floor while still catching genuine divergence.
107    #[serde(default = "default_trend_tol")]
108    pub trend_tol: f64,
109    /// Inv9: absolute energy tolerance.
110    #[serde(default = "default_energy_tol")]
111    pub energy_tol: f64,
112}
113
114fn default_stutter_k() -> u64 {
115    2
116}
117fn default_window() -> usize {
118    8
119}
120fn default_horizon() -> usize {
121    32
122}
123fn default_trend_tol() -> f64 {
124    0.25
125}
126fn default_energy_tol() -> f64 {
127    1e-10
128}
129
130impl Default for GateConfig {
131    fn default() -> Self {
132        GateConfig {
133            enabled: Vec::new(),
134            stutter_k: default_stutter_k(),
135            window: default_window(),
136            horizon: default_horizon(),
137            trend_tol: default_trend_tol(),
138            energy_tol: default_energy_tol(),
139        }
140    }
141}
142
143impl GateConfig {
144    /// Parse a comma-separated gate list, e.g. `"inv5,inv7,inv9"` or `"all"`.
145    pub fn parse_list(s: &str) -> Result<Vec<Gate>, String> {
146        let s = s.trim();
147        if s.is_empty() || s.eq_ignore_ascii_case("none") {
148            return Ok(Vec::new());
149        }
150        if s.eq_ignore_ascii_case("all") {
151            return Ok(Gate::ALL.to_vec());
152        }
153        s.split(',')
154            .map(|part| {
155                Gate::parse(part).ok_or_else(|| format!("unknown gate '{}'", part.trim()))
156            })
157            .collect()
158    }
159
160    pub fn is_enabled(&self, g: Gate) -> bool {
161        self.enabled.contains(&g)
162    }
163}
164
165/// A single gate breach, with the step at which it was observed.
166#[derive(Debug, Clone, Serialize, Deserialize)]
167pub struct GateBreach {
168    pub gate: String,
169    pub step: u64,
170    pub detail: String,
171}
172
173/// The outcome of gate monitoring across a run.
174#[derive(Debug, Clone, Default, Serialize, Deserialize)]
175pub struct GateReport {
176    pub enabled: Vec<String>,
177    pub breaches: Vec<GateBreach>,
178}
179
180impl GateReport {
181    pub fn all_ok(&self) -> bool {
182        self.breaches.is_empty()
183    }
184}
185
186/// Watches a run and records Inv5–Inv11 breaches.
187///
188/// The monitor is fed after every `apply`; it never influences the action
189/// chosen, so enabling a gate cannot change which behaviors the engine exhibits
190/// — only which ones it reports on.
191#[derive(Debug)]
192pub struct GateMonitor {
193    config: GateConfig,
194    step: u64,
195    consecutive_stutters: u64,
196    /// Steps since the residual last exceeded ε with no productive action since.
197    hot_residual_age: Option<usize>,
198    /// Steps since the last productive action.
199    unproductive_run: usize,
200    /// Residuals over the current horizon.
201    residuals: Vec<f64>,
202    breaches: Vec<GateBreach>,
203}
204
205impl GateMonitor {
206    pub fn new(config: GateConfig) -> Self {
207        GateMonitor {
208            config,
209            step: 0,
210            consecutive_stutters: 0,
211            hot_residual_age: None,
212            unproductive_run: 0,
213            residuals: Vec::new(),
214            breaches: Vec::new(),
215        }
216    }
217
218    /// Observe one completed step.
219    // One block per operating gate Inv5–Inv11 (FORMAL_SPEC §2.6), kept in a
220    // single passive observer so no gate can be accidentally skipped.
221    #[allow(clippy::too_many_lines)]
222    pub fn observe(&mut self, action: Action, state: &State, residual: f64, eps: f64) {
223        let productive = action != Action::Stutter;
224
225        // --- Inv5: consecutive Stutter ≤ K (𝐂5) ---
226        if action == Action::Stutter {
227            self.consecutive_stutters += 1;
228        } else {
229            self.consecutive_stutters = 0;
230        }
231        if self.config.is_enabled(Gate::Inv5StutterBudget)
232            && self.consecutive_stutters > self.config.stutter_k
233        {
234            self.breach(
235                Gate::Inv5StutterBudget,
236                format!(
237                    "{} consecutive Stutters exceeds K = {}",
238                    self.consecutive_stutters, self.config.stutter_k
239                ),
240            );
241        }
242
243        // --- Inv6: a hot residual must be answered by P/M/D within the window ---
244        let answers_residual = matches!(
245            action,
246            Action::Predict | Action::Match | Action::Diffuse
247        );
248        if answers_residual {
249            self.hot_residual_age = None;
250        } else if let Some(age) = self.hot_residual_age.as_mut() {
251            *age += 1;
252        }
253        if residual > eps && self.hot_residual_age.is_none() && !answers_residual {
254            self.hot_residual_age = Some(0);
255        }
256        if self.config.is_enabled(Gate::Inv6ResidualProductivity) {
257            if let Some(age) = self.hot_residual_age {
258                if age >= self.config.window {
259                    self.breach(
260                        Gate::Inv6ResidualProductivity,
261                        format!(
262                            "Res = {residual:.6} > ε = {eps:.6} for {age} steps with no Predict/Match/Diffuse"
263                        ),
264                    );
265                    self.hot_residual_age = None;
266                }
267            }
268        }
269
270        // --- Inv7: the Match policy keeps the spine acyclic ---
271        if self.config.is_enabled(Gate::Inv7MergeAcyclicity)
272            && action == Action::Match
273            && !state.g.is_acyclic()
274        {
275            self.breach(
276                Gate::Inv7MergeAcyclicity,
277                format!("Match produced a cyclic graph (|V| = {})", state.g.node_count()),
278            );
279        }
280
281        // --- Inv8: the residual must not trend upward over the horizon ---
282        self.residuals.push(residual);
283        if self.residuals.len() > self.config.horizon {
284            self.residuals.remove(0);
285        }
286        if self.config.is_enabled(Gate::Inv8JepaWindowTrend)
287            && self.residuals.len() == self.config.horizon
288        {
289            let half = self.config.horizon / 2;
290            let early: f64 = self.residuals[..half].iter().sum::<f64>() / half as f64;
291            let late: f64 =
292                self.residuals[half..].iter().sum::<f64>() / (self.config.horizon - half) as f64;
293            // Relative rise, with an absolute floor so a near-zero early mean
294            // cannot make any late value look like an infinite increase.
295            let allowed = early * (1.0 + self.config.trend_tol) + 1e-12;
296            if late > allowed {
297                self.breach(
298                    Gate::Inv8JepaWindowTrend,
299                    format!(
300                        "mean residual rose {:.6} → {:.6} (+{:.1}%) over horizon {}, tol {:.0}%",
301                        early,
302                        late,
303                        100.0 * (late - early) / early.max(f64::MIN_POSITIVE),
304                        self.config.horizon,
305                        100.0 * self.config.trend_tol
306                    ),
307                );
308                self.residuals.clear();
309            }
310        }
311
312        // --- Inv9: energy is conserved under every disjunct, Stutter included ---
313        if self.config.is_enabled(Gate::Inv9EnergyEveryAction) {
314            let drift = (state.energy() - state.energy_0).abs();
315            if drift > self.config.energy_tol {
316                self.breach(
317                    Gate::Inv9EnergyEveryAction,
318                    format!("{action:?} drifted energy by {drift:.3e}"),
319                );
320            }
321        }
322
323        // --- Inv10: Match implies a well-typed graph (ℙ3) ---
324        if self.config.is_enabled(Gate::Inv10MatchWellTyped) && action == Action::Match {
325            let dim = state.z.len();
326            if !state.g.ok(dim) {
327                self.breach(
328                    Gate::Inv10MatchWellTyped,
329                    "Match produced a graph failing GraphOK".into(),
330                );
331            }
332        }
333
334        // --- Inv11: productive actions must not be starved ---
335        if productive {
336            self.unproductive_run = 0;
337        } else {
338            self.unproductive_run += 1;
339        }
340        if self.config.is_enabled(Gate::Inv11FairProductivity)
341            && self.unproductive_run >= self.config.window
342        {
343            self.breach(
344                Gate::Inv11FairProductivity,
345                format!(
346                    "{} consecutive non-productive steps (window {})",
347                    self.unproductive_run, self.config.window
348                ),
349            );
350            self.unproductive_run = 0;
351        }
352
353        self.step += 1;
354    }
355
356    fn breach(&mut self, gate: Gate, detail: String) {
357        self.breaches.push(GateBreach {
358            gate: gate.name().to_string(),
359            step: self.step,
360            detail,
361        });
362    }
363
364    /// Finish monitoring and produce the report.
365    pub fn finish(self) -> GateReport {
366        GateReport {
367            enabled: self.config.enabled.iter().map(|g| g.name().into()).collect(),
368            breaches: self.breaches,
369        }
370    }
371}
372
373#[cfg(test)]
374mod tests {
375    use super::*;
376    use crate::graph::{EdgeType, Graph, GraphOp, NodeId, NodeType};
377    use num_complex::Complex64;
378
379    /// Add a node with a `dim`-dimensional zero embedding.
380    ///
381    /// Deliberately committed through the op alphabet so these fixtures
382    /// exercise the same path the engine does; `emb_dim` may disagree with the
383    /// state's dim(Z) on purpose — that is what Inv10 is asked to catch.
384    fn add_test_node(g: &mut Graph, id: NodeId, emb_dim: usize) {
385        g.apply(
386            &GraphOp::AddNode {
387                id,
388                ntype: NodeType::Observation,
389                emb: vec![0.0; emb_dim],
390                ts: 0,
391            },
392            emb_dim,
393        )
394        .expect("fixture node must apply");
395    }
396
397    fn add_test_edge(g: &mut Graph, from: NodeId, to: NodeId) {
398        g.apply(
399            &GraphOp::AddEdge {
400                from,
401                to,
402                etype: EdgeType::CausallyPrecedes,
403            },
404            0,
405        )
406        .expect("fixture edge must apply");
407    }
408
409    fn state(latent_dim: usize) -> State {
410        State {
411            psi: vec![Complex64::new(1.0, 0.0)],
412            z: vec![0.0; latent_dim],
413            g: Graph::empty(),
414            t: 0,
415            prev_res: 0.0,
416            energy_0: 1.0,
417        }
418    }
419
420    fn monitor(gates: &[Gate]) -> GateMonitor {
421        GateMonitor::new(GateConfig {
422            enabled: gates.to_vec(),
423            window: 4,
424            horizon: 8,
425            ..GateConfig::default()
426        })
427    }
428
429    #[test]
430    fn no_gates_means_no_breaches() {
431        let mut m = monitor(&[]);
432        let s = state(4);
433        for _ in 0..50 {
434            m.observe(Action::Stutter, &s, 99.0, 1.0);
435        }
436        assert!(m.finish().all_ok(), "gates must be off by default");
437    }
438
439    #[test]
440    fn inv5_flags_an_over_budget_stutter_run() {
441        let mut m = monitor(&[Gate::Inv5StutterBudget]);
442        let s = state(4);
443        for _ in 0..5 {
444            m.observe(Action::Stutter, &s, 0.0, 1.0);
445        }
446        let r = m.finish();
447        assert!(!r.all_ok());
448        assert!(r.breaches.iter().all(|b| b.gate == "inv5"));
449    }
450
451    #[test]
452    fn inv5_accepts_a_bounded_stutter_run() {
453        let mut m = monitor(&[Gate::Inv5StutterBudget]);
454        let s = state(4);
455        for _ in 0..10 {
456            m.observe(Action::Stutter, &s, 0.0, 1.0);
457            m.observe(Action::Stutter, &s, 0.0, 1.0);
458            m.observe(Action::OpticalStep, &s, 0.0, 1.0);
459        }
460        assert!(m.finish().all_ok());
461    }
462
463    #[test]
464    fn inv6_flags_a_hot_residual_left_unanswered() {
465        let mut m = monitor(&[Gate::Inv6ResidualProductivity]);
466        let s = state(4);
467        for _ in 0..10 {
468            m.observe(Action::OpticalStep, &s, 5.0, 1.0);
469        }
470        let r = m.finish();
471        assert!(r.breaches.iter().any(|b| b.gate == "inv6"), "{r:?}");
472    }
473
474    #[test]
475    fn inv6_accepts_a_hot_residual_answered_by_predict() {
476        let mut m = monitor(&[Gate::Inv6ResidualProductivity]);
477        let s = state(4);
478        for _ in 0..10 {
479            m.observe(Action::OpticalStep, &s, 5.0, 1.0);
480            m.observe(Action::Predict, &s, 0.0, 1.0);
481        }
482        assert!(m.finish().all_ok());
483    }
484
485    #[test]
486    fn inv7_flags_a_cyclic_match_result() {
487        let mut m = monitor(&[Gate::Inv7MergeAcyclicity]);
488        let mut s = state(2);
489        add_test_node(&mut s.g, 1, 2);
490        add_test_node(&mut s.g, 2, 2);
491        add_test_edge(&mut s.g, 1, 2);
492        add_test_edge(&mut s.g, 2, 1);
493        m.observe(Action::Match, &s, 0.0, 1.0);
494        assert!(m.finish().breaches.iter().any(|b| b.gate == "inv7"));
495    }
496
497    #[test]
498    fn inv8_ignores_stationary_noise() {
499        let mut m = monitor(&[Gate::Inv8JepaWindowTrend]);
500        let s = state(4);
501        // ±10% oscillation around 1.0 — noise, not divergence.
502        for i in 0..200 {
503            let r = 1.0 + 0.1 * (f64::from(i) * 0.7).sin();
504            m.observe(Action::OpticalStep, &s, r, 1.0);
505        }
506        assert!(m.finish().all_ok(), "Inv8 must not fire on stationary noise");
507    }
508
509    #[test]
510    fn inv8_flags_a_diverging_residual() {
511        let mut m = monitor(&[Gate::Inv8JepaWindowTrend]);
512        let s = state(4);
513        for i in 0..64 {
514            m.observe(Action::OpticalStep, &s, 1.0 + f64::from(i), 1.0);
515        }
516        assert!(m.finish().breaches.iter().any(|b| b.gate == "inv8"));
517    }
518
519    #[test]
520    fn inv8_accepts_a_falling_residual() {
521        let mut m = monitor(&[Gate::Inv8JepaWindowTrend]);
522        let s = state(4);
523        for i in 0..64 {
524            m.observe(Action::OpticalStep, &s, 10.0 / (1.0 + f64::from(i)), 1.0);
525        }
526        assert!(m.finish().all_ok());
527    }
528
529    #[test]
530    fn inv9_flags_energy_drift() {
531        let mut m = monitor(&[Gate::Inv9EnergyEveryAction]);
532        let mut s = state(4);
533        s.energy_0 = 2.0; // ‖ψ‖ = 1 ≠ 2
534        m.observe(Action::Stutter, &s, 0.0, 1.0);
535        assert!(m.finish().breaches.iter().any(|b| b.gate == "inv9"));
536    }
537
538    #[test]
539    fn inv10_flags_a_match_to_a_bad_graph() {
540        let mut m = monitor(&[Gate::Inv10MatchWellTyped]);
541        let mut s = state(4);
542        // Embedding dimension 2 while dim(Z) = 4.
543        add_test_node(&mut s.g, 1, 2);
544        m.observe(Action::Match, &s, 0.0, 1.0);
545        assert!(m.finish().breaches.iter().any(|b| b.gate == "inv10"));
546    }
547
548    #[test]
549    fn inv11_flags_starved_productivity() {
550        let mut m = monitor(&[Gate::Inv11FairProductivity]);
551        let s = state(4);
552        for _ in 0..12 {
553            m.observe(Action::Stutter, &s, 0.0, 1.0);
554        }
555        assert!(m.finish().breaches.iter().any(|b| b.gate == "inv11"));
556    }
557
558    #[test]
559    fn parse_list_handles_names_all_and_none() {
560        assert_eq!(GateConfig::parse_list("").unwrap(), vec![]);
561        assert_eq!(GateConfig::parse_list("none").unwrap(), vec![]);
562        assert_eq!(GateConfig::parse_list("all").unwrap(), Gate::ALL.to_vec());
563        assert_eq!(
564            GateConfig::parse_list("inv5, inv9").unwrap(),
565            vec![Gate::Inv5StutterBudget, Gate::Inv9EnergyEveryAction]
566        );
567        assert!(GateConfig::parse_list("inv12").is_err());
568    }
569}