Skip to main content

omega_cognitive_kernel/adaptive/
eval.rs

1//! Preregistered paired `Shadow` vs `Active` controlled evaluation harness for
2//! Adaptive Kernel Protocol v1 (Phase 3).
3//!
4//! Uses a deterministic external service-gateway workload (controlling
5//! `max_concurrency` and `retry_backoff_ms`) with isolated discovery and
6//! validation seed sets, fixed horizons, and paired Student-t 95% intervals on
7//! external task reward.
8
9use alloc::collections::BTreeMap;
10use alloc::format;
11use alloc::string::{String, ToString};
12use alloc::vec::Vec;
13use serde::{Deserialize, Serialize};
14
15use crate::adaptive::state::AdaptiveStateMachine;
16use crate::adaptive::types::{
17    AdaptiveConfig, AdaptiveMode, ExecutionReceipt, FeedbackOutcome, FeedbackRequest,
18    PolicySnapshot, ProposalDecision, ProposalRequest,
19};
20
21/// Default number of paired discovery seeds (`df = 29`).
22pub const ADAPTIVE_EVAL_DISCOVERY_SEEDS: usize = 30;
23/// Default number of independent paired validation seeds (`df = 29`).
24pub const ADAPTIVE_EVAL_VALIDATION_SEEDS: usize = 30;
25/// Default fixed horizon (external host steps per seed per arm).
26pub const ADAPTIVE_EVAL_HORIZON: usize = 36;
27/// Starting seed for the preregistered discovery set.
28pub const ADAPTIVE_EVAL_DISCOVERY_START_SEED: u64 = 2026_1201;
29/// Starting seed for the independent validation set.
30pub const ADAPTIVE_EVAL_VALIDATION_START_SEED: u64 = 2027_1201;
31/// Preregistered stable-scenario lower-bound tolerance (`Active - Shadow >= -0.01`).
32pub const ADAPTIVE_EVAL_STABLE_SAFETY_FLOOR: f64 = -0.01;
33
34/// Two-sided Student-t 95% critical value for `df = 29` (`n = 30`).
35const T95_DF29: f64 = 2.04523;
36
37/// Preregistered external workload scenarios.
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
39#[serde(rename_all = "snake_case")]
40#[non_exhaustive]
41pub enum AdaptiveEvalScenario {
42    /// Stationary upstream capacity near baseline parameters; tests non-regression.
43    Stable,
44    /// Sharp upstream rate-limit drop at 1/3 horizon and partial recovery at 2/3 horizon.
45    RegimeShift,
46    /// High-variance transient bursts around baseline with zero sustained shift.
47    Noisy,
48}
49
50impl AdaptiveEvalScenario {
51    /// All three preregistered Phase 3 scenarios in canonical order.
52    pub const ALL: [Self; 3] = [Self::Stable, Self::RegimeShift, Self::Noisy];
53}
54
55/// Summary statistics for a single scenario within one seed set.
56#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
57#[non_exhaustive]
58pub struct AdaptiveScenarioEvalResult {
59    /// Scenario evaluated.
60    pub scenario: AdaptiveEvalScenario,
61    /// Number of paired seeds executed.
62    pub seeds: usize,
63    /// Mean external task reward under `Shadow` (host stays on baseline).
64    pub shadow_mean_reward: f64,
65    /// Mean external task reward under `Active` (host applies bounded snapshots).
66    pub active_mean_reward: f64,
67    /// Mean paired external reward delta (`Active - Shadow`).
68    pub mean_reward_delta: f64,
69    /// Lower bound of the paired 95% Student-t interval.
70    pub t95_low: f64,
71    /// Upper bound of the paired 95% Student-t interval.
72    pub t95_high: f64,
73    /// Mean number of shadow proposals emitted per seed (never executed).
74    pub shadow_proposals_per_seed: f64,
75    /// Mean number of active proposals applied & settled per seed.
76    pub active_settled_per_seed: f64,
77    /// Mean number of active recovery recommendations triggered per seed.
78    pub active_recoveries_per_seed: f64,
79}
80
81/// Seed-set evaluation block (Discovery or Validation).
82#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
83#[non_exhaustive]
84pub struct AdaptiveSeedSetEvalReport {
85    /// Label of the seed set (`discovery` or `validation`).
86    pub label: String,
87    /// Inclusive starting seed.
88    pub start_seed: u64,
89    /// Number of seeds evaluated.
90    pub seed_count: usize,
91    /// Results for `stable`, `regime_shift`, and `noisy`.
92    pub scenarios: Vec<AdaptiveScenarioEvalResult>,
93}
94
95/// Complete reproducible Phase 3 `Shadow` vs `Active` controlled evaluation report.
96#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
97#[non_exhaustive]
98pub struct AdaptiveV1EvalReport {
99    /// Protocol draft/contract identifier.
100    pub protocol: String,
101    /// Fixed steps per seed per arm.
102    pub horizon: usize,
103    /// Preregistered stable safety tolerance floor.
104    pub stable_safety_floor: f64,
105    /// Discovery seed-set results.
106    pub discovery: AdaptiveSeedSetEvalReport,
107    /// Independent validation seed-set results.
108    pub validation: AdaptiveSeedSetEvalReport,
109    /// Whether `regime_shift` achieved `t95_low > 0` with applied policies in both sets.
110    pub regime_shift_gain_reproduced: bool,
111    /// Whether `stable` satisfied `t95_low >= stable_safety_floor` in both sets.
112    pub stable_safety_passed: bool,
113    /// Overall preregistered acceptance verdict.
114    pub overall_passed: bool,
115}
116
117/// Deterministic splitmix64 PRNG for zero-dependency reproducible paired seeds.
118struct DeterministicRng {
119    state: u64,
120}
121
122impl DeterministicRng {
123    fn new(seed: u64) -> Self {
124        Self { state: seed }
125    }
126
127    fn next_u64(&mut self) -> u64 {
128        self.state = self.state.wrapping_add(0x9E37_79B9_7F4A_7C15);
129        let mut z = self.state;
130        z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
131        z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
132        z ^ (z >> 31)
133    }
134
135    /// Returns a deterministic value in `[-1.0, 1.0]`.
136    fn next_signed_unit(&mut self) -> f64 {
137        let bits = self.next_u64() >> 11;
138        let unit = (bits as f64) / ((1u64 << 53) as f64);
139        unit * 2.0 - 1.0
140    }
141}
142
143fn baseline_gateway_params() -> BTreeMap<String, f64> {
144    let mut map = BTreeMap::new();
145    map.insert("max_concurrency".to_string(), 4.0);
146    map.insert("retry_backoff_ms".to_string(), 200.0);
147    map
148}
149
150fn clamp(v: f64, lo: f64, hi: f64) -> f64 {
151    if v < lo {
152        lo
153    } else if v > hi {
154        hi
155    } else {
156        v
157    }
158}
159
160/// Evaluates external service-gateway reward and overload error at `step`.
161fn evaluate_gateway_step(
162    scenario: AdaptiveEvalScenario,
163    step: usize,
164    horizon: usize,
165    params: &BTreeMap<String, f64>,
166    noise: f64,
167) -> (f64, f64) {
168    let concurrency = params.get("max_concurrency").copied().unwrap_or(4.0);
169    let backoff_ms = params.get("retry_backoff_ms").copied().unwrap_or(200.0);
170
171    let (target_cap, target_backoff, burst_noise) = match scenario {
172        AdaptiveEvalScenario::Stable => (4.0, 200.0, 0.05 * noise),
173        AdaptiveEvalScenario::RegimeShift => {
174            if step < horizon / 3 {
175                (4.0, 200.0, 0.05 * noise)
176            } else if step < (2 * horizon) / 3 {
177                (2.0, 500.0, 0.06 * noise)
178            } else {
179                (3.5, 275.0, 0.05 * noise)
180            }
181        }
182        AdaptiveEvalScenario::Noisy => (4.0, 200.0, 0.25 * noise),
183    };
184
185    let overload = (concurrency - target_cap).max(0.0);
186    let underuse = (target_cap - concurrency).max(0.0);
187    let backoff_gap = libm::fabs(backoff_ms - target_backoff) / 600.0;
188
189    // Overload causes nonlinear 429/timeout degradation; underuse reduces throughput linearly.
190    let error_rate = clamp(
191        0.04 + 0.26 * overload + 0.14 * backoff_gap + burst_noise.max(0.0),
192        0.0,
193        1.0,
194    );
195    let throughput = clamp(concurrency / 4.0, 0.15, 1.0);
196    let raw_reward = clamp(
197        0.92 - 0.55 * error_rate - 0.08 * underuse + 0.04 * throughput + 0.03 * noise,
198        0.0,
199        1.0,
200    );
201    (raw_reward, error_rate)
202}
203
204struct ArmRunSummary {
205    mean_reward: f64,
206    shadow_proposals: u64,
207    active_settled: u64,
208    active_recoveries: u64,
209}
210
211fn run_single_arm(
212    scenario: AdaptiveEvalScenario,
213    mode: AdaptiveMode,
214    seed: u64,
215    horizon: usize,
216) -> ArmRunSummary {
217    let baseline = baseline_gateway_params();
218    let mut machine = AdaptiveStateMachine::new(
219        AdaptiveConfig {
220            mode,
221            ..AdaptiveConfig::default()
222        },
223        PolicySnapshot::new(0, baseline.clone()).expect("finite baseline"),
224    )
225    .expect("valid state machine");
226
227    let mut rng = DeterministicRng::new(seed);
228    let mut host_params = baseline.clone();
229    let mut total_reward = 0.0;
230    let mut shadow_proposals = 0u64;
231    let mut active_settled = 0u64;
232    let mut active_recoveries = 0u64;
233
234    let mut consecutive_high_error = 0u32;
235    let mut consecutive_low_error = 0u32;
236    let mut prev_reward = 0.85;
237
238    for step in 0..horizon {
239        let noise = rng.next_signed_unit();
240        let (reward, error_rate) =
241            evaluate_gateway_step(scenario, step, horizon, &host_params, noise);
242        total_reward += reward;
243
244        if error_rate >= 0.32 {
245            consecutive_high_error += 1;
246            consecutive_low_error = 0;
247        } else if error_rate <= 0.12 {
248            consecutive_low_error += 1;
249            consecutive_high_error = 0;
250        } else {
251            consecutive_high_error = 0;
252            consecutive_low_error = 0;
253        }
254
255        // Bounded proposal heuristic shared identically by Shadow and Active arms.
256        let candidate_opt = if consecutive_high_error >= 2 {
257            consecutive_high_error = 0;
258            let cur_c = host_params["max_concurrency"];
259            let cur_b = host_params["retry_backoff_ms"];
260            let mut next = BTreeMap::new();
261            next.insert("max_concurrency".to_string(), clamp(cur_c - 1.0, 1.0, 8.0));
262            next.insert(
263                "retry_backoff_ms".to_string(),
264                clamp(cur_b + 150.0, 50.0, 800.0),
265            );
266            Some((next, false))
267        } else if consecutive_low_error >= 3 && host_params != baseline {
268            consecutive_low_error = 0;
269            let cur_c = host_params["max_concurrency"];
270            let cur_b = host_params["retry_backoff_ms"];
271            let mut next = BTreeMap::new();
272            next.insert("max_concurrency".to_string(), clamp(cur_c + 0.5, 1.0, 8.0));
273            next.insert(
274                "retry_backoff_ms".to_string(),
275                clamp(cur_b - 75.0, 50.0, 800.0),
276            );
277            Some((next, false))
278        } else if reward + 0.15 < prev_reward && host_params != baseline {
279            if let Ok(rec) = machine.recommend_recovery(baseline.clone()) {
280                Some((rec.recovery_params, true))
281            } else {
282                None
283            }
284        } else {
285            None
286        };
287
288        if let Some((candidate_params, is_recovery)) = candidate_opt {
289            let req_id = format!("req-{seed}-{step}");
290            let prop_id = format!("prop-{seed}-{step}");
291            let digest = format!("digest-{seed}-{step}");
292            if let Ok(resp) = machine.propose(ProposalRequest {
293                request_id: req_id,
294                proposal_id: prop_id.clone(),
295                request_digest: digest,
296                requested_mode: mode,
297                candidate_params: Some(candidate_params),
298            }) {
299                match resp.decision {
300                    ProposalDecision::ShadowProposal => {
301                        shadow_proposals += 1;
302                    }
303                    ProposalDecision::ActiveProposal => {
304                        if let Some(snapshot) = resp.candidate_snapshot {
305                            host_params = snapshot.params.clone();
306                            let exec_id = format!("exec-{seed}-{step}");
307                            if machine
308                                .acknowledge_applied(ExecutionReceipt {
309                                    proposal_id: prop_id.clone(),
310                                    execution_id: exec_id.clone(),
311                                    applied_params: host_params.clone(),
312                                })
313                                .is_ok()
314                            {
315                                let (post_reward, post_err) = evaluate_gateway_step(
316                                    scenario,
317                                    step,
318                                    horizon,
319                                    &host_params,
320                                    noise,
321                                );
322                                if machine
323                                    .feedback(FeedbackRequest {
324                                        feedback_id: format!("fb-{seed}-{step}"),
325                                        proposal_id: prop_id,
326                                        execution_id: exec_id,
327                                        outcome: FeedbackOutcome::Completed {
328                                            reward: post_reward,
329                                            error_delta: post_err - error_rate,
330                                            risk_delta: 0.0,
331                                        },
332                                    })
333                                    .is_ok()
334                                {
335                                    active_settled += 1;
336                                    if is_recovery {
337                                        active_recoveries += 1;
338                                    }
339                                }
340                            }
341                        }
342                    }
343                    _ => {}
344                }
345            }
346        }
347
348        prev_reward = reward;
349    }
350
351    ArmRunSummary {
352        mean_reward: total_reward / (horizon as f64),
353        shadow_proposals,
354        active_settled,
355        active_recoveries,
356    }
357}
358
359fn evaluate_seed_set(
360    label: &str,
361    start_seed: u64,
362    seed_count: usize,
363    horizon: usize,
364) -> AdaptiveSeedSetEvalReport {
365    let mut scenarios = Vec::with_capacity(AdaptiveEvalScenario::ALL.len());
366    for scenario in AdaptiveEvalScenario::ALL {
367        let mut shadow_sum = 0.0;
368        let mut active_sum = 0.0;
369        let mut deltas = Vec::with_capacity(seed_count);
370        let mut shadow_props_sum = 0u64;
371        let mut active_settled_sum = 0u64;
372        let mut active_rec_sum = 0u64;
373
374        for offset in 0..seed_count {
375            let seed = start_seed + (offset as u64);
376            let shadow = run_single_arm(scenario, AdaptiveMode::Shadow, seed, horizon);
377            let active = run_single_arm(scenario, AdaptiveMode::Active, seed, horizon);
378
379            shadow_sum += shadow.mean_reward;
380            active_sum += active.mean_reward;
381            deltas.push(active.mean_reward - shadow.mean_reward);
382            shadow_props_sum += shadow.shadow_proposals;
383            active_settled_sum += active.active_settled;
384            active_rec_sum += active.active_recoveries;
385        }
386
387        let n = seed_count as f64;
388        let mean_delta = deltas.iter().sum::<f64>() / n;
389        let variance = if seed_count > 1 {
390            deltas
391                .iter()
392                .map(|d| {
393                    let diff = d - mean_delta;
394                    diff * diff
395                })
396                .sum::<f64>()
397                / ((seed_count - 1) as f64)
398        } else {
399            0.0
400        };
401        let se = libm::sqrt(variance / n);
402        let half_width = T95_DF29 * se;
403
404        scenarios.push(AdaptiveScenarioEvalResult {
405            scenario,
406            seeds: seed_count,
407            shadow_mean_reward: shadow_sum / n,
408            active_mean_reward: active_sum / n,
409            mean_reward_delta: mean_delta,
410            t95_low: mean_delta - half_width,
411            t95_high: mean_delta + half_width,
412            shadow_proposals_per_seed: (shadow_props_sum as f64) / n,
413            active_settled_per_seed: (active_settled_sum as f64) / n,
414            active_recoveries_per_seed: (active_rec_sum as f64) / n,
415        });
416    }
417
418    AdaptiveSeedSetEvalReport {
419        label: label.to_string(),
420        start_seed,
421        seed_count,
422        scenarios,
423    }
424}
425
426/// Runs the preregistered Phase 3 paired `Shadow` vs `Active` controlled evaluation.
427pub fn run_adaptive_v1_preregistered_eval() -> AdaptiveV1EvalReport {
428    let discovery = evaluate_seed_set(
429        "discovery",
430        ADAPTIVE_EVAL_DISCOVERY_START_SEED,
431        ADAPTIVE_EVAL_DISCOVERY_SEEDS,
432        ADAPTIVE_EVAL_HORIZON,
433    );
434    let validation = evaluate_seed_set(
435        "validation",
436        ADAPTIVE_EVAL_VALIDATION_START_SEED,
437        ADAPTIVE_EVAL_VALIDATION_SEEDS,
438        ADAPTIVE_EVAL_HORIZON,
439    );
440
441    fn find(
442        set: &AdaptiveSeedSetEvalReport,
443        sc: AdaptiveEvalScenario,
444    ) -> &AdaptiveScenarioEvalResult {
445        set.scenarios
446            .iter()
447            .find(|row| row.scenario == sc)
448            .expect("scenario present")
449    }
450
451    let disc_shift = find(&discovery, AdaptiveEvalScenario::RegimeShift);
452    let val_shift = find(&validation, AdaptiveEvalScenario::RegimeShift);
453    let regime_shift_gain_reproduced = disc_shift.t95_low > 0.0
454        && val_shift.t95_low > 0.0
455        && disc_shift.active_settled_per_seed > 0.0
456        && val_shift.active_settled_per_seed > 0.0;
457
458    let disc_stable = find(&discovery, AdaptiveEvalScenario::Stable);
459    let val_stable = find(&validation, AdaptiveEvalScenario::Stable);
460    let stable_safety_passed = disc_stable.t95_low >= ADAPTIVE_EVAL_STABLE_SAFETY_FLOOR
461        && val_stable.t95_low >= ADAPTIVE_EVAL_STABLE_SAFETY_FLOOR;
462
463    AdaptiveV1EvalReport {
464        protocol: "adaptive-v1-phase3-gateway-eval".to_string(),
465        horizon: ADAPTIVE_EVAL_HORIZON,
466        stable_safety_floor: ADAPTIVE_EVAL_STABLE_SAFETY_FLOOR,
467        discovery,
468        validation,
469        regime_shift_gain_reproduced,
470        stable_safety_passed,
471        overall_passed: regime_shift_gain_reproduced && stable_safety_passed,
472    }
473}