1use 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
21pub const ADAPTIVE_EVAL_DISCOVERY_SEEDS: usize = 30;
23pub const ADAPTIVE_EVAL_VALIDATION_SEEDS: usize = 30;
25pub const ADAPTIVE_EVAL_HORIZON: usize = 36;
27pub const ADAPTIVE_EVAL_DISCOVERY_START_SEED: u64 = 2026_1201;
29pub const ADAPTIVE_EVAL_VALIDATION_START_SEED: u64 = 2027_1201;
31pub const ADAPTIVE_EVAL_STABLE_SAFETY_FLOOR: f64 = -0.01;
33
34const T95_DF29: f64 = 2.04523;
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
39#[serde(rename_all = "snake_case")]
40#[non_exhaustive]
41pub enum AdaptiveEvalScenario {
42 Stable,
44 RegimeShift,
46 Noisy,
48}
49
50impl AdaptiveEvalScenario {
51 pub const ALL: [Self; 3] = [Self::Stable, Self::RegimeShift, Self::Noisy];
53}
54
55#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
57#[non_exhaustive]
58pub struct AdaptiveScenarioEvalResult {
59 pub scenario: AdaptiveEvalScenario,
61 pub seeds: usize,
63 pub shadow_mean_reward: f64,
65 pub active_mean_reward: f64,
67 pub mean_reward_delta: f64,
69 pub t95_low: f64,
71 pub t95_high: f64,
73 pub shadow_proposals_per_seed: f64,
75 pub active_settled_per_seed: f64,
77 pub active_recoveries_per_seed: f64,
79}
80
81#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
83#[non_exhaustive]
84pub struct AdaptiveSeedSetEvalReport {
85 pub label: String,
87 pub start_seed: u64,
89 pub seed_count: usize,
91 pub scenarios: Vec<AdaptiveScenarioEvalResult>,
93}
94
95#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
97#[non_exhaustive]
98pub struct AdaptiveV1EvalReport {
99 pub protocol: String,
101 pub horizon: usize,
103 pub stable_safety_floor: f64,
105 pub discovery: AdaptiveSeedSetEvalReport,
107 pub validation: AdaptiveSeedSetEvalReport,
109 pub regime_shift_gain_reproduced: bool,
111 pub stable_safety_passed: bool,
113 pub overall_passed: bool,
115}
116
117struct 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 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
160fn 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 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 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
426pub 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}