Skip to main content

omega_cognitive_kernel/l2/
control.rs

1//! Resident L2 safety controller, implemented with `alloc` and `libm` only.
2use crate::l2::meta_cache;
3#[allow(unused_imports)]
4use crate::prelude::*;
5use alloc::collections::BTreeMap;
6use serde::{Deserialize, Serialize};
7
8/// Constant defining expert names.
9pub const EXPERT_NAMES: [&str; 4] = ["KEEP_L0", "STABILIZE", "EXPLORE", "OBSERVE"];
10/// Constant defining keep L0.
11pub const KEEP_L0: usize = 0;
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
14#[serde(rename_all = "UPPERCASE")]
15/// Identifies a supported L2 gate state.
16pub enum L2GateState {
17    #[default]
18    /// Variant representing dormant.
19    Dormant,
20    /// Variant representing active.
21    Active,
22}
23
24#[derive(Debug, Clone, Serialize, Deserialize)]
25#[serde(default)]
26/// Data structure representing trust region.
27pub struct TrustRegion {
28    /// Alpha for this value.
29    pub alpha: f64,
30    /// Alpha maximum for this value.
31    pub alpha_max: f64,
32    /// Rise rate for this value.
33    pub rise_rate: f64,
34    /// Number of cooldown.
35    pub cooldown_steps: u32,
36    /// Cooldown remaining for this value.
37    pub cooldown_remaining: u32,
38}
39impl Default for TrustRegion {
40    fn default() -> Self {
41        Self {
42            alpha: 0.0,
43            alpha_max: 0.35,
44            rise_rate: 0.08,
45            cooldown_steps: 0,
46            cooldown_remaining: 0,
47        }
48    }
49}
50impl TrustRegion {
51    /// Performs update for this type.
52    pub fn update(&mut self, active: bool, rollback: bool, reward_delta: f64, consequence: f64) {
53        self.cooldown_remaining = self.cooldown_remaining.saturating_sub(1);
54        if rollback || reward_delta < -0.15 {
55            self.alpha = 0.0;
56            self.cooldown_remaining = self.cooldown_steps.max(2);
57        } else if !active {
58            self.alpha = 0.0;
59        } else if self.cooldown_remaining == 0 && consequence >= 0.0 {
60            self.alpha = (self.alpha + self.rise_rate).min(self.alpha_max);
61        } else if consequence < -0.05 {
62            self.alpha = 0.0;
63            self.cooldown_remaining = self.cooldown_steps;
64        }
65    }
66}
67
68#[derive(Debug, Clone, Copy)]
69/// Data structure representing control feedback.
70pub struct ControlFeedback {
71    /// Error for this value.
72    pub error: f64,
73    /// Reward for this value.
74    pub reward: f64,
75    /// Whether rollback is enabled or active.
76    pub rollback: bool,
77    /// Consequence for this value.
78    pub consequence: f64,
79    /// Kl policy for this value.
80    pub kl_policy: [f64; 2],
81}
82
83#[derive(Debug, Clone, Serialize, Deserialize)]
84#[serde(default)]
85/// Data structure representing expert aggregator.
86pub struct ExpertAggregator {
87    /// Weights for this value.
88    pub weights: [f64; 4],
89    /// Cumulative reward for this value.
90    pub cumulative_reward: [f64; 4],
91    /// Most recent probabilities.
92    pub last_probabilities: [f64; 4],
93    /// Forgetting for this value.
94    pub forgetting: f64,
95    /// Learning rate for this value.
96    pub learning_rate: f64,
97    /// Mixing for this value.
98    pub mixing: f64,
99    /// Rounds for this value.
100    pub rounds: u64,
101}
102impl Default for ExpertAggregator {
103    fn default() -> Self {
104        Self {
105            weights: [1.15, 1.0, 1.0, 1.0],
106            cumulative_reward: [0.0; 4],
107            last_probabilities: [0.25; 4],
108            forgetting: 0.97,
109            learning_rate: 0.35,
110            mixing: 0.05,
111            rounds: 0,
112        }
113    }
114}
115impl ExpertAggregator {
116    /// Performs probabilities for this type.
117    pub fn probabilities(&self) -> [f64; 4] {
118        let total: f64 = self.weights.iter().sum();
119        if !total.is_finite() || total <= 0.0 {
120            return [0.25; 4];
121        }
122        let mut p = [0.0; 4];
123        for (i, item) in p.iter_mut().enumerate() {
124            *item = 0.95 * self.weights[i] / total + self.mixing / 4.0;
125        }
126        p
127    }
128    /// Performs select for this type.
129    pub fn select(&self, surprise: f64) -> usize {
130        let p = self.probabilities();
131        // Deterministic pseudo-random draw: the complete decision is replayable.
132        let draw = libm::fabs(libm::sin(
133            (self.rounds + 1) as f64 * 12.9898 + surprise * 78.233,
134        ));
135        let mut cumulative = 0.0;
136        for (i, probability) in p.iter().enumerate() {
137            cumulative += probability;
138            if draw <= cumulative {
139                return i;
140            }
141        }
142        KEEP_L0
143    }
144    /// Inverse-propensity scoring (IPS) for the selected expert. Unselected
145    /// counterfactual rewards are not observed and therefore remain zero in
146    /// this sparse estimator: E[1{I=i} r/p_i | r_i] = r_i. Nonzero mixing gives
147    /// every expert support, while forgetting bounds the effective horizon.
148    /// Calling this standard IPS is not a claim of counterfactual observation.
149    pub fn update_ips(&mut self, expert: usize, probabilities: [f64; 4], reward: f64) {
150        if expert >= 4
151            || !probabilities.iter().all(|p| p.is_finite() && *p > 0.0)
152            || libm::fabs(probabilities.iter().sum::<f64>() - 1.0) > 1.0e-6
153        {
154            return;
155        }
156        let reward = reward.clamp(0.0, 1.0);
157        for i in 0..4 {
158            self.cumulative_reward[i] *= self.forgetting;
159            self.weights[i] = (self.weights[i] * self.forgetting + 1.0e-12).max(1.0e-12);
160        }
161        let estimate = reward / probabilities[expert].max(1.0e-6);
162        self.cumulative_reward[expert] += estimate;
163        self.weights[expert] *= libm::exp(self.learning_rate * estimate / 4.0);
164        let maximum = self.weights.iter().copied().fold(1.0e-12, f64::max);
165        for weight in &mut self.weights {
166            *weight = (*weight / maximum).max(1.0e-12);
167        }
168        self.last_probabilities = probabilities;
169        self.rounds = self.rounds.saturating_add(1);
170    }
171    /// Performs warm start for this type.
172    pub fn warm_start(&mut self, mut weights: [f64; 4]) {
173        // Never turn an untrusted or zero-valued cached weight into a zero
174        // probability: EXP3 support is required by the IPS estimator.
175        for weight in &mut weights {
176            if !weight.is_finite() {
177                *weight = 1.0e-12;
178            }
179            *weight = weight.max(1.0e-12);
180        }
181        self.weights = weights;
182        self.last_probabilities = self.probabilities();
183    }
184    /// Diagnostic discounted-Hedge envelope, in reward units, under bounded
185    /// rewards and a comparator with `switches` changes. It is not an
186    /// unconditional dynamic-regret proof for the closed-loop environment:
187    /// IPS variance, model error, and environmental feedback are additional
188    /// assumptions that cannot be inferred from a benchmark score.
189    pub fn tracking_regret_bound(&self, switches: u64) -> f64 {
190        let horizon = self.rounds.max(1) as f64;
191        let eta = self.learning_rate.max(1.0e-6);
192        let effective_horizon = 1.0 / (1.0 - self.forgetting.clamp(0.0, 0.999999));
193        libm::log(4.0) / eta
194            + effective_horizon * eta / 8.0
195            + (switches as f64 + 1.0) * (1.0 - self.forgetting) * horizon
196    }
197}
198
199#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
200#[serde(default)]
201/// Data structure representing stability certificate.
202pub struct StabilityCertificate {
203    /// Potential for this value.
204    pub potential: f64,
205    /// Predicted potential for this value.
206    pub predicted_potential: f64,
207    /// Gamma for this value.
208    pub gamma: f64,
209    /// Epsilon for this value.
210    pub epsilon: f64,
211    /// Whether lyapunov veto is enabled or active.
212    pub lyapunov_veto: bool,
213}
214impl Default for StabilityCertificate {
215    fn default() -> Self {
216        Self {
217            potential: 1.0,
218            predicted_potential: 1.0,
219            gamma: 0.05,
220            epsilon: 0.01,
221            lyapunov_veto: false,
222        }
223    }
224}
225impl StabilityCertificate {
226    /// Validates this value and reports any violated constraints.
227    pub fn check(&self, residual: f64, predicted_residual: f64) -> Self {
228        let potential = residual * residual;
229        let predicted_potential = predicted_residual * predicted_residual;
230        let veto = !potential.is_finite()
231            || !predicted_potential.is_finite()
232            || predicted_potential > (1.0 - self.gamma) * potential + self.epsilon;
233        Self {
234            potential,
235            predicted_potential,
236            lyapunov_veto: veto,
237            ..*self
238        }
239    }
240}
241
242/// Exact frozen solution of `E[R] - beta KL(pi || prior)` for two actions.
243pub fn kl_regularized_policy(rewards: [f64; 2], prior: [f64; 2], beta: f64) -> [f64; 2] {
244    if beta <= 0.0 {
245        return if rewards[1] > rewards[0] {
246            [0.0, 1.0]
247        } else {
248            [1.0, 0.0]
249        };
250    }
251    let prior = [prior[0].max(1.0e-8), prior[1].max(1.0e-8)];
252    let total = prior[0] + prior[1];
253    let scaled = [
254        rewards[0] / beta + libm::log(prior[0] / total),
255        rewards[1] / beta + libm::log(prior[1] / total),
256    ];
257    let max = scaled[0].max(scaled[1]);
258    let exp = [libm::exp(scaled[0] - max), libm::exp(scaled[1] - max)];
259    [exp[0] / (exp[0] + exp[1]), exp[1] / (exp[0] + exp[1])]
260}
261
262#[derive(Debug, Clone, Serialize, Deserialize)]
263#[serde(default)]
264/// Data structure representing resident controller.
265pub struct ResidentController {
266    /// Gate state for this value.
267    pub gate_state: L2GateState,
268    /// Normal recovery is finalized at consequence settlement. Until then
269    /// the commit snapshot remains valid for execution and feedback.
270    pub retire_requested: bool,
271    /// Whether feedback settled is enabled or active.
272    pub feedback_settled: bool,
273    /// Trust for this value.
274    pub trust: TrustRegion,
275    /// Experts for this value.
276    pub experts: ExpertAggregator,
277    /// Certificate for this value.
278    pub certificate: StabilityCertificate,
279    /// Cache for this value.
280    pub cache: meta_cache::MetaCache,
281    /// Baseline error for this value.
282    pub baseline_error: f64,
283    /// Ema error for this value.
284    pub ema_error: f64,
285    /// Ema reward for this value.
286    pub ema_reward: f64,
287    /// Baseline reward for this value.
288    pub baseline_reward: f64,
289    /// Observations for this value.
290    pub observations: u64,
291    /// Error margin for this value.
292    pub error_margin: f64,
293    /// Reward drop margin for this value.
294    pub reward_drop_margin: f64,
295    /// Rollback wakeup for this value.
296    pub rollback_wakeup: u32,
297    /// Rollback streak for this value.
298    pub rollback_streak: u32,
299    /// Calm streak for this value.
300    pub calm_streak: u32,
301    /// Calm required for this value.
302    pub calm_required: u32,
303    /// Maximum error history.
304    pub max_error_history: usize,
305    /// Collection of errors.
306    pub errors: Vec<f64>,
307    /// Collection of rewards.
308    pub rewards: Vec<f64>,
309    /// Window rollbacks for this value.
310    pub window_rollbacks: u32,
311    /// Window total for this value.
312    pub window_total: u32,
313    /// Beta maximum for this value.
314    pub beta_max: f64,
315    /// Whether meta cache hit is enabled or active.
316    pub meta_cache_hit: bool,
317    /// True only on the transition into ACTIVE, including a rollback wakeup.
318    pub surprise_started: bool,
319    /// Whether cache prepared is enabled or active.
320    pub cache_prepared: bool,
321    /// Optional cache prepared fingerprint.
322    pub cache_prepared_fingerprint: Option<meta_cache::ContextFingerprint>,
323    /// Optional surprise fingerprint.
324    pub surprise_fingerprint: Option<meta_cache::ContextFingerprint>,
325    /// Episode start residual for this value.
326    pub episode_start_residual: f64,
327    /// Whether cached this episode is enabled or active.
328    pub cached_this_episode: bool,
329    /// Entropy sum for this value.
330    pub entropy_sum: f64,
331    /// Most recent selected expert.
332    pub last_selected_expert: usize,
333    /// Most recent reward.
334    pub last_reward: f64,
335    /// Residual for this value.
336    pub residual: f64,
337    /// Residual relaxation state and its most recent frozen target. These
338    /// fields retain their v4 names for snapshot compatibility.
339    pub dayan_state: f64,
340    /// Dayan relaxation for this value.
341    pub dayan_relaxation: f64,
342    /// Residual ema for this value.
343    pub residual_ema: f64,
344    /// Previous error for this value.
345    pub previous_error: f64,
346    /// Residual slope for this value.
347    pub residual_slope: f64,
348    /// Residual control gain for this value.
349    pub residual_control_gain: f64,
350    /// Model confidence for this value.
351    pub model_confidence: f64,
352    /// Number of veto.
353    pub veto_count: u64,
354    /// Cache hits for this value.
355    pub cache_hits: u64,
356    /// Best residual for this value.
357    pub best_residual: f64,
358    /// Initial residual for this value.
359    pub initial_residual: f64,
360}
361impl Default for ResidentController {
362    fn default() -> Self {
363        Self {
364            gate_state: L2GateState::Dormant,
365            retire_requested: false,
366            feedback_settled: false,
367            trust: TrustRegion {
368                cooldown_steps: 3,
369                ..TrustRegion::default()
370            },
371            experts: ExpertAggregator::default(),
372            certificate: StabilityCertificate::default(),
373            cache: meta_cache::MetaCache::default(),
374            baseline_error: 0.0,
375            ema_error: 0.0,
376            ema_reward: 0.5,
377            baseline_reward: 0.5,
378            observations: 0,
379            error_margin: 0.04,
380            reward_drop_margin: 0.18,
381            rollback_wakeup: 2,
382            rollback_streak: 0,
383            calm_streak: 0,
384            calm_required: 3,
385            max_error_history: 16,
386            errors: Vec::new(),
387            rewards: Vec::new(),
388            window_rollbacks: 0,
389            window_total: 0,
390            beta_max: 2.0,
391            meta_cache_hit: false,
392            surprise_started: false,
393            cache_prepared: false,
394            cache_prepared_fingerprint: None,
395            surprise_fingerprint: None,
396            episode_start_residual: 1.0,
397            cached_this_episode: false,
398            entropy_sum: 0.0,
399            last_selected_expert: KEEP_L0,
400            last_reward: 0.5,
401            residual: 1.0,
402            dayan_state: 0.0,
403            dayan_relaxation: 0.35,
404            residual_ema: 1.0,
405            previous_error: 0.0,
406            residual_slope: 0.0,
407            residual_control_gain: 0.25,
408            model_confidence: 0.0,
409            veto_count: 0,
410            cache_hits: 0,
411            best_residual: 1.0,
412            initial_residual: 1.0,
413        }
414    }
415}
416impl ResidentController {
417    /// Consume exactly one outcome for the policy that acted before this call.
418    /// `executed_expert = KEEP_L0` means no intervention was applied and the
419    /// reward update uses L0's own selection propensity (IPS still works).
420    /// The policy remains noncommitted; its probabilities describe the actual
421    /// selection rather than granting a new intervention.
422    pub fn observe(&mut self, feedback: ControlFeedback, policy: crate::types::L2Policy) {
423        if self.feedback_settled {
424            return;
425        }
426        self.feedback_settled = true;
427        self.meta_cache_hit = false;
428        if !(feedback.error.is_finite()
429            && feedback.reward.is_finite()
430            && feedback.consequence.is_finite()
431            && feedback
432                .kl_policy
433                .iter()
434                .all(|p| p.is_finite() && *p >= 0.0))
435        {
436            self.retire_requested = true;
437            self.trust.alpha = 0.0;
438            self.trust.cooldown_remaining = self.trust.cooldown_steps.max(2);
439            return;
440        }
441        let error = feedback.error.clamp(0.0, 1.0);
442        if self.observations > 0 {
443            let error_delta = error - self.previous_error;
444            let target_delta = self.residual_ema - self.previous_error;
445            self.residual_slope =
446                (0.8 * self.residual_slope + 0.2 * (target_delta - error_delta)).clamp(-0.5, 0.5);
447            self.model_confidence =
448                (1.0 - libm::fabs(self.residual_slope - target_delta)).clamp(0.0, 1.0);
449        } else {
450            self.model_confidence = 1.0;
451        }
452        self.previous_error = error;
453        if self.observations == 0 {
454            self.baseline_error = error;
455            self.baseline_reward = feedback.reward;
456            self.ema_error = error;
457            self.ema_reward = feedback.reward;
458        } else {
459            self.ema_error = 0.75 * self.ema_error + 0.25 * error;
460            self.ema_reward = 0.80 * self.ema_reward + 0.20 * feedback.reward;
461            self.baseline_error = 0.98 * self.baseline_error + 0.02 * error;
462            self.baseline_reward = 0.98 * self.baseline_reward + 0.02 * feedback.reward;
463        }
464        self.observations = self.observations.saturating_add(1);
465        self.errors.push(error);
466        self.rewards.push(feedback.reward.clamp(0.0, 1.0));
467        let bounded = self.max_error_history.max(2);
468        if self.errors.len() > bounded {
469            self.errors.remove(0);
470        }
471        if self.rewards.len() > bounded {
472            self.rewards.remove(0);
473        }
474        self.window_total = self.window_total.saturating_add(1);
475        self.window_rollbacks = self
476            .window_rollbacks
477            .saturating_add(u32::from(feedback.rollback));
478        self.rollback_streak = if feedback.rollback {
479            self.rollback_streak.saturating_add(1)
480        } else {
481            0
482        };
483        let entropy = feedback
484            .kl_policy
485            .iter()
486            .filter(|p| **p > 0.0)
487            .map(|p| -p * libm::log(*p))
488            .sum::<f64>()
489            / libm::log(2.0);
490        self.entropy_sum += entropy;
491        let probabilities = policy.expert_probabilities;
492        let policy = policy.effective();
493        let expert = policy.expert;
494        self.experts
495            .update_ips(expert, probabilities, feedback.reward);
496
497        let rollback_surprise = self.rollback_streak >= self.rollback_wakeup;
498        let surprise = self.ema_error > self.baseline_error + self.error_margin
499            || self.ema_reward < self.baseline_reward - self.reward_drop_margin
500            || rollback_surprise;
501        self.surprise_started = false;
502        if surprise && self.gate_state == L2GateState::Dormant {
503            self.gate_state = L2GateState::Active;
504            self.surprise_started = true;
505            self.calm_streak = 0;
506            self.cache_prepared = false;
507            self.surprise_fingerprint = Some(self.fingerprint());
508            self.episode_start_residual = self.residual;
509            self.cached_this_episode = false;
510        }
511        self.trust.update(
512            self.gate_state == L2GateState::Active,
513            feedback.rollback,
514            feedback.reward - self.last_reward,
515            feedback.consequence,
516        );
517        self.last_reward = feedback.reward;
518        if self.gate_state == L2GateState::Active && self.observations >= 4 {
519            // A changed regime may have a new normal reward/error level. Once
520            // the actual fixed-point residual is low and stable, raw baseline
521            // offsets must not keep the controller awake forever.
522            let recovered_residual =
523                self.residual <= 0.18 && self.residual < self.episode_start_residual - 0.01;
524            // Recovery can mean either convergence from an actual perturbation
525            // or confirmation that the original alarm has subsided. Requiring
526            // a further decrease from an already tiny residual would keep a
527            // healthy controller permanently ACTIVE.
528            let calm_observation =
529                !surprise && self.residual <= 0.18 && feedback.consequence >= -0.05;
530            let recovery = !rollback_surprise && (recovered_residual || calm_observation);
531            self.calm_streak = if recovery {
532                self.calm_streak.saturating_add(1)
533            } else {
534                0
535            };
536            if recovery && !self.cached_this_episode && self.cache_prepared {
537                let fingerprint = self
538                    .surprise_fingerprint
539                    .unwrap_or_else(|| self.fingerprint());
540                self.cache.store(
541                    fingerprint,
542                    self.experts.weights,
543                    self.trust.alpha,
544                    1.0 + (self.initial_residual - self.residual).max(0.0),
545                );
546                self.cached_this_episode = true;
547            }
548            if self.calm_streak >= self.calm_required {
549                self.retire_requested = true;
550            }
551        }
552    }
553    /// Complete a normal retirement only after the acting policy's feedback
554    /// has been consumed. An unused pending commit keeps the gate snapshot
555    /// valid until the next action and its consequence have both settled.
556    pub fn finish_cycle(&mut self) {
557        if !self.feedback_settled {
558            return;
559        }
560        if self.retire_requested {
561            self.gate_state = L2GateState::Dormant;
562            self.calm_streak = 0;
563            self.trust.alpha = 0.0;
564            self.retire_requested = false;
565            self.cached_this_episode = false;
566        }
567        self.feedback_settled = false;
568        self.window_rollbacks = 0;
569        self.window_total = 0;
570        self.entropy_sum = 0.0;
571        self.meta_cache_hit = false;
572    }
573    /// Performs fingerprint for this type.
574    pub fn fingerprint(&self) -> meta_cache::ContextFingerprint {
575        meta_cache::ContextFingerprint::from_window(
576            &self.errors,
577            self.window_rollbacks,
578            self.window_total,
579            self.entropy_sum / self.window_total.max(1) as f64,
580        )
581    }
582    /// Performs prior for this type.
583    pub fn prior(&self) -> [f64; 2] {
584        match self.last_selected_expert {
585            1 => [0.90, 0.10],
586            2 => [0.10, 0.90],
587            3 => [0.65, 0.35],
588            _ => [0.5, 0.5],
589        }
590    }
591    /// Performs beta for this type.
592    pub fn beta(&self) -> f64 {
593        self.beta_for(false)
594    }
595
596    /// Return a regularization budget. Legacy controllers apply trust/confidence
597    /// here; the spectral experiment applies them once at the KL boundary.
598    pub fn beta_for(&self, spectral_weighting: bool) -> f64 {
599        if self.gate_state == L2GateState::Dormant
600            || self.last_selected_expert == KEEP_L0
601            || self.retire_requested
602        {
603            0.0
604        } else if spectral_weighting {
605            self.beta_max.max(0.0)
606        } else {
607            self.beta_max * self.trust.alpha / self.trust.alpha_max.max(1.0e-9)
608                * self.model_confidence
609        }
610    }
611    /// Predict one relaxation step from the current frozen target, then add
612    /// the declared expert's worst-case bounded disturbance. `error` is the
613    /// observation associated with the latest target; alpha only bounds
614    /// uncertainty, it is not treated as a guaranteed error reduction.
615    ///
616    /// This is a model-based one-step check, not a claim that an expert can
617    /// control the environment. For a frozen target, STABILIZE (which makes no
618    /// additional perturbation in this model) recovers exactly the contraction
619    /// `r+ = (1 - lambda) r`; EXPLORE/OBSERVE pay a transparent risk budget.
620    pub fn predicted_residual(&self, error: f64, alpha: f64, expert: usize) -> f64 {
621        let disturbance = match expert {
622            1 => 0.0,
623            2 => libm::fabs(self.residual_control_gain),
624            3 => 0.35 * libm::fabs(self.residual_control_gain),
625            _ => return f64::INFINITY,
626        };
627        if !error.is_finite() {
628            return f64::INFINITY;
629        }
630        let lambda = self.dayan_relaxation.clamp(0.01, 1.0);
631        let innovation =
632            (libm::fabs(self.residual_slope) + libm::fabs(self.ema_error - error)).clamp(0.0, 1.0);
633        let disturbance_term = 0.2 * lambda * innovation + alpha.clamp(0.0, 1.0) * disturbance;
634        let predicted = (1.0 - lambda) * self.residual + disturbance_term;
635        if predicted.is_finite() {
636            predicted
637        } else {
638            f64::INFINITY
639        }
640    }
641    /// One explicit fixed-point iteration on the residual:
642    /// `r+ = (1-lambda) r + lambda |target - previous_target|`.
643    /// The latest observation supplies the omega=dayan target. For a frozen
644    /// target and 0 < lambda <= 1 this is a contraction, hence V=r^2 decreases
645    /// by (1-lambda)^2. On a regime change the target may move, which is why a
646    /// separate single-step Lyapunov certificate guards every commit.
647    pub fn update_dayan(&mut self, target_alignment: f64) -> f64 {
648        let target = target_alignment.clamp(0.0, 1.0);
649        if self.observations == 0 {
650            self.residual_ema = target;
651            self.initial_residual = 1.0;
652            self.best_residual = 1.0;
653        }
654        let lambda = self.dayan_relaxation.clamp(0.01, 1.0);
655        self.dayan_state =
656            (1.0 - lambda) * self.dayan_state + lambda * libm::fabs(target - self.residual_ema);
657        self.dayan_state = self.dayan_state.clamp(0.0, 1.0);
658        self.residual = self.dayan_state;
659        self.residual_ema = target;
660        self.best_residual = self.best_residual.min(self.residual);
661        self.residual
662    }
663    /// Performs expert weights for this type.
664    pub fn expert_weights(&self) -> BTreeMap<String, f64> {
665        let p = self.experts.probabilities();
666        let mut result = BTreeMap::new();
667        for (name, probability) in EXPERT_NAMES.iter().zip(p) {
668            result.insert((*name).into(), probability);
669        }
670        result
671    }
672}
673
674#[cfg(test)]
675mod tests {
676    use super::*;
677    use crate::types::L2Policy;
678
679    #[test]
680    fn trust_is_zero_outside_active_and_resets_on_rollback() {
681        let mut trust = TrustRegion::default();
682        trust.update(false, false, 0.0, 1.0);
683        assert_eq!(trust.alpha, 0.0);
684        trust.update(true, false, 0.0, 1.0);
685        assert!(trust.alpha > 0.0);
686        trust.update(true, true, 0.0, 1.0);
687        assert_eq!(trust.alpha, 0.0);
688        assert!(trust.cooldown_remaining > 0);
689    }
690
691    #[test]
692    fn ips_uses_logged_propensity_and_supports_every_expert() {
693        let mut experts = ExpertAggregator::default();
694        let probabilities = experts.probabilities();
695        let before = experts.cumulative_reward[2];
696        experts.update_ips(2, probabilities, 0.5);
697        assert!((experts.cumulative_reward[2] - 0.5 / probabilities[2]).abs() < 1e-10);
698        assert!(experts.probabilities().iter().all(|p| *p > 0.0));
699        assert!(experts.tracking_regret_bound(2).is_finite());
700        assert_eq!(before, 0.0);
701    }
702
703    #[test]
704    fn lyapunov_vetoes_an_increasing_prediction() {
705        let certificate = StabilityCertificate::default();
706        assert!(certificate.check(0.5, 0.7).lyapunov_veto);
707        assert!(!certificate.check(0.5, 0.4).lyapunov_veto);
708    }
709
710    #[test]
711    fn kl_policy_matches_closed_form_and_zero_beta_is_greedy() {
712        let policy = kl_regularized_policy([0.2, 0.8], [0.8, 0.2], 0.5);
713        let total = 0.8 * libm::exp(0.2 / 0.5) + 0.2 * libm::exp(0.8 / 0.5);
714        assert!((policy[0] - 0.8 * libm::exp(0.2 / 0.5) / total).abs() < 1e-12);
715        assert!((policy.iter().sum::<f64>() - 1.0).abs() < 1e-12);
716        assert_eq!(
717            kl_regularized_policy([0.2, 0.8], [1.0, 0.0], 0.0),
718            [0.0, 1.0]
719        );
720    }
721
722    #[test]
723    fn malformed_feedback_fails_closed_without_learning() {
724        let mut controller = ResidentController {
725            gate_state: L2GateState::Active,
726            trust: TrustRegion {
727                alpha: 0.2,
728                ..TrustRegion::default()
729            },
730            ..ResidentController::default()
731        };
732        controller.observe(
733            ControlFeedback {
734                error: f64::NAN,
735                reward: 1.0,
736                rollback: false,
737                consequence: 0.0,
738                kl_policy: [0.5, 0.5],
739            },
740            L2Policy::default(),
741        );
742        assert_eq!(controller.observations, 0);
743        assert_eq!(controller.experts.rounds, 0);
744        assert_eq!(controller.trust.alpha, 0.0);
745        assert!(controller.retire_requested);
746        controller.finish_cycle();
747        assert_eq!(controller.gate_state, L2GateState::Dormant);
748    }
749
750    #[test]
751    fn prediction_contracts_without_disturbance_and_charges_expert_risk() {
752        let controller = ResidentController {
753            residual: 0.4,
754            dayan_state: 0.4,
755            residual_ema: 0.6,
756            ema_error: 0.2,
757            ..ResidentController::default()
758        };
759        let predicted = controller.predicted_residual(0.2, 0.2, 1);
760        assert!((predicted - 0.65 * 0.4).abs() < 1e-12);
761        assert!(!controller.certificate.check(0.4, predicted).lyapunov_veto);
762        let risky = controller.predicted_residual(0.2, 1.0, 2);
763        assert!(risky > predicted);
764        assert!(controller.certificate.check(0.4, risky).lyapunov_veto);
765        assert!(controller
766            .predicted_residual(0.2, 0.2, KEEP_L0)
767            .is_infinite());
768    }
769
770    #[test]
771    fn retirement_waits_for_feedback_settlement() {
772        let mut controller = ResidentController {
773            gate_state: L2GateState::Active,
774            retire_requested: true,
775            trust: TrustRegion {
776                alpha: 0.2,
777                ..TrustRegion::default()
778            },
779            ..ResidentController::default()
780        };
781        controller.finish_cycle();
782        assert_eq!(controller.gate_state, L2GateState::Active);
783        assert!(controller.retire_requested);
784        controller.feedback_settled = true;
785        controller.finish_cycle();
786        assert_eq!(controller.gate_state, L2GateState::Dormant);
787        assert!(!controller.retire_requested);
788        assert_eq!(controller.trust.alpha, 0.0);
789    }
790
791    #[test]
792    fn keep_l0_feedback_uses_actual_selection_propensity() {
793        let mut controller = ResidentController::default();
794        let probabilities = [0.4, 0.3, 0.2, 0.1];
795        controller.experts.last_probabilities = probabilities;
796        let before = controller.experts.cumulative_reward;
797        controller.observe(
798            ControlFeedback {
799                error: 0.2,
800                reward: 0.5,
801                rollback: false,
802                consequence: 0.0,
803                kl_policy: [1.0, 0.0],
804            },
805            L2Policy {
806                expert_probabilities: probabilities,
807                ..L2Policy::default()
808            },
809        );
810        assert!((controller.experts.cumulative_reward[0] - before[0] - 0.5 / 0.4).abs() < 1e-10);
811        assert_eq!(controller.experts.last_probabilities, probabilities);
812    }
813
814    #[test]
815    fn repeated_feedback_is_idempotent() {
816        let mut controller = ResidentController::default();
817        let feedback = ControlFeedback {
818            error: 0.4,
819            reward: 0.8,
820            rollback: false,
821            consequence: 0.1,
822            kl_policy: [0.8, 0.2],
823        };
824        controller.observe(feedback, L2Policy::default());
825        let observations = controller.observations;
826        let rounds = controller.experts.rounds;
827        let ema = controller.ema_error;
828        controller.observe(feedback, L2Policy::default());
829        assert_eq!(controller.observations, observations);
830        assert_eq!(controller.experts.rounds, rounds);
831        assert_eq!(controller.ema_error, ema);
832    }
833
834    #[test]
835    fn fixed_point_residual_contracts_for_frozen_target() {
836        let mut controller = ResidentController {
837            residual: 0.8,
838            dayan_state: 0.8,
839            residual_ema: 0.8,
840            ..ResidentController::default()
841        };
842        let mut previous = f64::INFINITY;
843        for step in 0..8 {
844            let residual = controller.update_dayan(0.8);
845            assert!(
846                residual < previous,
847                "step={step} residual={residual} previous={previous} state={} target={} lambda={}",
848                controller.dayan_state,
849                controller.residual_ema,
850                controller.dayan_relaxation,
851            );
852            controller.observe(
853                ControlFeedback {
854                    error: 0.1,
855                    reward: 1.0,
856                    rollback: false,
857                    consequence: 0.1,
858                    kl_policy: [1.0, 0.0],
859                },
860                L2Policy::default(),
861            );
862            controller.finish_cycle();
863            previous = residual;
864        }
865        assert!(previous < 0.03);
866    }
867
868    #[test]
869    fn gate_wakes_on_error_and_returns_to_dormant_after_recovery() {
870        fn feedback(error: f64, reward: f64) -> ControlFeedback {
871            ControlFeedback {
872                error,
873                reward,
874                rollback: false,
875                consequence: 0.0,
876                kl_policy: [1.0, 0.0],
877            }
878        }
879        let mut controller = ResidentController::default();
880        let policy = L2Policy::default();
881        for _ in 0..5 {
882            controller.observe(feedback(0.1, 1.0), policy);
883            controller.finish_cycle();
884            controller.residual = 0.3;
885            controller.episode_start_residual = 0.6;
886        }
887        controller.observe(feedback(0.9, 0.0), policy);
888        assert_eq!(controller.gate_state, L2GateState::Active);
889        assert!(controller.surprise_started);
890        controller.residual = 0.6;
891        controller.episode_start_residual = 0.6;
892        for _ in 0..=controller.calm_required {
893            controller.residual = 0.1;
894            controller.observe(feedback(0.1, 1.0), policy);
895            controller.finish_cycle();
896        }
897        // A new request must not be finalized before the acting policy's own
898        // feedback has settled. In this loop the previous request was already
899        // consumed; the next recovery observation starts a fresh cycle.
900        assert!(controller.retire_requested || controller.gate_state == L2GateState::Dormant);
901        controller.finish_cycle();
902        assert_eq!(
903            controller.gate_state,
904            L2GateState::Dormant,
905            "ema={} baseline={} reward={} reward_base={} residual={} calm={}",
906            controller.ema_error,
907            controller.baseline_error,
908            controller.ema_reward,
909            controller.baseline_reward,
910            controller.residual,
911            controller.calm_streak
912        );
913        assert_eq!(controller.trust.alpha, 0.0);
914    }
915}