interplane.Get Omega
Read in your language

spark-rsi-mv

Native Rust recursive self-improvement engine with paired bootstrap evaluation and cryptographic ledger

Brought by drakestapleton

branch main Branches Tags History

spark-rsi-mv / src / measure / mod.rs

202 lines · 6893 bytes Raw Blame History
1//! M1 Measurement: stage samples from completed cycles, never constants.
2//!
3//! Vocabulary follows CONTEXT.md: stage, stage sample, partial cycle, workload key,
4//! execution-profile fingerprint, measured, unavailable, cold start.
5//!
6//! A cycle that ends with an error is a partial cycle: its samples go to
7//! `partial-cycles.jsonl` and are never ranked. A cycle that ends early for a normal reason
8//! (no candidate, judge refused, canary quota refused) is complete for the stages it ran.
9
10pub mod claims;
11pub mod log;
12pub mod profile;
13pub mod select;
14pub mod stats;
15
16use serde::{Deserialize, Serialize};
17use std::collections::BTreeMap;
18use std::time::Duration;
19
20pub use claims::{check_claim, requires_measured_diagnosis};
21pub use log::{SampleLog, COMPLETE_FILE, MEASURE_DIR, PARTIAL_FILE};
22pub use profile::{ExecutionConfig, ExecutionProfile, MeasureContext};
23pub use select::{build_capability_graph, measure_stages, StageMeasurement};
24pub use stats::{median, p95_if_sufficient, percentile_nearest_rank, validate_samples};
25
26/// Version 2 (2026-10-15): the execution config names the endpoint `model_url` and no longer
27/// carries a balance kernel path (the balance kernel is native Rust only). Version 1 logs are
28/// refused by the strict reader rather than mixed with version 2 samples.
29pub const SCHEMA_VERSION: u32 = 2;
30
31/// The six RSI pipeline stages, in pipeline order. These are the capability graph nodes.
32#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
33pub enum Stage {
34 Observe,
35 Propose,
36 BuildJail,
37 JudgeEvaluation,
38 SupervisorCanary,
39 CortexCommit,
40}
41
42impl Stage {
43 pub const ALL: [Stage; 6] = [
44 Stage::Observe,
45 Stage::Propose,
46 Stage::BuildJail,
47 Stage::JudgeEvaluation,
48 Stage::SupervisorCanary,
49 Stage::CortexCommit,
50 ];
51
52 /// The capability graph node id.
53 pub fn id(self) -> &'static str {
54 match self {
55 Stage::Observe => "Observe",
56 Stage::Propose => "Propose",
57 Stage::BuildJail => "BuildJail",
58 Stage::JudgeEvaluation => "JudgeEvaluation",
59 Stage::SupervisorCanary => "SupervisorCanary",
60 Stage::CortexCommit => "CortexCommit",
61 }
62 }
63}
64
65/// How a stage ended. Worst outcome wins when a stage runs once per candidate:
66/// `Failed` over `Refused` over `Ok`. Only `Failed` counts toward the error rate.
67#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
68#[serde(rename_all = "snake_case")]
69pub enum StageOutcome {
70 Ok,
71 /// A normal refusal: invariants or judge said no, the canary quota was not met.
72 Refused,
73 Failed,
74}
75
76#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
77#[serde(deny_unknown_fields)]
78pub struct StageSample {
79 pub stage: Stage,
80 pub duration_us: u64,
81 pub outcome: StageOutcome,
82 /// Recorded on SupervisorCanary samples only. Not part of the fingerprint.
83 #[serde(default, skip_serializing_if = "Option::is_none")]
84 pub canary_protocol_version: Option<u16>,
85}
86
87/// One record per cycle in `stage-samples.jsonl` (complete) or `partial-cycles.jsonl` (partial).
88#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
89#[serde(deny_unknown_fields)]
90pub struct CycleSampleRecord {
91 pub schema_version: u32,
92 pub cycle_id: String,
93 pub workload_key: String,
94 pub execution_profile_fingerprint: String,
95 pub execution_profile: ExecutionProfile,
96 /// Every stage that ran, in pipeline order.
97 pub stages: Vec<StageSample>,
98 /// Target repository HEAD when the cycle began. Provenance only, never part of the key.
99 pub source_commit: Option<String>,
100 pub recorded_at: String,
101}
102
103/// Collects per-stage wall time inside one cycle. A stage that runs more than once (once per
104/// candidate) has its durations summed and its worst outcome kept.
105#[derive(Debug, Default)]
106pub struct StageClock {
107 stages: BTreeMap<Stage, (u64, StageOutcome)>,
108}
109
110/// Records a stage on drop: `Failed` unless [`StageGuard::complete`] ran first. A stage that
111/// ends with an early `?` return still leaves its sample in the partial-cycle set.
112pub struct StageGuard<'a> {
113 clock: &'a mut StageClock,
114 stage: Stage,
115 started: std::time::Instant,
116 armed: bool,
117}
118
119impl StageGuard<'_> {
120 pub fn complete(mut self, outcome: StageOutcome) {
121 self.armed = false;
122 self.clock
123 .record(self.stage, self.started.elapsed(), outcome);
124 }
125}
126
127impl Drop for StageGuard<'_> {
128 fn drop(&mut self) {
129 if self.armed {
130 self.clock
131 .record(self.stage, self.started.elapsed(), StageOutcome::Failed);
132 }
133 }
134}
135
136impl StageClock {
137 pub fn new() -> Self {
138 Self::default()
139 }
140
141 /// Starts timing `stage`; the guard records `Failed` if dropped before `complete`.
142 pub fn guard(&mut self, stage: Stage) -> StageGuard<'_> {
143 StageGuard {
144 clock: self,
145 stage,
146 started: std::time::Instant::now(),
147 armed: true,
148 }
149 }
150
151 pub fn record(&mut self, stage: Stage, elapsed: Duration, outcome: StageOutcome) {
152 let us = u64::try_from(elapsed.as_micros()).unwrap_or(u64::MAX);
153 let entry = self.stages.entry(stage).or_insert((0, outcome));
154 entry.0 = entry.0.saturating_add(us);
155 entry.1 = entry.1.max(outcome);
156 }
157
158 /// Wall time recorded so far for a stage.
159 pub fn duration(&self, stage: Stage) -> Duration {
160 Duration::from_micros(self.stages.get(&stage).map(|s| s.0).unwrap_or(0))
161 }
162
163 pub fn is_empty(&self) -> bool {
164 self.stages.is_empty()
165 }
166
167 pub fn samples(&self) -> Vec<StageSample> {
168 self.stages
169 .iter()
170 .map(|(stage, (duration_us, outcome))| StageSample {
171 stage: *stage,
172 duration_us: *duration_us,
173 outcome: *outcome,
174 canary_protocol_version: (*stage == Stage::SupervisorCanary)
175 .then_some(crate::canary::CANARY_PROTOCOL_VERSION),
176 })
177 .collect()
178 }
179}
180
181#[cfg(test)]
182mod tests {
183 use super::*;
184
185 #[test]
186 fn guard_records_failed_on_early_return_and_the_outcome_on_complete() {
187 fn early(clock: &mut StageClock) -> Result<(), String> {
188 let _guard = clock.guard(Stage::Observe);
189 Err("boom".to_string())
190 }
191 let mut clock = StageClock::new();
192 assert!(early(&mut clock).is_err());
193 let samples = clock.samples();
194 assert_eq!(samples.len(), 1);
195 assert_eq!(samples[0].stage, Stage::Observe);
196 assert_eq!(samples[0].outcome, StageOutcome::Failed);
197
198 let mut clock = StageClock::new();
199 clock.guard(Stage::Propose).complete(StageOutcome::Ok);
200 assert_eq!(clock.samples()[0].outcome, StageOutcome::Ok);
201 }
202}