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 / tests / test_dual_price_reader.rs

841 lines · 27834 bytes Raw Blame History
1//! DUAL diagnostic price reader (ADR 0031 section 7.5 and 10).
2//!
3//! Golden vectors in tests/fixtures/dual/golden.txt were produced by the omega
4//! C encoder (branch dual/0a-records, commit
5//! f056b77f64ee94a80f4ed2899b5f9495aa3ef840). Every hostile case below is
6//! compared against the C decoder's RxDualStatus recorded in the same file.
7
8use sha2::Digest as _;
9use spark_rsi::dual::{
10 decode_constraint, decode_controller, decode_price_vector, decode_resource, digest_constraint,
11 digest_controller, digest_price_vector, digest_resource, encode_constraint, encode_controller,
12 encode_price_vector, encode_resource, verify_digest, Class, Digest32, FreshState, Kind,
13 LambdaState, PriceVector, Refusal, ScarcityDiagnostic, UnavailableReason, Unit, VerifyError,
14};
15use std::collections::HashMap;
16use std::path::Path;
17
18struct Golden {
19 bytes: HashMap<String, Vec<u8>>,
20 status: HashMap<String, i32>,
21}
22
23fn golden() -> Golden {
24 let text = std::fs::read_to_string(
25 Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/dual/golden.txt"),
26 )
27 .expect("golden fixture");
28 let mut bytes = HashMap::new();
29 let mut status = HashMap::new();
30 for line in text.lines() {
31 if line.starts_with('#') || line.trim().is_empty() {
32 continue;
33 }
34 let parts: Vec<&str> = line.split_whitespace().collect();
35 if parts[0] == "status" {
36 status.insert(parts[1].to_string(), parts[2].parse::<i32>().unwrap());
37 } else {
38 bytes.insert(parts[0].to_string(), hex::decode(parts[1]).unwrap());
39 }
40 }
41 Golden { bytes, status }
42}
43
44impl Golden {
45 fn b(&self, name: &str) -> &[u8] {
46 self.bytes
47 .get(name)
48 .unwrap_or_else(|| panic!("fixture {name}"))
49 }
50 fn d(&self, name: &str) -> Digest32 {
51 let v = self.b(&format!("{name}.digest"));
52 let mut d = [0u8; 32];
53 d.copy_from_slice(v);
54 d
55 }
56 fn st(&self, case: &str) -> i32 {
57 *self
58 .status
59 .get(case)
60 .unwrap_or_else(|| panic!("status {case}"))
61 }
62}
63
64fn tag(s: &str) -> Digest32 {
65 sha2::Sha256::digest(s.as_bytes()).into()
66}
67
68// ------------------------------------------------------------ round trips
69
70#[test]
71fn golden_resource_round_trip_and_digest() {
72 let g = golden();
73 let r = decode_resource(g.b("resource_kv")).unwrap();
74 assert_eq!(r.resource_id, 5);
75 assert_eq!(r.unit, Unit::KvBlocks);
76 assert_eq!(r.scale, 1024.0);
77 assert_eq!(r.contract, tag("contract-kv"));
78 assert_eq!(encode_resource(&r), g.b("resource_kv"));
79 assert_eq!(digest_resource(&r), g.d("resource_kv"));
80 verify_digest(Kind::Resource, g.b("resource_kv"), &g.d("resource_kv")).unwrap();
81}
82
83#[test]
84fn golden_constraints_round_trip_and_digest() {
85 let g = golden();
86 let cases: [(&str, u32, Unit, Class, f64, LambdaState, u64); 7] = [
87 (
88 "constraint_fresh_soft_ns",
89 2,
90 Unit::Ns,
91 Class::Soft,
92 0.42,
93 LambdaState::Fresh,
94 3,
95 ),
96 (
97 "constraint_fresh_soft_kv",
98 5,
99 Unit::KvBlocks,
100 Class::Soft,
101 0.42,
102 LambdaState::Fresh,
103 3,
104 ),
105 (
106 "constraint_fresh_capacity",
107 9,
108 Unit::Bytes,
109 Class::Capacity,
110 0.1,
111 LambdaState::Fresh,
112 0,
113 ),
114 (
115 "constraint_stale",
116 5,
117 Unit::KvBlocks,
118 Class::Soft,
119 0.42,
120 LambdaState::Stale,
121 4,
122 ),
123 (
124 "constraint_uncalibrated",
125 7,
126 Unit::Pj,
127 Class::Soft,
128 3.0,
129 LambdaState::Uncalibrated,
130 0,
131 ),
132 (
133 "constraint_frozen",
134 11,
135 Unit::Watt,
136 Class::Soft,
137 0.7,
138 LambdaState::Frozen,
139 2,
140 ),
141 (
142 "constraint_negzero_lambda",
143 3,
144 Unit::Ns,
145 Class::Soft,
146 0.0,
147 LambdaState::Fresh,
148 0,
149 ),
150 ];
151 for (name, id, unit, class, lambda, state, tick) in cases {
152 let s = decode_constraint(g.b(name)).unwrap_or_else(|e| panic!("{name}: {e}"));
153 assert_eq!(s.resource_id, id, "{name}");
154 assert_eq!(s.unit, unit, "{name}");
155 assert_eq!(s.class, class, "{name}");
156 assert_eq!(s.lambda, lambda, "{name}");
157 assert_eq!(s.lambda_state, state, "{name}");
158 assert_eq!(s.tick, tick, "{name}");
159 assert_eq!(s.generation, 7, "{name}");
160 assert_eq!(s.budget, 4096.0);
161 assert_eq!(s.estimate, 3900.5);
162 assert_eq!(s.uncertainty, 12.25);
163 assert_eq!(s.evidence_root, tag("evidence-root"));
164 assert_eq!(encode_constraint(&s), g.b(name), "{name} re-encode");
165 assert_eq!(digest_constraint(&s), g.d(name), "{name} digest");
166 verify_digest(Kind::Constraint, g.b(name), &g.d(name)).unwrap();
167 assert_eq!(g.b(name).len(), 294);
168 }
169}
170
171#[test]
172fn golden_controller_round_trip_and_digest() {
173 let g = golden();
174 let c = decode_controller(g.b("controller")).unwrap();
175 assert_eq!(c.eta, 0.05);
176 assert_eq!(c.rho, 0.01);
177 assert_eq!(c.k_sigma, 2.0);
178 assert_eq!(c.max_age, 16);
179 assert_eq!(c.cadence, 1);
180 assert_eq!(c.entries, vec![(2, 10.0), (5, 10.0), (9, 1.0)]);
181 assert_eq!(encode_controller(&c), g.b("controller"));
182 assert_eq!(digest_controller(&c), g.d("controller"));
183 verify_digest(Kind::Controller, g.b("controller"), &g.d("controller")).unwrap();
184}
185
186#[test]
187fn golden_price_vectors_round_trip_and_state_digests() {
188 let g = golden();
189 let a = decode_price_vector(g.b("pricevec_a")).unwrap();
190 assert_eq!(a.generation, 7);
191 assert_eq!(a.context, tag("decision-context"));
192 assert_eq!(
193 a.entries,
194 vec![
195 (2, g.d("constraint_fresh_soft_ns")),
196 (5, g.d("constraint_fresh_soft_kv")),
197 (9, g.d("constraint_fresh_capacity")),
198 ]
199 );
200 assert_eq!(encode_price_vector(&a), g.b("pricevec_a"));
201 assert_eq!(digest_price_vector(&a), g.d("pricevec_a"));
202 assert_eq!(g.b("pricevec_a").len(), 154);
203
204 let b = decode_price_vector(g.b("pricevec_b")).unwrap();
205 assert_eq!(
206 b.entries,
207 vec![
208 (5, g.d("constraint_stale")),
209 (7, g.d("constraint_uncalibrated"))
210 ]
211 );
212 assert_eq!(digest_price_vector(&b), g.d("pricevec_b"));
213
214 let c = decode_price_vector(g.b("pricevec_c")).unwrap();
215 assert_eq!(
216 c.entries,
217 vec![
218 (7, g.d("constraint_uncalibrated")),
219 (9, g.d("constraint_fresh_capacity"))
220 ]
221 );
222 assert_eq!(digest_price_vector(&c), g.d("pricevec_c"));
223 for name in ["pricevec_a", "pricevec_b", "pricevec_c"] {
224 verify_digest(Kind::PriceVector, g.b(name), &g.d(name)).unwrap();
225 }
226}
227
228#[test]
229fn negative_zero_on_the_wire_decodes_and_digests_canonically() {
230 let g = golden();
231 let canonical = g.b("constraint_negzero_lambda").to_vec();
232 // lambda occupies bytes 170..178; set the sign bit so the wire says -0.0
233 let mut wire = canonical.clone();
234 wire[177] |= 0x80;
235 assert_ne!(wire, canonical);
236 let s = decode_constraint(&wire).expect("-0.0 is finite and not negative");
237 assert_eq!(s.lambda, 0.0);
238 assert_eq!(
239 encode_constraint(&s),
240 canonical,
241 "re-encoding canonicalizes -0.0"
242 );
243 assert_eq!(digest_constraint(&s), g.d("constraint_negzero_lambda"));
244}
245
246// --------------------------------------------------------- hostile inputs
247
248fn mutate_constraint(base: &[u8], case: &str) -> Vec<u8> {
249 let mut m = base.to_vec();
250 match case {
251 "wrong_kind" => m[0] = 4,
252 "wrong_version" => m[1] = 2,
253 "truncated" => {
254 m.pop();
255 }
256 "trailing" => m.push(0),
257 "class_invariant" => m[10] = 1,
258 "class_undeclared" => m[10] = 0,
259 "unit_none" => m[6] = 0,
260 "unit_unknown" => m[6] = 16,
261 "lambda_negative" => m[177] |= 0x80,
262 "lambda_nan" => m[170..178].copy_from_slice(&f64::NAN.to_bits().to_le_bytes()),
263 "lambda_inf" => m[170..178].copy_from_slice(&f64::INFINITY.to_bits().to_le_bytes()),
264 "uncertainty_negative" => m[137] |= 0x80,
265 "fresh_without_calibration" => m[138..170].fill(0),
266 "evidence_root_zero" => m[230..262].fill(0),
267 "parent_zero_with_tick" => m[262..294].fill(0),
268 "tick_zero_with_parent" => m[222..230].fill(0),
269 "estimate_kind_zero" => m[118] = 0,
270 "estimate_kind_four" => m[118] = 4,
271 "lambda_state_zero" => m[178] = 0,
272 "lambda_state_six" => m[178] = 6,
273 "measured_without_observation" => m[54..86].fill(0),
274 "budget_contract_zero" => m[22..54].fill(0),
275 other => panic!("unknown case {other}"),
276 }
277 m
278}
279
280#[test]
281fn hostile_constraints_refused_with_the_c_status() {
282 let g = golden();
283 let base = g.b("constraint_fresh_soft_kv");
284 let cases = [
285 ("wrong_kind", Refusal::Kind),
286 ("wrong_version", Refusal::Encoding),
287 ("truncated", Refusal::Encoding),
288 ("trailing", Refusal::Encoding),
289 ("class_invariant", Refusal::Class),
290 ("class_undeclared", Refusal::Class),
291 ("unit_none", Refusal::Unit),
292 ("unit_unknown", Refusal::Unit),
293 ("lambda_negative", Refusal::Range),
294 ("lambda_nan", Refusal::NonFinite),
295 ("lambda_inf", Refusal::NonFinite),
296 ("uncertainty_negative", Refusal::Range),
297 ("fresh_without_calibration", Refusal::Calibration),
298 ("evidence_root_zero", Refusal::Digest),
299 ("parent_zero_with_tick", Refusal::Digest),
300 ("tick_zero_with_parent", Refusal::Digest),
301 ("estimate_kind_zero", Refusal::Kind),
302 ("estimate_kind_four", Refusal::Kind),
303 ("lambda_state_zero", Refusal::Range),
304 ("lambda_state_six", Refusal::Range),
305 ("measured_without_observation", Refusal::Digest),
306 ("budget_contract_zero", Refusal::Digest),
307 ];
308 assert_eq!(
309 cases.len(),
310 g.status.keys().filter(|k| !k.starts_with("pv_")).count(),
311 "every C constraint status in the fixture is covered"
312 );
313 for (case, expected) in cases {
314 let r = decode_constraint(&mutate_constraint(base, case));
315 let err = r
316 .as_ref()
317 .err()
318 .unwrap_or_else(|| panic!("{case} must be refused"));
319 assert_eq!(*err, expected, "{case}");
320 assert_eq!(err.c_status(), g.st(case), "{case} matches the C decoder");
321 // a refused record never reaches a diagnostic as a price
322 let diag = ScarcityDiagnostic::from_records(
323 g.b("pricevec_a"),
324 &[&mutate_constraint(base, case)],
325 None,
326 );
327 assert!(!diag.is_available(), "{case}");
328 }
329}
330
331fn mutate_pv(base: &[u8], case: &str) -> Vec<u8> {
332 let mut m = base.to_vec();
333 match case {
334 "pv_wrong_kind" => m[0] = 2,
335 "pv_wrong_version" => m[1] = 0,
336 "pv_truncated" => m.truncate(m.len() - 5),
337 "pv_trailing" => m.push(7),
338 "pv_unordered_ids" => {
339 m[46] = 5;
340 m[82] = 2;
341 }
342 "pv_duplicate_ids" => m[82] = 2,
343 "pv_zero_state_digest" => m[50..82].fill(0),
344 "pv_zero_context" => m[10..42].fill(0),
345 "pv_n_zero" => {
346 m[42] = 0;
347 m.truncate(46);
348 }
349 "pv_n_too_large" => m[42] = 33,
350 other => panic!("unknown case {other}"),
351 }
352 m
353}
354
355#[test]
356fn hostile_price_vectors_refused_with_the_c_status() {
357 let g = golden();
358 let base = g.b("pricevec_a");
359 let cases = [
360 ("pv_wrong_kind", Refusal::Kind),
361 ("pv_wrong_version", Refusal::Encoding),
362 ("pv_truncated", Refusal::Encoding),
363 ("pv_trailing", Refusal::Encoding),
364 ("pv_unordered_ids", Refusal::Resource),
365 ("pv_duplicate_ids", Refusal::Resource),
366 ("pv_zero_state_digest", Refusal::Digest),
367 ("pv_zero_context", Refusal::Digest),
368 ("pv_n_zero", Refusal::Range),
369 ("pv_n_too_large", Refusal::Range),
370 ];
371 assert_eq!(
372 cases.len(),
373 g.status.keys().filter(|k| k.starts_with("pv_")).count()
374 );
375 let all: Vec<&[u8]> = vec![
376 g.b("constraint_fresh_soft_ns"),
377 g.b("constraint_fresh_soft_kv"),
378 g.b("constraint_fresh_capacity"),
379 ];
380 for (case, expected) in cases {
381 let r = decode_price_vector(&mutate_pv(base, case));
382 let err = r
383 .as_ref()
384 .err()
385 .unwrap_or_else(|| panic!("{case} must be refused"));
386 assert_eq!(*err, expected, "{case}");
387 assert_eq!(err.c_status(), g.st(case), "{case} matches the C decoder");
388 let diag = ScarcityDiagnostic::from_records(&mutate_pv(base, case), &all, None);
389 match diag {
390 ScarcityDiagnostic::Unavailable { reason, .. } => assert!(
391 matches!(
392 reason,
393 UnavailableReason::Malformed | UnavailableReason::Refused
394 ),
395 "{case}: {reason:?}"
396 ),
397 other => panic!("{case}: {other:?}"),
398 }
399 }
400}
401
402#[test]
403fn decoding_the_wrong_kind_through_every_decoder_is_refused() {
404 let g = golden();
405 assert_eq!(
406 decode_resource(g.b("constraint_fresh_soft_kv")),
407 Err(Refusal::Kind)
408 );
409 assert_eq!(decode_constraint(g.b("pricevec_a")), Err(Refusal::Kind));
410 assert_eq!(decode_controller(g.b("resource_kv")), Err(Refusal::Kind));
411 assert_eq!(decode_price_vector(g.b("controller")), Err(Refusal::Kind));
412 assert_eq!(decode_constraint(&[]), Err(Refusal::Encoding));
413 assert_eq!(decode_constraint(&[2]), Err(Refusal::Encoding));
414}
415
416// ------------------------------------------------- negative control: flip
417
418#[test]
419fn negative_control_flipped_byte_fails_digest_verification() {
420 let g = golden();
421 // Flip a byte inside estimate_ref (86..118): the record still decodes,
422 // so only the digest can catch it.
423 let mut flipped = g.b("constraint_fresh_soft_kv").to_vec();
424 flipped[100] ^= 0x01;
425 decode_constraint(&flipped).expect("structurally valid");
426 let r = verify_digest(Kind::Constraint, &flipped, &g.d("constraint_fresh_soft_kv"));
427 assert!(
428 matches!(r, Err(VerifyError::DigestMismatch { .. })),
429 "{r:?}"
430 );
431 // the untouched bytes verify, proving the control is the flip
432 verify_digest(
433 Kind::Constraint,
434 g.b("constraint_fresh_soft_kv"),
435 &g.d("constraint_fresh_soft_kv"),
436 )
437 .unwrap();
438
439 // Same flip seen through the diagnostic: the vector's state digest no
440 // longer names any supplied record, so no price is read.
441 let diag = ScarcityDiagnostic::from_records(
442 g.b("pricevec_a"),
443 &[
444 g.b("constraint_fresh_soft_ns"),
445 &flipped,
446 g.b("constraint_fresh_capacity"),
447 ],
448 None,
449 );
450 assert!(matches!(
451 diag,
452 ScarcityDiagnostic::Unavailable {
453 reason: UnavailableReason::Missing,
454 ..
455 }
456 ));
457
458 // Flip in the vector itself against its expected digest.
459 let mut pv = g.b("pricevec_a").to_vec();
460 pv[20] ^= 0x80; // inside context
461 let diag = ScarcityDiagnostic::from_records(&pv, &[], Some(&g.d("pricevec_a")));
462 assert!(matches!(
463 diag,
464 ScarcityDiagnostic::Unavailable {
465 reason: UnavailableReason::DigestMismatch,
466 ..
467 }
468 ));
469}
470
471// ------------------------------------------------------ dominant scarcity
472
473#[test]
474fn dominant_scarcity_tie_breaks_on_lowest_resource_id_and_flags_capacity() {
475 let g = golden();
476 let diag = ScarcityDiagnostic::from_records(
477 g.b("pricevec_a"),
478 &[
479 // supplied out of order on purpose: matching is by digest
480 g.b("constraint_fresh_capacity"),
481 g.b("constraint_fresh_soft_kv"),
482 g.b("constraint_fresh_soft_ns"),
483 g.b("constraint_stale"), // unrelated extra record is ignored
484 ],
485 Some(&g.d("pricevec_a")),
486 );
487 match diag {
488 ScarcityDiagnostic::Available {
489 resource_id,
490 unit,
491 class,
492 diagnostic_only,
493 lambda,
494 generation,
495 ref evidence_root,
496 state,
497 } => {
498 // ids 2 and 5 both carry lambda 0.42: lowest id wins
499 assert_eq!(resource_id, 2);
500 assert_eq!(unit, Unit::Ns);
501 assert_eq!(class, Class::Soft);
502 assert!(!diagnostic_only);
503 assert_eq!(lambda, 0.42);
504 assert_eq!(generation, 7);
505 assert_eq!(*evidence_root, hex::encode(tag("evidence-root")));
506 assert_eq!(state, FreshState::Fresh);
507 }
508 other => panic!("{other:?}"),
509 }
510 let s = diag.summary();
511 assert!(s.starts_with("dominant fresh calibrated scarcity: resource 2 (NS), class SOFT, lambda 0.42, generation 7, evidence root "));
512 assert!(s.ends_with(", state FRESH"));
513
514 // CAPACITY: reported, flagged diagnostic only, never "relaxable";
515 // the UNCALIBRATED lambda 3.0 beside it is ignored.
516 let diag = ScarcityDiagnostic::from_records(
517 g.b("pricevec_c"),
518 &[
519 g.b("constraint_uncalibrated"),
520 g.b("constraint_fresh_capacity"),
521 ],
522 Some(&g.d("pricevec_c")),
523 );
524 match &diag {
525 ScarcityDiagnostic::Available {
526 resource_id,
527 class,
528 diagnostic_only,
529 lambda,
530 ..
531 } => {
532 assert_eq!(*resource_id, 9);
533 assert_eq!(*class, Class::Capacity);
534 assert!(*diagnostic_only);
535 assert_eq!(*lambda, 0.1);
536 }
537 other => panic!("{other:?}"),
538 }
539 assert!(diag
540 .summary()
541 .contains("CAPACITY (diagnostic only, never relaxable)"));
542 let json = serde_json::to_value(&diag).unwrap();
543 assert_eq!(json["status"], "available");
544 assert_eq!(json["diagnostic_only"], true);
545 assert_eq!(json["state"], "FRESH");
546}
547
548#[test]
549fn non_fresh_prices_are_unavailable_never_zero() {
550 let g = golden();
551 let diag = ScarcityDiagnostic::from_records(
552 g.b("pricevec_b"),
553 &[g.b("constraint_stale"), g.b("constraint_uncalibrated")],
554 Some(&g.d("pricevec_b")),
555 );
556 assert_eq!(
557 match &diag {
558 ScarcityDiagnostic::Unavailable { reason, .. } => *reason,
559 other => panic!("{other:?}"),
560 },
561 UnavailableReason::Stale
562 );
563 assert!(diag
564 .summary()
565 .starts_with("scarcity reading unavailable: price is STALE"));
566 let json = serde_json::to_value(&diag).unwrap();
567 assert_eq!(json["status"], "unavailable");
568 assert_eq!(json["reason"], "STALE");
569 assert!(
570 json.get("lambda").is_none(),
571 "no lambda is ever reported as zero"
572 );
573
574 // Only an UNCALIBRATED state: reason UNCALIBRATED, lambda 3.0 not surfaced.
575 let s = decode_constraint(g.b("constraint_uncalibrated")).unwrap();
576 let pv = PriceVector {
577 generation: 7,
578 context: tag("decision-context"),
579 entries: vec![(7, digest_constraint(&s))],
580 };
581 let diag = ScarcityDiagnostic::from_records(
582 &encode_price_vector(&pv),
583 &[g.b("constraint_uncalibrated")],
584 None,
585 );
586 assert!(matches!(
587 diag,
588 ScarcityDiagnostic::Unavailable {
589 reason: UnavailableReason::Uncalibrated,
590 ..
591 }
592 ));
593
594 // FROZEN alone: reason FROZEN.
595 let f = decode_constraint(g.b("constraint_frozen")).unwrap();
596 let pv = PriceVector {
597 generation: 7,
598 context: tag("decision-context"),
599 entries: vec![(11, digest_constraint(&f))],
600 };
601 let diag = ScarcityDiagnostic::from_records(
602 &encode_price_vector(&pv),
603 &[g.b("constraint_frozen")],
604 None,
605 );
606 assert!(matches!(
607 diag,
608 ScarcityDiagnostic::Unavailable {
609 reason: UnavailableReason::Frozen,
610 ..
611 }
612 ));
613}
614
615#[test]
616fn vector_state_must_name_the_right_resource_and_generation() {
617 let g = golden();
618 let ns = decode_constraint(g.b("constraint_fresh_soft_ns")).unwrap();
619 let kv = decode_constraint(g.b("constraint_fresh_soft_kv")).unwrap();
620
621 // digest for id 2 actually names the id 5 record
622 let pv = PriceVector {
623 generation: 7,
624 context: tag("decision-context"),
625 entries: vec![(2, digest_constraint(&kv)), (5, digest_constraint(&ns))],
626 };
627 let diag = ScarcityDiagnostic::from_records(
628 &encode_price_vector(&pv),
629 &[
630 g.b("constraint_fresh_soft_ns"),
631 g.b("constraint_fresh_soft_kv"),
632 ],
633 None,
634 );
635 assert!(matches!(
636 diag,
637 ScarcityDiagnostic::Unavailable {
638 reason: UnavailableReason::DigestMismatch,
639 ..
640 }
641 ));
642
643 // a state at another generation than the vector
644 let mut old = ns.clone();
645 old.generation = 6;
646 let old_bytes = encode_constraint(&old);
647 let pv = PriceVector {
648 generation: 7,
649 context: tag("decision-context"),
650 entries: vec![(2, digest_constraint(&old))],
651 };
652 let diag = ScarcityDiagnostic::from_records(&encode_price_vector(&pv), &[&old_bytes], None);
653 match diag {
654 ScarcityDiagnostic::Unavailable { reason, detail } => {
655 assert_eq!(reason, UnavailableReason::Refused);
656 assert!(detail.contains("generation 6 differs from vector generation 7"));
657 }
658 other => panic!("{other:?}"),
659 }
660
661 // a referenced record that was never supplied
662 let diag = ScarcityDiagnostic::from_records(
663 g.b("pricevec_a"),
664 &[
665 g.b("constraint_fresh_soft_ns"),
666 g.b("constraint_fresh_capacity"),
667 ],
668 None,
669 );
670 assert!(matches!(
671 diag,
672 ScarcityDiagnostic::Unavailable {
673 reason: UnavailableReason::Missing,
674 ..
675 }
676 ));
677
678 // wrong expected digest for a good vector
679 let diag = ScarcityDiagnostic::from_records(
680 g.b("pricevec_a"),
681 &[
682 g.b("constraint_fresh_soft_ns"),
683 g.b("constraint_fresh_soft_kv"),
684 g.b("constraint_fresh_capacity"),
685 ],
686 Some(&g.d("pricevec_b")),
687 );
688 assert!(matches!(
689 diag,
690 ScarcityDiagnostic::Unavailable {
691 reason: UnavailableReason::DigestMismatch,
692 ..
693 }
694 ));
695}
696
697// ---------------------------------------------------- default + directory
698
699#[test]
700fn default_is_missing_and_old_configs_still_deserialize() {
701 let d = ScarcityDiagnostic::default();
702 assert_eq!(
703 d,
704 ScarcityDiagnostic::Unavailable {
705 reason: UnavailableReason::Missing,
706 detail: "no price vector configured".to_string(),
707 }
708 );
709 assert!(d
710 .summary()
711 .starts_with("scarcity reading unavailable: price is MISSING"));
712 assert!(spark_rsi::models::RsiConfig::default()
713 .dual_price_vector_dir
714 .is_none());
715
716 // A config serialized before the new key existed still loads with None.
717 let old = serde_json::json!({
718 "target_repo": ".", "cortex_url": "http://127.0.0.1:18080", "cortex_space": "s",
719 "mojo_kernel_path": "mojo/balance_bin", "loop_interval_secs": 60,
720 "sandbox_root": "/tmp/spark-rsi-sandbox"
721 });
722 let cfg: spark_rsi::models::RsiConfig = serde_json::from_value(old).unwrap();
723 assert!(cfg.dual_price_vector_dir.is_none());
724 // RsiCycleResult.scarcity carries #[serde(default)], so a result written
725 // before the field existed deserializes to the same default.
726 assert_eq!(
727 serde_json::from_str::<ScarcityDiagnostic>(
728 &serde_json::to_string(&ScarcityDiagnostic::default()).unwrap()
729 )
730 .unwrap(),
731 ScarcityDiagnostic::default()
732 );
733}
734
735#[test]
736fn load_from_dir_reads_vector_constraints_and_optional_digest() {
737 let g = golden();
738 let dir = tempfile::tempdir().unwrap();
739 let p = dir.path();
740 assert!(matches!(
741 ScarcityDiagnostic::load_from_dir(p),
742 ScarcityDiagnostic::Unavailable {
743 reason: UnavailableReason::Missing,
744 ..
745 }
746 ));
747 assert!(matches!(
748 ScarcityDiagnostic::load_from_dir(&p.join("does-not-exist")),
749 ScarcityDiagnostic::Unavailable {
750 reason: UnavailableReason::Missing,
751 ..
752 }
753 ));
754
755 std::fs::write(p.join("price_vector.bin"), g.b("pricevec_a")).unwrap();
756 std::fs::write(p.join("ns.constraint.bin"), g.b("constraint_fresh_soft_ns")).unwrap();
757 std::fs::write(p.join("kv.constraint.bin"), g.b("constraint_fresh_soft_kv")).unwrap();
758 std::fs::write(
759 p.join("cap.constraint.bin"),
760 g.b("constraint_fresh_capacity"),
761 )
762 .unwrap();
763 std::fs::write(p.join("notes.txt"), "ignored").unwrap();
764 let diag = ScarcityDiagnostic::load_from_dir(p);
765 assert!(
766 matches!(diag, ScarcityDiagnostic::Available { resource_id: 2, .. }),
767 "{diag:?}"
768 );
769
770 std::fs::write(
771 p.join("price_vector.sha256"),
772 hex::encode(g.d("pricevec_a")),
773 )
774 .unwrap();
775 assert!(ScarcityDiagnostic::load_from_dir(p).is_available());
776
777 std::fs::write(
778 p.join("price_vector.sha256"),
779 hex::encode(g.d("pricevec_b")),
780 )
781 .unwrap();
782 assert!(matches!(
783 ScarcityDiagnostic::load_from_dir(p),
784 ScarcityDiagnostic::Unavailable {
785 reason: UnavailableReason::DigestMismatch,
786 ..
787 }
788 ));
789
790 std::fs::write(p.join("price_vector.sha256"), "zz").unwrap();
791 assert!(matches!(
792 ScarcityDiagnostic::load_from_dir(p),
793 ScarcityDiagnostic::Unavailable {
794 reason: UnavailableReason::Malformed,
795 ..
796 }
797 ));
798}
799
800// -------------------------------------------------- no authority path
801
802#[test]
803fn authority_paths_do_not_reference_the_dual_reader() {
804 // Source-level guard: ranking, evaluation layers, judging, ratification,
805 // promotion and the safety envelope never read DUAL output (ADR 0031 s6:
806 // "a consumer that reads a DualPriceVector as a gate input fails its gate").
807 let root = Path::new(env!("CARGO_MANIFEST_DIR"));
808 let guarded = [
809 "src/graph/mod.rs",
810 "src/evaluator/mod.rs",
811 "src/evaluator/layers/mod.rs",
812 "src/evaluator/layers/correctness.rs",
813 "src/evaluator/layers/security.rs",
814 "src/evaluator/layers/performance.rs",
815 "src/evaluator/layers/resource_efficiency.rs",
816 "src/evaluator/layers/style.rs",
817 "src/evaluator/layers/longitudinal_replay.rs",
818 "src/actor/judge.rs",
819 "src/ratify.rs",
820 "src/diff_gate.rs",
821 "src/canary_observation.rs",
822 "src/safety_envelope.rs",
823 "src/meta/mod.rs",
824 "src/verifier.rs",
825 ];
826 for rel in guarded {
827 let text = std::fs::read_to_string(root.join(rel)).unwrap_or_else(|e| panic!("{rel}: {e}"));
828 for needle in [
829 "dual::",
830 "ScarcityDiagnostic",
831 "scarcity",
832 "lambda_state",
833 "PriceVector",
834 ] {
835 assert!(!text.contains(needle), "{rel} references {needle}");
836 }
837 }
838 // The fixed bottleneck weights are untouched.
839 let graph = std::fs::read_to_string(root.join("src/graph/mod.rs")).unwrap();
840 assert!(graph.contains("let score = (c * 0.4) + (lat_ratio * 0.4) + (err_factor * 0.2);"));
841}