omega_cognitive_kernel/task/types.rs
1//! Data types, report structs, and constants for bandit and L2 benchmark tasks.
2
3use alloc::collections::BTreeMap;
4use serde::{Serialize, Serializer};
5
6fn serialize_score_breakdown<S>(
7 values: &BTreeMap<String, f64>,
8 serializer: S,
9) -> core::result::Result<S::Ok, S::Error>
10where
11 S: Serializer,
12{
13 let mut entries: Vec<_> = values.iter().collect();
14 entries.sort_unstable_by_key(|(key, _)| *key);
15 serializer.collect_map(entries)
16}
17
18#[derive(Debug, Clone, Default, Serialize)]
19/// Data structure representing L2 expert metrics.
20pub struct L2ExpertMetrics {
21 /// Committed for this value.
22 pub committed: u64,
23 /// Applied for this value.
24 pub applied: u64,
25 /// Not applied for this value.
26 pub not_applied: u64,
27 /// Reward sum for this value.
28 pub reward_sum: f64,
29}
30
31#[derive(Debug, Clone, Default, Serialize)]
32/// Data structure representing L2 pipeline diagnostics.
33pub struct L2PipelineDiagnostics {
34 /// Observations for this value.
35 pub observations: u64,
36 /// Spectral active for this value.
37 pub spectral_active: u64,
38 /// Proposals for this value.
39 pub proposals: u64,
40 /// Dry runs for this value.
41 pub dry_runs: u64,
42 /// Candidate arm changed relative to KEEP_L0 on the same pre-action snapshot.
43 pub candidate_changes: u64,
44 /// Selected arm changed relative to KEEP_L0 on that same snapshot.
45 pub selected_changes: u64,
46 /// Counterfactual changed candidate but L0 safety/hysteresis held the arm.
47 pub candidate_changes_not_selected: u64,
48 /// History discounts for this value.
49 pub history_discounts: u64,
50 /// Spectral rejections for this value.
51 pub spectral_rejections: u64,
52 /// Lyapunov rejections for this value.
53 pub lyapunov_rejections: u64,
54 /// Cooldown rejections for this value.
55 pub cooldown_rejections: u64,
56 /// Confidence rejections for this value.
57 pub confidence_rejections: u64,
58}
59
60#[derive(Debug, Clone, PartialEq, Serialize)]
61/// Data structure representing L2 diagnostic sample.
62pub struct L2DiagnosticSample {
63 /// Step for this value.
64 pub step: u64,
65 /// Selected arm for this value.
66 pub selected_arm: usize,
67 /// Optimal arm for this value.
68 pub optimal_arm: usize,
69 /// Reward for this value.
70 pub reward: f64,
71 /// Spectral bias for this value.
72 pub spectral_bias: f64,
73 /// Normalized energy for this value.
74 pub normalized_energy: f64,
75 /// Spectral dc drift for this value.
76 pub spectral_dc_drift: f64,
77 /// Convergence residual for this value.
78 pub convergence_residual: f64,
79 /// Controller residual for this value.
80 pub controller_residual: f64,
81 /// Alpha for this value.
82 pub alpha: f64,
83 /// Beta for this value.
84 pub beta: f64,
85 /// Confidence for this value.
86 pub confidence: f64,
87 /// Optional proposed expert.
88 pub proposed_expert: Option<usize>,
89 /// Whether applied is enabled or active.
90 pub applied: bool,
91 /// Optional dry run baseline arm.
92 pub dry_run_baseline_arm: Option<usize>,
93 /// Optional dry run treatment arm.
94 pub dry_run_treatment_arm: Option<usize>,
95 /// Optional dry run baseline candidate.
96 pub dry_run_baseline_candidate: Option<usize>,
97 /// Optional dry run treatment candidate.
98 pub dry_run_treatment_candidate: Option<usize>,
99 /// Optional rejection reason.
100 pub rejection_reason: Option<String>,
101}
102
103#[derive(Debug, Clone, Copy, Default, Serialize)]
104/// Data structure representing correlation diagnostic.
105pub struct CorrelationDiagnostic {
106 /// Samples for this value.
107 pub samples: usize,
108 /// Optional pearson.
109 pub pearson: Option<f64>,
110 /// Optional spearman.
111 pub spearman: Option<f64>,
112 #[serde(skip_serializing_if = "Option::is_none")]
113 /// Optional spearman bootstrap ci95.
114 pub spearman_bootstrap_ci95: Option<[f64; 2]>,
115}
116
117#[derive(Debug, Clone, Default, Serialize)]
118/// Data structure representing L2 signal diagnostics.
119pub struct L2SignalDiagnostics {
120 /// Bias to next reward for this value.
121 pub bias_to_next_reward: CorrelationDiagnostic,
122 /// Residual to next error for this value.
123 pub residual_to_next_error: CorrelationDiagnostic,
124 /// Bias to regime change for this value.
125 pub bias_to_regime_change: CorrelationDiagnostic,
126 /// Bias to next optimal arm for this value.
127 pub bias_to_next_optimal_arm: CorrelationDiagnostic,
128}
129
130#[derive(Debug, Clone, Default, Serialize)]
131/// Data structure representing L2 experiment settings.
132pub struct L2ExperimentSettings {
133 /// Whether spectral control is enabled or active.
134 pub spectral_control: bool,
135 /// Whether purity prior is enabled or active.
136 pub purity_prior: bool,
137 /// Whether reverse brake is enabled or active.
138 pub reverse_brake: bool,
139 /// Whether history discount is enabled or active.
140 pub history_discount: bool,
141}
142
143#[derive(Debug, Clone, Serialize)]
144/// Report of bandit.
145pub struct BanditReport {
146 /// Scenario for this value.
147 pub scenario: String,
148 /// Episodes for this value.
149 pub episodes: u32,
150 /// Steps per episode for this value.
151 pub steps_per_episode: u32,
152 /// Mean reward for this value.
153 pub mean_reward: f64,
154 /// Mean external reward after UCB's error, rollback, and switching costs.
155 /// This is a learning diagnostic, not a substitute for external reward.
156 pub mean_adjusted_reward: f64,
157 /// Best arm rate for this value.
158 pub best_arm_rate: f64,
159 /// Prediction-error damping factor at the end of the run.
160 pub final_damping: f64,
161 /// Final explore bonus for this value.
162 pub final_explore_bonus: f64,
163 /// Final risk tolerance for this value.
164 pub final_risk_tolerance: f64,
165 /// Whether average prediction error fell during the run.
166 pub error_decreased: bool,
167 /// Number of patches accepted during the run.
168 pub patches_accepted: u64,
169 /// Seed for this value.
170 pub seed: u64,
171 // Strategy-decay observability
172 /// Number of stored strategies.
173 pub strategy_count: usize,
174 /// Number of idle strategy.
175 pub idle_strategy_count: usize,
176 /// Mean strategy weight for this value.
177 pub mean_strategy_weight: f64,
178 /// Number of mean idle.
179 pub mean_idle_steps: f64,
180 /// Maximum idle steps.
181 pub max_idle_steps: u32,
182 /// Mean idle weight for this value.
183 pub mean_idle_weight: f64,
184 /// Mean active weight for this value.
185 pub mean_active_weight: f64,
186 /// Initial average error for this value.
187 pub initial_avg_error: f64,
188 /// Final average error for this value.
189 pub final_avg_error: f64,
190 /// Fixed point enters for this value.
191 pub fixed_point_enters: usize,
192 /// Fixed point exits for this value.
193 pub fixed_point_exits: usize,
194 /// Maximum fixed point dwell.
195 pub max_fixed_point_dwell: u64,
196 /// L2 nudges for this value.
197 pub l2_nudges: usize,
198 /// L2 proposals for this value.
199 pub l2_proposals: usize,
200 /// L2 commits for this value.
201 pub l2_commits: usize,
202 /// Action switches for this value.
203 pub action_switches: usize,
204 /// Post commit action changes for this value.
205 pub post_commit_action_changes: usize,
206 /// Post commit arm changes for this value.
207 pub post_commit_arm_changes: usize,
208 /// Distinct actions for this value.
209 pub distinct_actions: usize,
210 /// Mean l2 consequence score for this value.
211 pub mean_l2_consequence_score: f64,
212 #[serde(serialize_with = "serialize_score_breakdown")]
213 /// Mapping of final score breakdown.
214 pub final_score_breakdown: BTreeMap<String, f64>,
215 /// Final alignment score for this value.
216 pub final_alignment_score: f64,
217 /// Number of recovery.
218 pub recovery_steps: Option<u32>,
219 /// Number of L1 rollback.
220 pub l1_rollback_count: u64,
221 /// Number of L1 blocked by L2.
222 pub l1_blocked_by_l2_count: u64,
223 /// Number of L2 rollback.
224 pub l2_rollback_count: u64,
225 /// Whether dayan converged is enabled or active.
226 pub dayan_converged: bool,
227 /// Final dayan residual for this value.
228 pub final_dayan_residual: f64,
229 /// Number of dwell hold.
230 pub dwell_hold_count: u64,
231 /// Number of margin hold.
232 pub margin_hold_count: u64,
233 /// Number of active.
234 pub active_steps: u64,
235 /// Committed policies applied for this value.
236 pub committed_policies_applied: u64,
237 /// Expert metrics for this value.
238 pub expert_metrics: [L2ExpertMetrics; 4],
239 /// Lyapunov vetoes for this value.
240 pub lyapunov_vetoes: u64,
241 /// Meta cache hits for this value.
242 pub meta_cache_hits: u64,
243 /// Collection of recovery latencies.
244 pub recovery_latencies: Vec<u32>,
245 /// Collection of warm recovery latencies.
246 pub warm_recovery_latencies: Vec<u32>,
247 /// Mean residual improvement for this value.
248 pub mean_residual_improvement: f64,
249 #[serde(skip_serializing_if = "Option::is_none")]
250 /// Optional pipeline.
251 pub pipeline: Option<L2PipelineDiagnostics>,
252 #[serde(skip_serializing_if = "Option::is_none")]
253 /// Optional diagnostics.
254 pub diagnostics: Option<Vec<L2DiagnosticSample>>,
255 #[serde(skip_serializing_if = "Option::is_none")]
256 /// Optional signals.
257 pub signals: Option<L2SignalDiagnostics>,
258 #[serde(skip_serializing_if = "Option::is_none")]
259 /// Optional experiment.
260 pub experiment: Option<L2ExperimentSettings>,
261}
262
263#[derive(Debug, Clone, Serialize)]
264/// Data structure representing L2 benchmark aggregate.
265pub struct L2BenchmarkAggregate {
266 /// Runs for this value.
267 pub runs: u32,
268 /// Mean reward for this value.
269 pub mean_reward: f64,
270 /// Mean adjusted reward for this value.
271 pub mean_adjusted_reward: f64,
272 /// Best arm rate for this value.
273 pub best_arm_rate: f64,
274 /// Error decrease rate for this value.
275 pub error_decrease_rate: f64,
276 /// Mean initial error for this value.
277 pub mean_initial_error: f64,
278 /// Mean final error for this value.
279 pub mean_final_error: f64,
280 /// Mean error delta for this value.
281 pub mean_error_delta: f64,
282 /// Mean patches accepted for this value.
283 pub mean_patches_accepted: f64,
284 /// Mean fixed point enters for this value.
285 pub mean_fixed_point_enters: f64,
286 /// Mean fixed point exits for this value.
287 pub mean_fixed_point_exits: f64,
288 /// Mean maximum fixed point dwell for this value.
289 pub mean_max_fixed_point_dwell: f64,
290 /// Mean l2 nudges for this value.
291 pub mean_l2_nudges: f64,
292 /// Mean l2 proposals for this value.
293 pub mean_l2_proposals: f64,
294 /// Mean l2 commits for this value.
295 pub mean_l2_commits: f64,
296 /// Mean action switches for this value.
297 pub mean_action_switches: f64,
298 /// Mean post commit action changes for this value.
299 pub mean_post_commit_action_changes: f64,
300 /// Mean post commit arm changes for this value.
301 pub mean_post_commit_arm_changes: f64,
302 /// Mean distinct actions for this value.
303 pub mean_distinct_actions: f64,
304 /// Mean l2 consequence score for this value.
305 pub mean_l2_consequence_score: f64,
306 #[serde(serialize_with = "serialize_score_breakdown")]
307 /// Mapping of mean final score breakdown.
308 pub mean_final_score_breakdown: BTreeMap<String, f64>,
309 /// Mean final alignment score for this value.
310 pub mean_final_alignment_score: f64,
311 /// Number of mean recovery.
312 pub mean_recovery_steps: Option<f64>,
313 /// Recovery rate for this value.
314 pub recovery_rate: f64,
315 /// Number of mean L1 rollback.
316 pub mean_l1_rollback_count: f64,
317 /// Number of mean L1 blocked by L2.
318 pub mean_l1_blocked_by_l2_count: f64,
319 /// Number of mean L2 rollback.
320 pub mean_l2_rollback_count: f64,
321 /// Dayan convergence rate for this value.
322 pub dayan_convergence_rate: f64,
323 /// Mean final dayan residual for this value.
324 pub mean_final_dayan_residual: f64,
325 /// Number of mean dwell hold.
326 pub mean_dwell_hold_count: f64,
327 /// Number of mean margin hold.
328 pub mean_margin_hold_count: f64,
329 /// Number of mean active.
330 pub mean_active_steps: f64,
331 /// Mean committed policies applied for this value.
332 pub mean_committed_policies_applied: f64,
333 /// Mean expert committed for this value.
334 pub mean_expert_committed: [f64; 4],
335 /// Mean expert applied for this value.
336 pub mean_expert_applied: [f64; 4],
337 /// Mean expert not applied for this value.
338 pub mean_expert_not_applied: [f64; 4],
339 /// Optional mean expert reward.
340 pub mean_expert_reward: [Option<f64>; 4],
341 /// Mean lyapunov vetoes for this value.
342 pub mean_lyapunov_vetoes: f64,
343 /// Mean meta cache hits for this value.
344 pub mean_meta_cache_hits: f64,
345 /// Recovery event rate for this value.
346 pub recovery_event_rate: f64,
347 /// Number of mean warm recovery.
348 pub mean_warm_recovery_steps: Option<f64>,
349 /// Mean residual improvement for this value.
350 pub mean_residual_improvement: f64,
351}
352
353#[derive(Debug, Clone, Default, PartialEq, Serialize)]
354/// Data structure representing paired mean difference.
355pub struct PairedMeanDifference {
356 /// Mean for this value.
357 pub mean: f64,
358 /// Optional ci95 low.
359 pub ci95_low: Option<f64>,
360 /// Optional ci95 high.
361 pub ci95_high: Option<f64>,
362}
363
364#[derive(Debug, Clone, Serialize)]
365/// Data structure representing L2 paired run.
366pub struct L2PairedRun {
367 /// Seed for this value.
368 pub seed: u64,
369 /// Baseline for this value.
370 pub baseline: BanditReport,
371 /// Treatment for this value.
372 pub treatment: BanditReport,
373 /// Delta mean reward for this value.
374 pub delta_mean_reward: f64,
375 /// Delta best arm rate for this value.
376 pub delta_best_arm_rate: f64,
377 /// Delta error delta for this value.
378 pub delta_error_delta: f64,
379 /// Whether treatment influenced L0 is enabled or active.
380 pub treatment_influenced_l0: bool,
381}
382
383#[derive(Debug, Clone, Serialize)]
384/// Report of L2 benchmark.
385pub struct L2BenchmarkReport {
386 /// Scenario for this value.
387 pub scenario: String,
388 /// Episodes for this value.
389 pub episodes: u32,
390 /// Steps per episode for this value.
391 pub steps_per_episode: u32,
392 /// Runs for this value.
393 pub runs: u32,
394 /// Seed for this value.
395 pub seed: u64,
396 /// Baseline l2 disabled for this value.
397 pub baseline_l2_disabled: L2BenchmarkAggregate,
398 /// Whether treatment L2 enabled.
399 pub treatment_l2_enabled: L2BenchmarkAggregate,
400 /// Delta mean reward for this value.
401 pub delta_mean_reward: f64,
402 /// Delta best arm rate for this value.
403 pub delta_best_arm_rate: f64,
404 /// Delta error decrease rate for this value.
405 pub delta_error_decrease_rate: f64,
406 /// Paired reward difference for this value.
407 pub paired_reward_difference: PairedMeanDifference,
408 /// Paired best arm difference for this value.
409 pub paired_best_arm_difference: PairedMeanDifference,
410 /// Paired reward bootstrap for this value.
411 pub paired_reward_bootstrap: PairedMeanDifference,
412 /// Paired best arm bootstrap for this value.
413 pub paired_best_arm_bootstrap: PairedMeanDifference,
414 /// L0 influenced runs for this value.
415 pub l0_influenced_runs: u32,
416 /// Per-seed evidence for diagnosing differences that occur without a commit.
417 pub paired_runs: Vec<L2PairedRun>,
418}
419
420#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
421#[serde(rename_all = "snake_case")]
422/// Identifies a supported factorial arm.
423pub enum FactorialArm {
424 /// Variant representing L0.
425 L0,
426 /// Variant representing L1.
427 L1,
428 /// Variant representing L2.
429 L2,
430 /// Variant representing L1 L2.
431 L1L2,
432}
433
434impl FactorialArm {
435 /// Constant defining all.
436 pub const ALL: [Self; 4] = [Self::L0, Self::L1, Self::L2, Self::L1L2];
437
438 pub(super) fn index(self) -> usize {
439 match self {
440 Self::L0 => 0,
441 Self::L1 => 1,
442 Self::L2 => 2,
443 Self::L1L2 => 3,
444 }
445 }
446
447 /// Performs label for this type.
448 pub fn label(self) -> &'static str {
449 match self {
450 Self::L0 => "L0",
451 Self::L1 => "L1",
452 Self::L2 => "L2",
453 Self::L1L2 => "L1+L2",
454 }
455 }
456
457 pub(super) fn l1_enabled(self) -> bool {
458 matches!(self, Self::L1 | Self::L1L2)
459 }
460
461 pub(super) fn l2_enabled(self) -> bool {
462 matches!(self, Self::L2 | Self::L1L2)
463 }
464}
465
466#[derive(Debug, Clone, Default, PartialEq, Serialize)]
467/// Data structure representing factorial effect.
468pub struct FactorialEffect {
469 /// Reward for this value.
470 pub reward: PairedMeanDifference,
471 /// Reward bootstrap for this value.
472 pub reward_bootstrap: PairedMeanDifference,
473 /// Best arm rate for this value.
474 pub best_arm_rate: PairedMeanDifference,
475 /// Adjusted reward for this value.
476 pub adjusted_reward: PairedMeanDifference,
477}
478
479#[derive(Debug, Clone, Serialize)]
480/// Data structure representing factorial run.
481pub struct FactorialRun {
482 /// Seed for this value.
483 pub seed: u64,
484 /// Arms for this value.
485 pub arms: [BanditReport; 4],
486 /// L1 reward delta for this value.
487 pub l1_reward_delta: f64,
488 /// L2 reward delta for this value.
489 pub l2_reward_delta: f64,
490 /// Joint reward delta for this value.
491 pub joint_reward_delta: f64,
492 /// Interaction reward delta for this value.
493 pub interaction_reward_delta: f64,
494}
495
496#[derive(Debug, Clone, Serialize)]
497/// Report of factorial benchmark.
498pub struct FactorialBenchmarkReport {
499 /// Scenario for this value.
500 pub scenario: String,
501 /// Episodes for this value.
502 pub episodes: u32,
503 /// Steps per episode for this value.
504 pub steps_per_episode: u32,
505 /// Runs for this value.
506 pub runs: u32,
507 /// Seed for this value.
508 pub seed: u64,
509 /// Arm order for this value.
510 pub arm_order: [FactorialArm; 4],
511 /// Aggregates for this value.
512 pub aggregates: [L2BenchmarkAggregate; 4],
513 /// L1 effect for this value.
514 pub l1_effect: FactorialEffect,
515 /// L2 effect for this value.
516 pub l2_effect: FactorialEffect,
517 /// Joint effect for this value.
518 pub joint_effect: FactorialEffect,
519 /// Interaction effect for this value.
520 pub interaction_effect: FactorialEffect,
521 /// Collection of paired runs.
522 pub paired_runs: Vec<FactorialRun>,
523}
524
525/// Constant defining L2 gain scenarios.
526pub const L2_GAIN_SCENARIOS: [&str; 4] =
527 ["stable", "nonstationary", "regime_shift", "cyclic_shift"];
528/// Constant defining L2 gain discovery seed.
529pub const L2_GAIN_DISCOVERY_SEED: u64 = 20261115;
530/// Constant defining L2 gain validation seed.
531pub const L2_GAIN_VALIDATION_SEED: u64 = 20270001;
532/// Constant defining L2 gain default runs.
533pub const L2_GAIN_DEFAULT_RUNS: u32 = 30;
534/// Constant defining L2 gain default episodes.
535pub const L2_GAIN_DEFAULT_EPISODES: u32 = 12;
536/// Constant defining L2 gain default steps.
537pub const L2_GAIN_DEFAULT_STEPS: u32 = 12;
538
539#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
540#[serde(rename_all = "snake_case")]
541/// Identifies a supported L2 gain seed set.
542pub enum L2GainSeedSet {
543 /// Variant representing discovery.
544 Discovery,
545 /// Variant representing validation.
546 Validation,
547}
548
549#[derive(Debug, Clone, Serialize)]
550/// Data structure representing L2 gain scenario assessment.
551pub struct L2GainScenarioAssessment {
552 /// Whether reward ci95 lower positive is enabled or active.
553 pub reward_ci95_lower_positive: bool,
554 /// Whether stable loss within tolerance is enabled or active.
555 pub stable_loss_within_tolerance: bool,
556 /// Executed interventions for this value.
557 pub executed_interventions: u64,
558}
559
560#[derive(Debug, Clone, Serialize)]
561/// Data structure representing L2 gain assessment.
562pub struct L2GainAssessment {
563 /// Primary scenario for this value.
564 pub primary_scenario: String,
565 /// Safety scenario for this value.
566 pub safety_scenario: String,
567 /// Stable loss tolerance for this value.
568 pub stable_loss_tolerance: f64,
569 /// Whether mechanism precondition met is enabled or active.
570 pub mechanism_precondition_met: bool,
571 /// Whether discovery primary passed is enabled or active.
572 pub discovery_primary_passed: bool,
573 /// Whether validation reproduced is enabled or active.
574 pub validation_reproduced: bool,
575 /// Whether discovery safety passed is enabled or active.
576 pub discovery_safety_passed: bool,
577 /// Whether validation safety passed is enabled or active.
578 pub validation_safety_passed: bool,
579 /// Whether reproducible gain is enabled or active.
580 pub reproducible_gain: bool,
581 /// Conclusion for this value.
582 pub conclusion: String,
583 /// Discovery for this value.
584 pub discovery: L2GainScenarioAssessment,
585 /// Validation for this value.
586 pub validation: L2GainScenarioAssessment,
587}
588
589#[derive(Debug, Clone, Serialize)]
590/// Report of L2 gain matrix.
591pub struct L2GainMatrixReport {
592 /// Version of the serialized kernel-state schema.
593 pub schema_version: u32,
594 /// Design for this value.
595 pub design: String,
596 /// Runs per scenario for this value.
597 pub runs_per_scenario: u32,
598 /// Episodes for this value.
599 pub episodes: u32,
600 /// Steps per episode for this value.
601 pub steps_per_episode: u32,
602 /// Scenarios for this value.
603 pub scenarios: [&'static str; 4],
604 /// Discovery seed for this value.
605 pub discovery_seed: u64,
606 /// Validation seed for this value.
607 pub validation_seed: u64,
608 /// Kernel runs for this value.
609 pub kernel_runs: u64,
610 /// Number of decision.
611 pub decision_steps: u64,
612 /// Collection of reports.
613 pub reports: Vec<FactorialBenchmarkReport>,
614 /// Assessment for this value.
615 pub assessment: L2GainAssessment,
616}