#![allow(deprecated)]
#![cfg(feature = "alloc")]
use bcinr_cmca::allocator::{
allocate_in, power, AdaptiveUpdate, AdmittedControlState, CertificateReceipt,
CertifiedLearning, EnvelopeReceipt, FeasibleRegion, OutcomeReceipt, StabilityRefusal,
};
use bcinr_cmca::cascade::{consequence_mass, escort_weight, CascadeRefusal, CascadeTree};
use bcinr_cmca::escort::{escort_distribution, EscortRefusal};
use bcinr_cmca::fixed::{NonNegativeFixed, SignedFixed};
use bcinr_cmca::generated::consequence_mass::case_studies::{
ETA, LENS_REGISTRY, N, OBJECT_REGISTRY, Q,
};
use bcinr_cmca::generated::stability_profile::CERTIFICATE_DIGEST;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(dead_code)] enum RuntimeSemanticKind {
UniformSiblingCoverage,
SupportCoverage,
IntegerFixedPointEscort,
FractionalPowerApproximation,
AllocatorProjection,
Unclassified,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(dead_code)]
enum CorrespondenceStanding {
MatchesNamedWitnesses,
DivergesOnNamedWitness,
Experimental,
Unsupported,
}
fn mass(x: f64) -> NonNegativeFixed {
NonNegativeFixed::from_bits((x * 65536.0).round() as u32)
}
fn q(x: f64) -> SignedFixed {
SignedFixed::from_bits((x * 65536.0).round() as i32)
}
fn approx_eq(a: NonNegativeFixed, b: NonNegativeFixed, tol_bits: i64) -> bool {
(a.to_bits() as i64 - b.to_bits() as i64).abs() < tol_bits
}
const SUPPORT_COVERAGE: [f64; 3] = [0.0, 0.5, 0.5];
const SIBLING_COVERAGE: [f64; 3] = [1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0];
fn assert_is_sibling_coverage_not_support_coverage(
result: &[NonNegativeFixed],
who: &str,
kind: RuntimeSemanticKind,
) {
assert_eq!(kind, RuntimeSemanticKind::UniformSiblingCoverage);
assert_eq!(
result.len(),
3,
"{who}: expected a 3-element [0,1,3] result"
);
for (i, (&got, &sibling)) in result.iter().zip(SIBLING_COVERAGE.iter()).enumerate() {
let expected = mass(sibling);
assert!(
approx_eq(got, expected, 50),
"{who}[{i}]: got {got:?}, expected sibling-coverage {expected:?} (not support-coverage {:?})",
mass(SUPPORT_COVERAGE[i])
);
}
}
#[test]
fn cascade_escort_weight_is_uniform_sibling_coverage_at_q_zero() {
let masses = [NonNegativeFixed::ZERO, mass(1.0), mass(3.0)];
let weights: Vec<NonNegativeFixed> = masses
.iter()
.enumerate()
.map(|(i, &m)| escort_weight(m, 0, i).unwrap())
.collect();
let mut sum = NonNegativeFixed::ZERO;
for &w in &weights {
sum += w;
}
let shares: Vec<NonNegativeFixed> = weights.into_iter().map(|w| w / sum).collect();
assert_is_sibling_coverage_not_support_coverage(
&shares,
"cascade::escort_weight",
RuntimeSemanticKind::UniformSiblingCoverage,
);
}
#[test]
fn consequence_mass_is_uniform_sibling_coverage_at_q_zero() {
let tree = CascadeTree::new(
vec![None, Some(0), Some(0), Some(0)],
vec![mass(1.0), NonNegativeFixed::ZERO, mass(1.0), mass(3.0)],
)
.unwrap();
let result = consequence_mass(&tree, &[0]).unwrap();
assert_is_sibling_coverage_not_support_coverage(
&result[1..],
"cascade::consequence_mass",
RuntimeSemanticKind::UniformSiblingCoverage,
);
}
#[test]
fn power_is_uniform_sibling_coverage_at_q_zero() {
let masses = [NonNegativeFixed::ZERO, mass(1.0), mass(3.0)];
let weights: Vec<NonNegativeFixed> = masses
.iter()
.map(|&m| power(m, SignedFixed::ZERO))
.collect();
for w in &weights {
assert_eq!(w.to_bits(), NonNegativeFixed::ONE.to_bits());
}
let mut sum = NonNegativeFixed::ZERO;
for &w in &weights {
sum += w;
}
let shares: Vec<NonNegativeFixed> = weights.into_iter().map(|w| w / sum).collect();
assert_is_sibling_coverage_not_support_coverage(
&shares,
"allocator::power",
RuntimeSemanticKind::UniformSiblingCoverage,
);
}
#[test]
fn escort_distribution_integer_path_is_uniform_sibling_coverage_at_q_zero() {
let masses = [NonNegativeFixed::ZERO, mass(1.0), mass(3.0)];
let result = escort_distribution(&masses, SignedFixed::ZERO).unwrap();
assert_is_sibling_coverage_not_support_coverage(
&result,
"escort::escort_distribution",
RuntimeSemanticKind::UniformSiblingCoverage,
);
}
#[test]
fn allocate_in_is_uniform_sibling_coverage_at_q_zero() {
let coverage_lens_idx = LENS_REGISTRY
.iter()
.position(|l| l.q.to_bits() == 0)
.expect("LENS_REGISTRY must contain a q=0 lens for this test to isolate");
let mut lambda = [[NonNegativeFixed::ZERO; Q]; 4]; for row in &mut lambda {
row[coverage_lens_idx] = NonNegativeFixed::ONE;
}
let mut weights = [[NonNegativeFixed::ONE; 2 * Q]; N];
let payoffs = [[NonNegativeFixed::ZERO; 2 * Q]; N];
let mut last_switch_t = 0;
let mut prev_mode = 0;
let parent = [-1; N]; let mu = [NonNegativeFixed::ZERO; N];
let costs = [NonNegativeFixed::ZERO; N];
let proof = AdaptiveUpdate::admit_adaptive_update(
AdmittedControlState::admit_control_state(0),
CertificateReceipt::admit_certificate(0),
EnvelopeReceipt::admit_envelope(0),
OutcomeReceipt::admit_outcome(0),
NonNegativeFixed::ZERO,
NonNegativeFixed::ONE,
CertifiedLearning::admit_learning(),
);
let result = allocate_in(
&FeasibleRegion::CURRENT,
&OBJECT_REGISTRY,
&LENS_REGISTRY,
&lambda,
ETA,
&parent,
&mut weights,
&payoffs,
NonNegativeFixed::ZERO,
NonNegativeFixed::ZERO,
&mu,
&costs,
0,
&mut last_switch_t,
&mut prev_mode,
500,
CERTIFICATE_DIGEST,
proof.as_ref(),
)
.unwrap();
let first = result[0];
for (i, &v) in result.iter().enumerate() {
assert!(
approx_eq(v, first, 50),
"allocate_in q=0 (coverage lens): node {i} = {v:?}, expected uniform with node 0 = {first:?} -- sibling coverage means equal weight independent of mass"
);
}
}
#[test]
fn escort_distribution_integer_path_matches_cascade_escort_weight_is_already_proven() {
let masses = [mass(1.0), mass(2.0), mass(3.0), mass(4.0)];
let lens = 3i32;
let via_dispatch = escort_distribution(&masses, q(lens as f64)).unwrap();
let exact_weights: Vec<NonNegativeFixed> = masses
.iter()
.enumerate()
.map(|(node, &m)| escort_weight(m, lens, node).unwrap())
.collect();
let mut exact_sum = NonNegativeFixed::ZERO;
for &w in &exact_weights {
exact_sum += w;
}
let via_exact: Vec<NonNegativeFixed> =
exact_weights.into_iter().map(|w| w / exact_sum).collect();
assert_eq!(
via_dispatch, via_exact,
"bit-for-bit, not just within tolerance"
);
}
#[test]
fn escort_distribution_fractional_negative_lens_now_names_the_zero_mass_element() {
let masses = [NonNegativeFixed::ZERO, mass(1.0), mass(3.0)];
let integer_result = escort_distribution(&masses, q(-1.0));
assert!(
matches!(
integer_result,
Err(EscortRefusal::ExactPathRefused {
reason: CascadeRefusal::ZeroMassUnderNegativeLens { .. },
..
})
),
"integer negative lens over a zero-mass sibling must refuse: got {integer_result:?}"
);
let fractional_result = escort_distribution(&masses, q(-1.5));
assert!(
matches!(
fractional_result,
Err(EscortRefusal::NumericFault { index: 0, .. })
),
"CMCA-109: the fractional path must now refuse at the zero-mass element (index 0) \
via NumericFault, not silently collapse to a generic DegenerateNormalization or -- \
worse -- succeed. Got {fractional_result:?}"
);
}
#[test]
fn allocate_in_refuses_out_of_range_q_without_proof() {
let mut lenses = LENS_REGISTRY;
lenses[0].q = SignedFixed::from_bits(3 * 65536);
let lambda = bcinr_cmca::generated::consequence_mass::case_studies::LAMBDA;
let mut weights = [[NonNegativeFixed::ONE; 2 * Q]; N];
let payoffs = [[NonNegativeFixed::ZERO; 2 * Q]; N];
let mut last_switch_t = 0;
let mut prev_mode = 0;
let parent = [-1; N];
let mu = [NonNegativeFixed::ZERO; N];
let costs = [NonNegativeFixed::ZERO; N];
let result = allocate_in(
&FeasibleRegion::CURRENT,
&OBJECT_REGISTRY,
&lenses,
&lambda,
ETA,
&parent,
&mut weights,
&payoffs,
NonNegativeFixed::ZERO,
NonNegativeFixed::ZERO,
&mu,
&costs,
0,
&mut last_switch_t,
&mut prev_mode,
500,
CERTIFICATE_DIGEST,
None, );
assert!(
matches!(result, Err(StabilityRefusal::QRangeDestabilizing)),
"CMCA-103: with proof=None, an out-of-range q must now be refused as \
QRangeDestabilizing regardless of proof.is_some()/is_none() -- got {result:?}"
);
}
#[test]
fn hostile_mu_cost_baseline_now_refuses_instead_of_degenerate_fallback() {
let lambda = bcinr_cmca::generated::consequence_mass::case_studies::LAMBDA;
let mut weights = [[NonNegativeFixed::ONE; 2 * Q]; N];
let payoffs = [[NonNegativeFixed::ZERO; 2 * Q]; N];
let mut last_switch_t = 0;
let mut prev_mode = 0;
let parent = [-1; N];
let mu = [NonNegativeFixed::from_bits(0u32.wrapping_sub(327680)); N];
let costs = [NonNegativeFixed::ONE; N];
let result = allocate_in(
&FeasibleRegion::CURRENT,
&OBJECT_REGISTRY,
&LENS_REGISTRY,
&lambda,
ETA,
&parent,
&mut weights,
&payoffs,
NonNegativeFixed::ZERO,
NonNegativeFixed::ZERO,
&mu,
&costs,
0,
&mut last_switch_t,
&mut prev_mode,
500,
CERTIFICATE_DIGEST,
None,
);
assert_eq!(
result,
Err(StabilityRefusal::PriceGainUnsafe),
"CMCA-103: an out-of-domain price/mu must now refuse unconditionally instead of \
hitting the degenerate-fallback-but-Ok regime -- got {result:?}"
);
}
#[test]
fn allocate_in_now_has_a_typed_refusal_for_the_former_degenerate_fallback_regime() {
let lambda = bcinr_cmca::generated::consequence_mass::case_studies::LAMBDA;
let mut weights = [[NonNegativeFixed::ONE; 2 * Q]; N];
let payoffs = [[NonNegativeFixed::ZERO; 2 * Q]; N];
let mut last_switch_t = 0;
let mut prev_mode = 0;
let parent = [-1; N];
let mu = [NonNegativeFixed::from_bits(0u32.wrapping_sub(327680)); N];
let costs = [NonNegativeFixed::ONE; N];
let result = allocate_in(
&FeasibleRegion::CURRENT,
&OBJECT_REGISTRY,
&LENS_REGISTRY,
&lambda,
ETA,
&parent,
&mut weights,
&payoffs,
NonNegativeFixed::ZERO,
NonNegativeFixed::ZERO,
&mu,
&costs,
0,
&mut last_switch_t,
&mut prev_mode,
500,
CERTIFICATE_DIGEST,
None,
);
assert_eq!(
result,
Err(StabilityRefusal::PriceGainUnsafe),
"CMCA-103: this degenerate-but-not-cyclic input now has a typed refusal \
(PriceGainUnsafe), not the prior silent-fallback-to-Ok -- got {result:?}"
);
}
#[test]
fn allocate_in_refuses_eta_above_one_without_proof() {
let lambda = bcinr_cmca::generated::consequence_mass::case_studies::LAMBDA;
let mut weights = [[NonNegativeFixed::ONE; 2 * Q]; N];
let payoffs = [[NonNegativeFixed::ZERO; 2 * Q]; N];
let mut last_switch_t = 0;
let mut prev_mode = 0;
let parent = [-1; N];
let mu = [NonNegativeFixed::ZERO; N];
let costs = [NonNegativeFixed::ZERO; N];
let eta_over_one = NonNegativeFixed::from_bits(NonNegativeFixed::ONE.val + 1);
let result = allocate_in(
&FeasibleRegion::CURRENT,
&OBJECT_REGISTRY,
&LENS_REGISTRY,
&lambda,
eta_over_one,
&parent,
&mut weights,
&payoffs,
NonNegativeFixed::ZERO,
NonNegativeFixed::ZERO,
&mu,
&costs,
0,
&mut last_switch_t,
&mut prev_mode,
500,
CERTIFICATE_DIGEST,
None, );
assert!(
result.is_err(),
"CMCA-110: eta > 1.0 with proof=None must be refused, not silently degraded to an \
unflagged uniform-explore result -- got {result:?}"
);
assert_eq!(
result,
Err(StabilityRefusal::ExploreFloorOutsideEnvelope),
"CMCA-110: eta_err (now upper-bound-checked) must be the reason this refuses -- got \
{result:?}. CMCA-122 gave eta_err its own dedicated reason instead of folding it \
into LearningRateOutsideEnvelope."
);
}
#[test]
fn eta_above_one_underflows_the_explore_floor_blend_subtraction() {
let eta_over_one = NonNegativeFixed::from_bits(NonNegativeFixed::ONE.val + 1);
let underflowed = NonNegativeFixed::ONE - eta_over_one;
assert_eq!(
underflowed.err,
StabilityRefusal::NumericRangeExceeded as u32,
"CMCA-110: `NonNegativeFixed::ONE - eta_actual` must fault as \
NumericRangeExceeded (not silently saturate to 0 unflagged) when eta > 1.0 -- this is \
the numeric fault `numeric_has_err` folds and must surface as a refusal on the \
proof=None path now that it is selection-critical"
);
assert_eq!(
underflowed.val, 0,
"CMCA-110: the underlying saturating_sub still clamps to 0 -- the fix is that the \
resulting err flag now reaches has_refusal, not that the clamp itself changed"
);
}
#[test]
fn all_five_surfaces_have_no_production_caller_as_of_bcinr_cmca_d() {
}