spark-rsi-mv
Native Rust recursive self-improvement engine with paired bootstrap evaluation and cryptographic ledger
Brought by drakestapleton
spark-rsi-mv / src / dual / diagnostic.rs
| 1 | //! Scarcity diagnostic for RSI (ADR 0031 section 7.5 and 10). |
| 2 | //! |
| 3 | //! RSI may read a verified `DualPriceVector` as a scarcity signal: the resource with |
| 4 | //! the largest FRESH, calibrated lambda is the dominant current scarcity. |
| 5 | //! That is all this type says. It never feeds `rank_bottlenecks`, a layer's |
| 6 | //! `is_hard_invariant`, admission, ratification or promotion. A missing, |
| 7 | //! stale, refused or uncalibrated price is reported as unavailable, never as |
| 8 | //! zero scarcity. |
| 9 | |
| 10 | use super::records::{ |
| 11 | decode_constraint, decode_price_vector, digest_constraint, digest_price_vector, Class, |
| 12 | ConstraintState, Digest32, LambdaState, PriceVector, Refusal, Unit, |
| 13 | }; |
| 14 | use serde::{Deserialize, Serialize}; |
| 15 | use std::path::Path; |
| 16 | |
| 17 | /// Why no dominant scarcity can be stated. |
| 18 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 19 | #[serde(rename_all = "SCREAMING_SNAKE_CASE")] |
| 20 | pub enum UnavailableReason { |
| 21 | /// No price vector configured, or a referenced constraint record absent. |
| 22 | Missing, |
| 23 | /// Verified vector, no FRESH price, at least one STALE. |
| 24 | Stale, |
| 25 | /// Verified vector, no FRESH or STALE price, at least one FROZEN. |
| 26 | Frozen, |
| 27 | /// Verified vector, every price UNCALIBRATED. |
| 28 | Uncalibrated, |
| 29 | /// A record failed the DUAL checker, or a state carries REFUSED and nothing fresher. |
| 30 | Refused, |
| 31 | /// A supplied digest did not match the record it names. |
| 32 | DigestMismatch, |
| 33 | /// Bytes are not a well-formed record (kind, version, length). |
| 34 | Malformed, |
| 35 | } |
| 36 | |
| 37 | impl UnavailableReason { |
| 38 | pub fn name(self) -> &'static str { |
| 39 | match self { |
| 40 | UnavailableReason::Missing => "MISSING", |
| 41 | UnavailableReason::Stale => "STALE", |
| 42 | UnavailableReason::Frozen => "FROZEN", |
| 43 | UnavailableReason::Uncalibrated => "UNCALIBRATED", |
| 44 | UnavailableReason::Refused => "REFUSED", |
| 45 | UnavailableReason::DigestMismatch => "DIGEST_MISMATCH", |
| 46 | UnavailableReason::Malformed => "MALFORMED", |
| 47 | } |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | /// The only lambda state an `Available` diagnostic can carry. |
| 52 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 53 | pub enum FreshState { |
| 54 | #[serde(rename = "FRESH")] |
| 55 | Fresh, |
| 56 | } |
| 57 | |
| 58 | /// Diagnostic reading only. Two shapes, nothing else. |
| 59 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] |
| 60 | #[serde(tag = "status", rename_all = "snake_case")] |
| 61 | pub enum ScarcityDiagnostic { |
| 62 | Available { |
| 63 | resource_id: u32, |
| 64 | unit: Unit, |
| 65 | class: Class, |
| 66 | /// True for CAPACITY: the price says what more capacity would be |
| 67 | /// worth; it is never a relaxable scarcity. |
| 68 | diagnostic_only: bool, |
| 69 | lambda: f64, |
| 70 | generation: u64, |
| 71 | /// Hex of the constraint state's evidence root. |
| 72 | evidence_root: String, |
| 73 | state: FreshState, |
| 74 | }, |
| 75 | Unavailable { |
| 76 | reason: UnavailableReason, |
| 77 | detail: String, |
| 78 | }, |
| 79 | } |
| 80 | |
| 81 | impl Default for ScarcityDiagnostic { |
| 82 | fn default() -> Self { |
| 83 | ScarcityDiagnostic::Unavailable { |
| 84 | reason: UnavailableReason::Missing, |
| 85 | detail: "no price vector configured".to_string(), |
| 86 | } |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | impl ScarcityDiagnostic { |
| 91 | fn unavailable(reason: UnavailableReason, detail: impl Into<String>) -> Self { |
| 92 | ScarcityDiagnostic::Unavailable { |
| 93 | reason, |
| 94 | detail: detail.into(), |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | pub fn is_available(&self) -> bool { |
| 99 | matches!(self, ScarcityDiagnostic::Available { .. }) |
| 100 | } |
| 101 | |
| 102 | /// One plain sentence for a report or proposal rationale. |
| 103 | pub fn summary(&self) -> String { |
| 104 | match self { |
| 105 | ScarcityDiagnostic::Available { |
| 106 | resource_id, |
| 107 | unit, |
| 108 | class, |
| 109 | diagnostic_only, |
| 110 | lambda, |
| 111 | generation, |
| 112 | evidence_root, |
| 113 | .. |
| 114 | } => format!( |
| 115 | "dominant fresh calibrated scarcity: resource {} ({}), class {}{}, lambda {}, generation {}, evidence root {}, state FRESH", |
| 116 | resource_id, |
| 117 | unit.name(), |
| 118 | match class { |
| 119 | Class::Capacity => "CAPACITY", |
| 120 | Class::Soft => "SOFT", |
| 121 | }, |
| 122 | if *diagnostic_only { |
| 123 | " (diagnostic only, never relaxable)" |
| 124 | } else { |
| 125 | "" |
| 126 | }, |
| 127 | lambda, |
| 128 | generation, |
| 129 | evidence_root |
| 130 | ), |
| 131 | ScarcityDiagnostic::Unavailable { reason, detail } => format!( |
| 132 | "scarcity reading unavailable: price is {} ({})", |
| 133 | reason.name(), |
| 134 | detail |
| 135 | ), |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | /// Verify a price vector against the supplied constraint records and |
| 140 | /// select the dominant scarcity. |
| 141 | /// |
| 142 | /// `expected_vector_digest`, when given, must equal the canonical digest |
| 143 | /// of the decoded vector. Every `state[i]` digest in the vector must name |
| 144 | /// one of `constraints` (compared by recomputed digest), that record's |
| 145 | /// `resource_id` must equal `resource_id[i]`, and its `generation` must |
| 146 | /// equal the vector's. |
| 147 | /// |
| 148 | /// Selection: among states that are FRESH with a nonzero calibration |
| 149 | /// receipt, the largest lambda wins; on an exact tie the lowest |
| 150 | /// `resource_id` wins (ids are strictly ascending, so the first such |
| 151 | /// entry). Non-FRESH states are ignored for selection. If nothing is |
| 152 | /// FRESH the reason is chosen by precedence REFUSED, STALE, FROZEN, |
| 153 | /// UNCALIBRATED over the states present. |
| 154 | pub fn from_records( |
| 155 | price_vector: &[u8], |
| 156 | constraints: &[&[u8]], |
| 157 | expected_vector_digest: Option<&Digest32>, |
| 158 | ) -> ScarcityDiagnostic { |
| 159 | let vector = match decode_price_vector(price_vector) { |
| 160 | Ok(v) => v, |
| 161 | Err(r) => return Self::refusal("price vector", r), |
| 162 | }; |
| 163 | if let Some(expected) = expected_vector_digest { |
| 164 | let actual = digest_price_vector(&vector); |
| 165 | if &actual != expected { |
| 166 | return Self::unavailable( |
| 167 | UnavailableReason::DigestMismatch, |
| 168 | format!( |
| 169 | "price vector digest {} does not match expected {}", |
| 170 | hex::encode(actual), |
| 171 | hex::encode(expected) |
| 172 | ), |
| 173 | ); |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | let mut decoded: Vec<(Digest32, ConstraintState)> = Vec::with_capacity(constraints.len()); |
| 178 | for (i, bytes) in constraints.iter().enumerate() { |
| 179 | match decode_constraint(bytes) { |
| 180 | Ok(s) => { |
| 181 | let d = digest_constraint(&s); |
| 182 | decoded.push((d, s)); |
| 183 | } |
| 184 | Err(r) => return Self::refusal(&format!("constraint record {}", i), r), |
| 185 | } |
| 186 | } |
| 187 | |
| 188 | let mut states: Vec<&ConstraintState> = Vec::with_capacity(vector.entries.len()); |
| 189 | for (resource_id, state_digest) in &vector.entries { |
| 190 | let found = decoded.iter().find(|(d, _)| d == state_digest); |
| 191 | let Some((_, s)) = found else { |
| 192 | return Self::unavailable( |
| 193 | UnavailableReason::Missing, |
| 194 | format!( |
| 195 | "no supplied constraint record has digest {} (resource {})", |
| 196 | hex::encode(state_digest), |
| 197 | resource_id |
| 198 | ), |
| 199 | ); |
| 200 | }; |
| 201 | if s.resource_id != *resource_id { |
| 202 | return Self::unavailable( |
| 203 | UnavailableReason::DigestMismatch, |
| 204 | format!( |
| 205 | "state digest for resource {} names a record for resource {}", |
| 206 | resource_id, s.resource_id |
| 207 | ), |
| 208 | ); |
| 209 | } |
| 210 | if s.generation != vector.generation { |
| 211 | return Self::unavailable( |
| 212 | UnavailableReason::Refused, |
| 213 | format!( |
| 214 | "resource {} generation {} differs from vector generation {} ({})", |
| 215 | resource_id, |
| 216 | s.generation, |
| 217 | vector.generation, |
| 218 | Refusal::Generation |
| 219 | ), |
| 220 | ); |
| 221 | } |
| 222 | states.push(s); |
| 223 | } |
| 224 | |
| 225 | Self::select_dominant(&vector, &states) |
| 226 | } |
| 227 | |
| 228 | fn refusal(what: &str, r: Refusal) -> ScarcityDiagnostic { |
| 229 | let reason = match r { |
| 230 | Refusal::Kind | Refusal::Encoding => UnavailableReason::Malformed, |
| 231 | _ => UnavailableReason::Refused, |
| 232 | }; |
| 233 | Self::unavailable(reason, format!("{} refused: {}", what, r)) |
| 234 | } |
| 235 | |
| 236 | fn select_dominant(vector: &PriceVector, states: &[&ConstraintState]) -> ScarcityDiagnostic { |
| 237 | let mut best: Option<&ConstraintState> = None; |
| 238 | for s in states { |
| 239 | if !s.is_fresh_calibrated() { |
| 240 | continue; |
| 241 | } |
| 242 | best = match best { |
| 243 | None => Some(s), |
| 244 | Some(b) => { |
| 245 | if s.lambda > b.lambda |
| 246 | || (s.lambda == b.lambda && s.resource_id < b.resource_id) |
| 247 | { |
| 248 | Some(s) |
| 249 | } else { |
| 250 | Some(b) |
| 251 | } |
| 252 | } |
| 253 | }; |
| 254 | } |
| 255 | if let Some(b) = best { |
| 256 | return ScarcityDiagnostic::Available { |
| 257 | resource_id: b.resource_id, |
| 258 | unit: b.unit, |
| 259 | class: b.class, |
| 260 | diagnostic_only: b.class == Class::Capacity, |
| 261 | lambda: b.lambda, |
| 262 | generation: vector.generation, |
| 263 | evidence_root: hex::encode(b.evidence_root), |
| 264 | state: FreshState::Fresh, |
| 265 | }; |
| 266 | } |
| 267 | let has = |st: LambdaState| states.iter().any(|s| s.lambda_state == st); |
| 268 | let (reason, state_name) = if has(LambdaState::Refused) { |
| 269 | (UnavailableReason::Refused, "REFUSED") |
| 270 | } else if has(LambdaState::Stale) { |
| 271 | (UnavailableReason::Stale, "STALE") |
| 272 | } else if has(LambdaState::Frozen) { |
| 273 | (UnavailableReason::Frozen, "FROZEN") |
| 274 | } else { |
| 275 | (UnavailableReason::Uncalibrated, "UNCALIBRATED") |
| 276 | }; |
| 277 | Self::unavailable( |
| 278 | reason, |
| 279 | format!( |
| 280 | "no FRESH calibrated price in a verified vector of {} at generation {}; states include {}", |
| 281 | states.len(), |
| 282 | vector.generation, |
| 283 | state_name |
| 284 | ), |
| 285 | ) |
| 286 | } |
| 287 | |
| 288 | /// Read a price vector from a directory laid out as: |
| 289 | /// `price_vector.bin` (required), any number of `*.constraint.bin`, and |
| 290 | /// an optional `price_vector.sha256` holding the expected digest as hex. |
| 291 | /// A missing directory or missing `price_vector.bin` is `Missing`. |
| 292 | pub fn load_from_dir(dir: &Path) -> ScarcityDiagnostic { |
| 293 | let pv_path = dir.join("price_vector.bin"); |
| 294 | let pv_bytes = match std::fs::read(&pv_path) { |
| 295 | Ok(b) => b, |
| 296 | Err(e) => { |
| 297 | return Self::unavailable( |
| 298 | UnavailableReason::Missing, |
| 299 | format!("cannot read {}: {}", pv_path.display(), e), |
| 300 | ) |
| 301 | } |
| 302 | }; |
| 303 | let expected: Option<Digest32> = |
| 304 | match std::fs::read_to_string(dir.join("price_vector.sha256")) { |
| 305 | Ok(text) => match hex::decode(text.trim()) { |
| 306 | Ok(v) if v.len() == 32 => { |
| 307 | let mut d = [0u8; 32]; |
| 308 | d.copy_from_slice(&v); |
| 309 | Some(d) |
| 310 | } |
| 311 | _ => { |
| 312 | return Self::unavailable( |
| 313 | UnavailableReason::Malformed, |
| 314 | "price_vector.sha256 is not 32 bytes of hex", |
| 315 | ) |
| 316 | } |
| 317 | }, |
| 318 | Err(_) => None, |
| 319 | }; |
| 320 | let mut constraint_files: Vec<Vec<u8>> = Vec::new(); |
| 321 | let entries = match std::fs::read_dir(dir) { |
| 322 | Ok(e) => e, |
| 323 | Err(e) => { |
| 324 | return Self::unavailable( |
| 325 | UnavailableReason::Missing, |
| 326 | format!("cannot list {}: {}", dir.display(), e), |
| 327 | ) |
| 328 | } |
| 329 | }; |
| 330 | let mut names: Vec<std::path::PathBuf> = entries |
| 331 | .filter_map(|e| e.ok().map(|e| e.path())) |
| 332 | .filter(|p| { |
| 333 | p.file_name() |
| 334 | .and_then(|n| n.to_str()) |
| 335 | .map(|n| n.ends_with(".constraint.bin")) |
| 336 | .unwrap_or(false) |
| 337 | }) |
| 338 | .collect(); |
| 339 | names.sort(); |
| 340 | for p in names { |
| 341 | match std::fs::read(&p) { |
| 342 | Ok(b) => constraint_files.push(b), |
| 343 | Err(e) => { |
| 344 | return Self::unavailable( |
| 345 | UnavailableReason::Missing, |
| 346 | format!("cannot read {}: {}", p.display(), e), |
| 347 | ) |
| 348 | } |
| 349 | } |
| 350 | } |
| 351 | let refs: Vec<&[u8]> = constraint_files.iter().map(|v| v.as_slice()).collect(); |
| 352 | Self::from_records(&pv_bytes, &refs, expected.as_ref()) |
| 353 | } |
| 354 | } |