omega-cognitive-kernel 1.2.0

Online strategy-patch runtime: training-free RuleEffect adaptation with audit and rollback
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
//! Preregistered paired `Shadow` vs `Active` controlled evaluation harness for
//! Adaptive Kernel Protocol v1 (Phase 3).
//!
//! Uses a deterministic external service-gateway workload (controlling
//! `max_concurrency` and `retry_backoff_ms`) with isolated discovery and
//! validation seed sets, fixed horizons, and paired Student-t 95% intervals on
//! external task reward.

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,
};

/// Default number of paired discovery seeds (`df = 29`).
pub const ADAPTIVE_EVAL_DISCOVERY_SEEDS: usize = 30;
/// Default number of independent paired validation seeds (`df = 29`).
pub const ADAPTIVE_EVAL_VALIDATION_SEEDS: usize = 30;
/// Default fixed horizon (external host steps per seed per arm).
pub const ADAPTIVE_EVAL_HORIZON: usize = 36;
/// Starting seed for the preregistered discovery set.
pub const ADAPTIVE_EVAL_DISCOVERY_START_SEED: u64 = 2026_1201;
/// Starting seed for the independent validation set.
pub const ADAPTIVE_EVAL_VALIDATION_START_SEED: u64 = 2027_1201;
/// Preregistered stable-scenario lower-bound tolerance (`Active - Shadow >= -0.01`).
pub const ADAPTIVE_EVAL_STABLE_SAFETY_FLOOR: f64 = -0.01;

/// Two-sided Student-t 95% critical value for `df = 29` (`n = 30`).
const T95_DF29: f64 = 2.04523;

/// Preregistered external workload scenarios.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum AdaptiveEvalScenario {
    /// Stationary upstream capacity near baseline parameters; tests non-regression.
    Stable,
    /// Sharp upstream rate-limit drop at 1/3 horizon and partial recovery at 2/3 horizon.
    RegimeShift,
    /// High-variance transient bursts around baseline with zero sustained shift.
    Noisy,
}

impl AdaptiveEvalScenario {
    /// All three preregistered Phase 3 scenarios in canonical order.
    pub const ALL: [Self; 3] = [Self::Stable, Self::RegimeShift, Self::Noisy];
}

/// Summary statistics for a single scenario within one seed set.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct AdaptiveScenarioEvalResult {
    /// Scenario evaluated.
    pub scenario: AdaptiveEvalScenario,
    /// Number of paired seeds executed.
    pub seeds: usize,
    /// Mean external task reward under `Shadow` (host stays on baseline).
    pub shadow_mean_reward: f64,
    /// Mean external task reward under `Active` (host applies bounded snapshots).
    pub active_mean_reward: f64,
    /// Mean paired external reward delta (`Active - Shadow`).
    pub mean_reward_delta: f64,
    /// Lower bound of the paired 95% Student-t interval.
    pub t95_low: f64,
    /// Upper bound of the paired 95% Student-t interval.
    pub t95_high: f64,
    /// Mean number of shadow proposals emitted per seed (never executed).
    pub shadow_proposals_per_seed: f64,
    /// Mean number of active proposals applied & settled per seed.
    pub active_settled_per_seed: f64,
    /// Mean number of active recovery recommendations triggered per seed.
    pub active_recoveries_per_seed: f64,
}

/// Seed-set evaluation block (Discovery or Validation).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct AdaptiveSeedSetEvalReport {
    /// Label of the seed set (`discovery` or `validation`).
    pub label: String,
    /// Inclusive starting seed.
    pub start_seed: u64,
    /// Number of seeds evaluated.
    pub seed_count: usize,
    /// Results for `stable`, `regime_shift`, and `noisy`.
    pub scenarios: Vec<AdaptiveScenarioEvalResult>,
}

/// Complete reproducible Phase 3 `Shadow` vs `Active` controlled evaluation report.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct AdaptiveV1EvalReport {
    /// Protocol draft/contract identifier.
    pub protocol: String,
    /// Fixed steps per seed per arm.
    pub horizon: usize,
    /// Preregistered stable safety tolerance floor.
    pub stable_safety_floor: f64,
    /// Discovery seed-set results.
    pub discovery: AdaptiveSeedSetEvalReport,
    /// Independent validation seed-set results.
    pub validation: AdaptiveSeedSetEvalReport,
    /// Whether `regime_shift` achieved `t95_low > 0` with applied policies in both sets.
    pub regime_shift_gain_reproduced: bool,
    /// Whether `stable` satisfied `t95_low >= stable_safety_floor` in both sets.
    pub stable_safety_passed: bool,
    /// Overall preregistered acceptance verdict.
    pub overall_passed: bool,
}

/// Deterministic splitmix64 PRNG for zero-dependency reproducible paired seeds.
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)
    }

    /// Returns a deterministic value in `[-1.0, 1.0]`.
    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
    }
}

/// Evaluates external service-gateway reward and overload error at `step`.
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;

    // Overload causes nonlinear 429/timeout degradation; underuse reduces throughput linearly.
    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;
        }

        // Bounded proposal heuristic shared identically by Shadow and Active arms.
        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,
    }
}

/// Runs the preregistered Phase 3 paired `Shadow` vs `Active` controlled evaluation.
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,
    }
}