use alloc::collections::BTreeMap;
use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use serde::{Deserialize, Serialize};
use crate::adaptive::state::AdaptiveStateMachine;
use crate::adaptive::types::{
AdaptiveConfig, AdaptiveMode, ExecutionReceipt, FeedbackOutcome, FeedbackRequest,
PolicySnapshot, ProposalDecision, ProposalRequest,
};
pub const ADAPTIVE_EVAL_DISCOVERY_SEEDS: usize = 30;
pub const ADAPTIVE_EVAL_VALIDATION_SEEDS: usize = 30;
pub const ADAPTIVE_EVAL_HORIZON: usize = 36;
pub const ADAPTIVE_EVAL_DISCOVERY_START_SEED: u64 = 2026_1201;
pub const ADAPTIVE_EVAL_VALIDATION_START_SEED: u64 = 2027_1201;
pub const ADAPTIVE_EVAL_STABLE_SAFETY_FLOOR: f64 = -0.01;
const T95_DF29: f64 = 2.04523;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum AdaptiveEvalScenario {
Stable,
RegimeShift,
Noisy,
}
impl AdaptiveEvalScenario {
pub const ALL: [Self; 3] = [Self::Stable, Self::RegimeShift, Self::Noisy];
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct AdaptiveScenarioEvalResult {
pub scenario: AdaptiveEvalScenario,
pub seeds: usize,
pub shadow_mean_reward: f64,
pub active_mean_reward: f64,
pub mean_reward_delta: f64,
pub t95_low: f64,
pub t95_high: f64,
pub shadow_proposals_per_seed: f64,
pub active_settled_per_seed: f64,
pub active_recoveries_per_seed: f64,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct AdaptiveSeedSetEvalReport {
pub label: String,
pub start_seed: u64,
pub seed_count: usize,
pub scenarios: Vec<AdaptiveScenarioEvalResult>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct AdaptiveV1EvalReport {
pub protocol: String,
pub horizon: usize,
pub stable_safety_floor: f64,
pub discovery: AdaptiveSeedSetEvalReport,
pub validation: AdaptiveSeedSetEvalReport,
pub regime_shift_gain_reproduced: bool,
pub stable_safety_passed: bool,
pub overall_passed: bool,
}
struct DeterministicRng {
state: u64,
}
impl DeterministicRng {
fn new(seed: u64) -> Self {
Self { state: seed }
}
fn next_u64(&mut self) -> u64 {
self.state = self.state.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = self.state;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^ (z >> 31)
}
fn next_signed_unit(&mut self) -> f64 {
let bits = self.next_u64() >> 11;
let unit = (bits as f64) / ((1u64 << 53) as f64);
unit * 2.0 - 1.0
}
}
fn baseline_gateway_params() -> BTreeMap<String, f64> {
let mut map = BTreeMap::new();
map.insert("max_concurrency".to_string(), 4.0);
map.insert("retry_backoff_ms".to_string(), 200.0);
map
}
fn clamp(v: f64, lo: f64, hi: f64) -> f64 {
if v < lo {
lo
} else if v > hi {
hi
} else {
v
}
}
fn evaluate_gateway_step(
scenario: AdaptiveEvalScenario,
step: usize,
horizon: usize,
params: &BTreeMap<String, f64>,
noise: f64,
) -> (f64, f64) {
let concurrency = params.get("max_concurrency").copied().unwrap_or(4.0);
let backoff_ms = params.get("retry_backoff_ms").copied().unwrap_or(200.0);
let (target_cap, target_backoff, burst_noise) = match scenario {
AdaptiveEvalScenario::Stable => (4.0, 200.0, 0.05 * noise),
AdaptiveEvalScenario::RegimeShift => {
if step < horizon / 3 {
(4.0, 200.0, 0.05 * noise)
} else if step < (2 * horizon) / 3 {
(2.0, 500.0, 0.06 * noise)
} else {
(3.5, 275.0, 0.05 * noise)
}
}
AdaptiveEvalScenario::Noisy => (4.0, 200.0, 0.25 * noise),
};
let overload = (concurrency - target_cap).max(0.0);
let underuse = (target_cap - concurrency).max(0.0);
let backoff_gap = libm::fabs(backoff_ms - target_backoff) / 600.0;
let error_rate = clamp(
0.04 + 0.26 * overload + 0.14 * backoff_gap + burst_noise.max(0.0),
0.0,
1.0,
);
let throughput = clamp(concurrency / 4.0, 0.15, 1.0);
let raw_reward = clamp(
0.92 - 0.55 * error_rate - 0.08 * underuse + 0.04 * throughput + 0.03 * noise,
0.0,
1.0,
);
(raw_reward, error_rate)
}
struct ArmRunSummary {
mean_reward: f64,
shadow_proposals: u64,
active_settled: u64,
active_recoveries: u64,
}
fn run_single_arm(
scenario: AdaptiveEvalScenario,
mode: AdaptiveMode,
seed: u64,
horizon: usize,
) -> ArmRunSummary {
let baseline = baseline_gateway_params();
let mut machine = AdaptiveStateMachine::new(
AdaptiveConfig {
mode,
..AdaptiveConfig::default()
},
PolicySnapshot::new(0, baseline.clone()).expect("finite baseline"),
)
.expect("valid state machine");
let mut rng = DeterministicRng::new(seed);
let mut host_params = baseline.clone();
let mut total_reward = 0.0;
let mut shadow_proposals = 0u64;
let mut active_settled = 0u64;
let mut active_recoveries = 0u64;
let mut consecutive_high_error = 0u32;
let mut consecutive_low_error = 0u32;
let mut prev_reward = 0.85;
for step in 0..horizon {
let noise = rng.next_signed_unit();
let (reward, error_rate) =
evaluate_gateway_step(scenario, step, horizon, &host_params, noise);
total_reward += reward;
if error_rate >= 0.32 {
consecutive_high_error += 1;
consecutive_low_error = 0;
} else if error_rate <= 0.12 {
consecutive_low_error += 1;
consecutive_high_error = 0;
} else {
consecutive_high_error = 0;
consecutive_low_error = 0;
}
let candidate_opt = if consecutive_high_error >= 2 {
consecutive_high_error = 0;
let cur_c = host_params["max_concurrency"];
let cur_b = host_params["retry_backoff_ms"];
let mut next = BTreeMap::new();
next.insert("max_concurrency".to_string(), clamp(cur_c - 1.0, 1.0, 8.0));
next.insert(
"retry_backoff_ms".to_string(),
clamp(cur_b + 150.0, 50.0, 800.0),
);
Some((next, false))
} else if consecutive_low_error >= 3 && host_params != baseline {
consecutive_low_error = 0;
let cur_c = host_params["max_concurrency"];
let cur_b = host_params["retry_backoff_ms"];
let mut next = BTreeMap::new();
next.insert("max_concurrency".to_string(), clamp(cur_c + 0.5, 1.0, 8.0));
next.insert(
"retry_backoff_ms".to_string(),
clamp(cur_b - 75.0, 50.0, 800.0),
);
Some((next, false))
} else if reward + 0.15 < prev_reward && host_params != baseline {
if let Ok(rec) = machine.recommend_recovery(baseline.clone()) {
Some((rec.recovery_params, true))
} else {
None
}
} else {
None
};
if let Some((candidate_params, is_recovery)) = candidate_opt {
let req_id = format!("req-{seed}-{step}");
let prop_id = format!("prop-{seed}-{step}");
let digest = format!("digest-{seed}-{step}");
if let Ok(resp) = machine.propose(ProposalRequest {
request_id: req_id,
proposal_id: prop_id.clone(),
request_digest: digest,
requested_mode: mode,
candidate_params: Some(candidate_params),
}) {
match resp.decision {
ProposalDecision::ShadowProposal => {
shadow_proposals += 1;
}
ProposalDecision::ActiveProposal => {
if let Some(snapshot) = resp.candidate_snapshot {
host_params = snapshot.params.clone();
let exec_id = format!("exec-{seed}-{step}");
if machine
.acknowledge_applied(ExecutionReceipt {
proposal_id: prop_id.clone(),
execution_id: exec_id.clone(),
applied_params: host_params.clone(),
})
.is_ok()
{
let (post_reward, post_err) = evaluate_gateway_step(
scenario,
step,
horizon,
&host_params,
noise,
);
if machine
.feedback(FeedbackRequest {
feedback_id: format!("fb-{seed}-{step}"),
proposal_id: prop_id,
execution_id: exec_id,
outcome: FeedbackOutcome::Completed {
reward: post_reward,
error_delta: post_err - error_rate,
risk_delta: 0.0,
},
})
.is_ok()
{
active_settled += 1;
if is_recovery {
active_recoveries += 1;
}
}
}
}
}
_ => {}
}
}
}
prev_reward = reward;
}
ArmRunSummary {
mean_reward: total_reward / (horizon as f64),
shadow_proposals,
active_settled,
active_recoveries,
}
}
fn evaluate_seed_set(
label: &str,
start_seed: u64,
seed_count: usize,
horizon: usize,
) -> AdaptiveSeedSetEvalReport {
let mut scenarios = Vec::with_capacity(AdaptiveEvalScenario::ALL.len());
for scenario in AdaptiveEvalScenario::ALL {
let mut shadow_sum = 0.0;
let mut active_sum = 0.0;
let mut deltas = Vec::with_capacity(seed_count);
let mut shadow_props_sum = 0u64;
let mut active_settled_sum = 0u64;
let mut active_rec_sum = 0u64;
for offset in 0..seed_count {
let seed = start_seed + (offset as u64);
let shadow = run_single_arm(scenario, AdaptiveMode::Shadow, seed, horizon);
let active = run_single_arm(scenario, AdaptiveMode::Active, seed, horizon);
shadow_sum += shadow.mean_reward;
active_sum += active.mean_reward;
deltas.push(active.mean_reward - shadow.mean_reward);
shadow_props_sum += shadow.shadow_proposals;
active_settled_sum += active.active_settled;
active_rec_sum += active.active_recoveries;
}
let n = seed_count as f64;
let mean_delta = deltas.iter().sum::<f64>() / n;
let variance = if seed_count > 1 {
deltas
.iter()
.map(|d| {
let diff = d - mean_delta;
diff * diff
})
.sum::<f64>()
/ ((seed_count - 1) as f64)
} else {
0.0
};
let se = libm::sqrt(variance / n);
let half_width = T95_DF29 * se;
scenarios.push(AdaptiveScenarioEvalResult {
scenario,
seeds: seed_count,
shadow_mean_reward: shadow_sum / n,
active_mean_reward: active_sum / n,
mean_reward_delta: mean_delta,
t95_low: mean_delta - half_width,
t95_high: mean_delta + half_width,
shadow_proposals_per_seed: (shadow_props_sum as f64) / n,
active_settled_per_seed: (active_settled_sum as f64) / n,
active_recoveries_per_seed: (active_rec_sum as f64) / n,
});
}
AdaptiveSeedSetEvalReport {
label: label.to_string(),
start_seed,
seed_count,
scenarios,
}
}
pub fn run_adaptive_v1_preregistered_eval() -> AdaptiveV1EvalReport {
let discovery = evaluate_seed_set(
"discovery",
ADAPTIVE_EVAL_DISCOVERY_START_SEED,
ADAPTIVE_EVAL_DISCOVERY_SEEDS,
ADAPTIVE_EVAL_HORIZON,
);
let validation = evaluate_seed_set(
"validation",
ADAPTIVE_EVAL_VALIDATION_START_SEED,
ADAPTIVE_EVAL_VALIDATION_SEEDS,
ADAPTIVE_EVAL_HORIZON,
);
fn find(
set: &AdaptiveSeedSetEvalReport,
sc: AdaptiveEvalScenario,
) -> &AdaptiveScenarioEvalResult {
set.scenarios
.iter()
.find(|row| row.scenario == sc)
.expect("scenario present")
}
let disc_shift = find(&discovery, AdaptiveEvalScenario::RegimeShift);
let val_shift = find(&validation, AdaptiveEvalScenario::RegimeShift);
let regime_shift_gain_reproduced = disc_shift.t95_low > 0.0
&& val_shift.t95_low > 0.0
&& disc_shift.active_settled_per_seed > 0.0
&& val_shift.active_settled_per_seed > 0.0;
let disc_stable = find(&discovery, AdaptiveEvalScenario::Stable);
let val_stable = find(&validation, AdaptiveEvalScenario::Stable);
let stable_safety_passed = disc_stable.t95_low >= ADAPTIVE_EVAL_STABLE_SAFETY_FLOOR
&& val_stable.t95_low >= ADAPTIVE_EVAL_STABLE_SAFETY_FLOOR;
AdaptiveV1EvalReport {
protocol: "adaptive-v1-phase3-gateway-eval".to_string(),
horizon: ADAPTIVE_EVAL_HORIZON,
stable_safety_floor: ADAPTIVE_EVAL_STABLE_SAFETY_FLOOR,
discovery,
validation,
regime_shift_gain_reproduced,
stable_safety_passed,
overall_passed: regime_shift_gain_reproduced && stable_safety_passed,
}
}