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    pub fn observe(&mut self, action: Action, state: &State, residual: f64, eps: f64) {
220        let productive = action != Action::Stutter;
221
222        // --- Inv5: consecutive Stutter ≤ K (𝐂5) ---
223        if action == Action::Stutter {
224            self.consecutive_stutters += 1;
225        } else {
226            self.consecutive_stutters = 0;
227        }
228        if self.config.is_enabled(Gate::Inv5StutterBudget)
229            && self.consecutive_stutters > self.config.stutter_k
230        {
231            self.breach(
232                Gate::Inv5StutterBudget,
233                format!(
234                    "{} consecutive Stutters exceeds K = {}",
235                    self.consecutive_stutters, self.config.stutter_k
236                ),
237            );
238        }
239
240        // --- Inv6: a hot residual must be answered by P/M/D within the window ---
241        let answers_residual = matches!(
242            action,
243            Action::Predict | Action::Match | Action::Diffuse
244        );
245        if answers_residual {
246            self.hot_residual_age = None;
247        } else if let Some(age) = self.hot_residual_age.as_mut() {
248            *age += 1;
249        }
250        if residual > eps && self.hot_residual_age.is_none() && !answers_residual {
251            self.hot_residual_age = Some(0);
252        }
253        if self.config.is_enabled(Gate::Inv6ResidualProductivity) {
254            if let Some(age) = self.hot_residual_age {
255                if age >= self.config.window {
256                    self.breach(
257                        Gate::Inv6ResidualProductivity,
258                        format!(
259                            "Res = {:.6} > ε = {:.6} for {} steps with no Predict/Match/Diffuse",
260                            residual, eps, age
261                        ),
262                    );
263                    self.hot_residual_age = None;
264                }
265            }
266        }
267
268        // --- Inv7: the Match policy keeps the spine acyclic ---
269        if self.config.is_enabled(Gate::Inv7MergeAcyclicity)
270            && action == Action::Match
271            && !state.g.is_acyclic()
272        {
273            self.breach(
274                Gate::Inv7MergeAcyclicity,
275                format!("Match produced a cyclic graph (|V| = {})", state.g.node_count()),
276            );
277        }
278
279        // --- Inv8: the residual must not trend upward over the horizon ---
280        self.residuals.push(residual);
281        if self.residuals.len() > self.config.horizon {
282            self.residuals.remove(0);
283        }
284        if self.config.is_enabled(Gate::Inv8JepaWindowTrend)
285            && self.residuals.len() == self.config.horizon
286        {
287            let half = self.config.horizon / 2;
288            let early: f64 = self.residuals[..half].iter().sum::<f64>() / half as f64;
289            let late: f64 =
290                self.residuals[half..].iter().sum::<f64>() / (self.config.horizon - half) as f64;
291            // Relative rise, with an absolute floor so a near-zero early mean
292            // cannot make any late value look like an infinite increase.
293            let allowed = early * (1.0 + self.config.trend_tol) + 1e-12;
294            if late > allowed {
295                self.breach(
296                    Gate::Inv8JepaWindowTrend,
297                    format!(
298                        "mean residual rose {:.6} → {:.6} (+{:.1}%) over horizon {}, tol {:.0}%",
299                        early,
300                        late,
301                        100.0 * (late - early) / early.max(f64::MIN_POSITIVE),
302                        self.config.horizon,
303                        100.0 * self.config.trend_tol
304                    ),
305                );
306                self.residuals.clear();
307            }
308        }
309
310        // --- Inv9: energy is conserved under every disjunct, Stutter included ---
311        if self.config.is_enabled(Gate::Inv9EnergyEveryAction) {
312            let drift = (state.energy() - state.energy_0).abs();
313            if drift > self.config.energy_tol {
314                self.breach(
315                    Gate::Inv9EnergyEveryAction,
316                    format!("{:?} drifted energy by {:.3e}", action, drift),
317                );
318            }
319        }
320
321        // --- Inv10: Match implies a well-typed graph (ℙ3) ---
322        if self.config.is_enabled(Gate::Inv10MatchWellTyped) && action == Action::Match {
323            let dim = state.z.len();
324            if !state.g.ok(dim) {
325                self.breach(
326                    Gate::Inv10MatchWellTyped,
327                    "Match produced a graph failing GraphOK".into(),
328                );
329            }
330        }
331
332        // --- Inv11: productive actions must not be starved ---
333        if productive {
334            self.unproductive_run = 0;
335        } else {
336            self.unproductive_run += 1;
337        }
338        if self.config.is_enabled(Gate::Inv11FairProductivity)
339            && self.unproductive_run >= self.config.window
340        {
341            self.breach(
342                Gate::Inv11FairProductivity,
343                format!(
344                    "{} consecutive non-productive steps (window {})",
345                    self.unproductive_run, self.config.window
346                ),
347            );
348            self.unproductive_run = 0;
349        }
350
351        self.step += 1;
352    }
353
354    fn breach(&mut self, gate: Gate, detail: String) {
355        self.breaches.push(GateBreach {
356            gate: gate.name().to_string(),
357            step: self.step,
358            detail,
359        });
360    }
361
362    /// Finish monitoring and produce the report.
363    pub fn finish(self) -> GateReport {
364        GateReport {
365            enabled: self.config.enabled.iter().map(|g| g.name().into()).collect(),
366            breaches: self.breaches,
367        }
368    }
369}
370
371#[cfg(test)]
372mod tests {
373    use super::*;
374    use crate::graph::Graph;
375    use num_complex::Complex64;
376
377    fn state(latent_dim: usize) -> State {
378        State {
379            psi: vec![Complex64::new(1.0, 0.0)],
380            z: vec![0.0; latent_dim],
381            g: Graph::empty(),
382            t: 0,
383            prev_res: 0.0,
384            energy_0: 1.0,
385        }
386    }
387
388    fn monitor(gates: &[Gate]) -> GateMonitor {
389        GateMonitor::new(GateConfig {
390            enabled: gates.to_vec(),
391            window: 4,
392            horizon: 8,
393            ..GateConfig::default()
394        })
395    }
396
397    #[test]
398    fn no_gates_means_no_breaches() {
399        let mut m = monitor(&[]);
400        let s = state(4);
401        for _ in 0..50 {
402            m.observe(Action::Stutter, &s, 99.0, 1.0);
403        }
404        assert!(m.finish().all_ok(), "gates must be off by default");
405    }
406
407    #[test]
408    fn inv5_flags_an_over_budget_stutter_run() {
409        let mut m = monitor(&[Gate::Inv5StutterBudget]);
410        let s = state(4);
411        for _ in 0..5 {
412            m.observe(Action::Stutter, &s, 0.0, 1.0);
413        }
414        let r = m.finish();
415        assert!(!r.all_ok());
416        assert!(r.breaches.iter().all(|b| b.gate == "inv5"));
417    }
418
419    #[test]
420    fn inv5_accepts_a_bounded_stutter_run() {
421        let mut m = monitor(&[Gate::Inv5StutterBudget]);
422        let s = state(4);
423        for _ in 0..10 {
424            m.observe(Action::Stutter, &s, 0.0, 1.0);
425            m.observe(Action::Stutter, &s, 0.0, 1.0);
426            m.observe(Action::OpticalStep, &s, 0.0, 1.0);
427        }
428        assert!(m.finish().all_ok());
429    }
430
431    #[test]
432    fn inv6_flags_a_hot_residual_left_unanswered() {
433        let mut m = monitor(&[Gate::Inv6ResidualProductivity]);
434        let s = state(4);
435        for _ in 0..10 {
436            m.observe(Action::OpticalStep, &s, 5.0, 1.0);
437        }
438        let r = m.finish();
439        assert!(r.breaches.iter().any(|b| b.gate == "inv6"), "{:?}", r);
440    }
441
442    #[test]
443    fn inv6_accepts_a_hot_residual_answered_by_predict() {
444        let mut m = monitor(&[Gate::Inv6ResidualProductivity]);
445        let s = state(4);
446        for _ in 0..10 {
447            m.observe(Action::OpticalStep, &s, 5.0, 1.0);
448            m.observe(Action::Predict, &s, 0.0, 1.0);
449        }
450        assert!(m.finish().all_ok());
451    }
452
453    #[test]
454    fn inv7_flags_a_cyclic_match_result() {
455        let mut m = monitor(&[Gate::Inv7MergeAcyclicity]);
456        let mut s = state(2);
457        s.g.add_node("a".into(), vec![0.0, 0.0], None);
458        s.g.add_node("b".into(), vec![0.0, 0.0], None);
459        s.g.add_edge("a".into(), "b".into(), "morph".into());
460        s.g.add_edge("b".into(), "a".into(), "morph".into());
461        m.observe(Action::Match, &s, 0.0, 1.0);
462        assert!(m.finish().breaches.iter().any(|b| b.gate == "inv7"));
463    }
464
465    #[test]
466    fn inv8_ignores_stationary_noise() {
467        let mut m = monitor(&[Gate::Inv8JepaWindowTrend]);
468        let s = state(4);
469        // ±10% oscillation around 1.0 — noise, not divergence.
470        for i in 0..200 {
471            let r = 1.0 + 0.1 * ((i as f64) * 0.7).sin();
472            m.observe(Action::OpticalStep, &s, r, 1.0);
473        }
474        assert!(m.finish().all_ok(), "Inv8 must not fire on stationary noise");
475    }
476
477    #[test]
478    fn inv8_flags_a_diverging_residual() {
479        let mut m = monitor(&[Gate::Inv8JepaWindowTrend]);
480        let s = state(4);
481        for i in 0..64 {
482            m.observe(Action::OpticalStep, &s, 1.0 + i as f64, 1.0);
483        }
484        assert!(m.finish().breaches.iter().any(|b| b.gate == "inv8"));
485    }
486
487    #[test]
488    fn inv8_accepts_a_falling_residual() {
489        let mut m = monitor(&[Gate::Inv8JepaWindowTrend]);
490        let s = state(4);
491        for i in 0..64 {
492            m.observe(Action::OpticalStep, &s, 10.0 / (1.0 + i as f64), 1.0);
493        }
494        assert!(m.finish().all_ok());
495    }
496
497    #[test]
498    fn inv9_flags_energy_drift() {
499        let mut m = monitor(&[Gate::Inv9EnergyEveryAction]);
500        let mut s = state(4);
501        s.energy_0 = 2.0; // ‖ψ‖ = 1 ≠ 2
502        m.observe(Action::Stutter, &s, 0.0, 1.0);
503        assert!(m.finish().breaches.iter().any(|b| b.gate == "inv9"));
504    }
505
506    #[test]
507    fn inv10_flags_a_match_to_a_bad_graph() {
508        let mut m = monitor(&[Gate::Inv10MatchWellTyped]);
509        let mut s = state(4);
510        // Embedding dimension 2 while dim(Z) = 4.
511        s.g.add_node("a".into(), vec![0.0, 0.0], None);
512        m.observe(Action::Match, &s, 0.0, 1.0);
513        assert!(m.finish().breaches.iter().any(|b| b.gate == "inv10"));
514    }
515
516    #[test]
517    fn inv11_flags_starved_productivity() {
518        let mut m = monitor(&[Gate::Inv11FairProductivity]);
519        let s = state(4);
520        for _ in 0..12 {
521            m.observe(Action::Stutter, &s, 0.0, 1.0);
522        }
523        assert!(m.finish().breaches.iter().any(|b| b.gate == "inv11"));
524    }
525
526    #[test]
527    fn parse_list_handles_names_all_and_none() {
528        assert_eq!(GateConfig::parse_list("").unwrap(), vec![]);
529        assert_eq!(GateConfig::parse_list("none").unwrap(), vec![]);
530        assert_eq!(GateConfig::parse_list("all").unwrap(), Gate::ALL.to_vec());
531        assert_eq!(
532            GateConfig::parse_list("inv5, inv9").unwrap(),
533            vec![Gate::Inv5StutterBudget, Gate::Inv9EnergyEveryAction]
534        );
535        assert!(GateConfig::parse_list("inv12").is_err());
536    }
537}