#![allow(non_upper_case_globals, unused_assignments, unused_mut, dead_code)]
#[macro_export]
macro_rules! unroll_8_static {
($var:ident, $body:expr) => {{
{
const $var: usize = 0;
$body
}
{
const $var: usize = 1;
$body
}
{
const $var: usize = 2;
$body
}
{
const $var: usize = 3;
$body
}
{
const $var: usize = 4;
$body
}
{
const $var: usize = 5;
$body
}
{
const $var: usize = 6;
$body
}
{
const $var: usize = 7;
$body
}
}};
}
#[macro_export]
macro_rules! unroll_9_static {
($var:ident, $body:expr) => {{
{
const $var: usize = 0;
$body
}
{
const $var: usize = 1;
$body
}
{
const $var: usize = 2;
$body
}
{
const $var: usize = 3;
$body
}
{
const $var: usize = 4;
$body
}
{
const $var: usize = 5;
$body
}
{
const $var: usize = 6;
$body
}
{
const $var: usize = 7;
$body
}
{
const $var: usize = 8;
$body
}
}};
}
#[macro_export]
macro_rules! unroll_4_static {
($var:ident, $body:expr) => {{
{
const $var: usize = 0;
$body
}
{
const $var: usize = 1;
$body
}
{
const $var: usize = 2;
$body
}
{
const $var: usize = 3;
$body
}
}};
}
#[macro_export]
macro_rules! unroll_32_static {
($var:ident, $body:expr) => {{
{
const $var: usize = 0;
$body
}
{
const $var: usize = 1;
$body
}
{
const $var: usize = 2;
$body
}
{
const $var: usize = 3;
$body
}
{
const $var: usize = 4;
$body
}
{
const $var: usize = 5;
$body
}
{
const $var: usize = 6;
$body
}
{
const $var: usize = 7;
$body
}
{
const $var: usize = 8;
$body
}
{
const $var: usize = 9;
$body
}
{
const $var: usize = 10;
$body
}
{
const $var: usize = 11;
$body
}
{
const $var: usize = 12;
$body
}
{
const $var: usize = 13;
$body
}
{
const $var: usize = 14;
$body
}
{
const $var: usize = 15;
$body
}
{
const $var: usize = 16;
$body
}
{
const $var: usize = 17;
$body
}
{
const $var: usize = 18;
$body
}
{
const $var: usize = 19;
$body
}
{
const $var: usize = 20;
$body
}
{
const $var: usize = 21;
$body
}
{
const $var: usize = 22;
$body
}
{
const $var: usize = 23;
$body
}
{
const $var: usize = 24;
$body
}
{
const $var: usize = 25;
$body
}
{
const $var: usize = 26;
$body
}
{
const $var: usize = 27;
$body
}
{
const $var: usize = 28;
$body
}
{
const $var: usize = 29;
$body
}
{
const $var: usize = 30;
$body
}
{
const $var: usize = 31;
$body
}
}};
}
macro_rules! unroll_5_static {
($var:ident, $body:expr) => {{
{
const $var: usize = 0;
$body
}
{
const $var: usize = 1;
$body
}
{
const $var: usize = 2;
$body
}
{
const $var: usize = 3;
$body
}
{
const $var: usize = 4;
$body
}
}};
}
use crate::fixed::{NonNegativeFixed, SignedFixed};
use crate::generated::consequence_mass::case_studies::{
LensSpec, PackedSemanticState, FACTOR_ACCESS_FREQUENCY, FACTOR_BUSINESS_VALUE,
FACTOR_DOWNSTREAM_CONSEQUENCE, FACTOR_RECOMPUTATION_COST, FACTOR_RETRIEVAL_DEMAND,
FACTOR_SCHEDULING_DEMAND, FACTOR_SEARCH_DEMAND, FACTOR_STANDING, FACTOR_VERIFICATION_COST, K,
MEASURE_CACHE, MEASURE_RETRIEVAL, MEASURE_SCHEDULING, MEASURE_SEARCH, N, Q,
};
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum StabilityRefusal {
CertificateMissing,
BlockGainBoundExceeded,
ContractionMarginInsufficient,
LearningRateOutsideEnvelope,
ModeDwellTimeViolated,
QRangeDestabilizing,
MassClampUnsafe,
PriceGainUnsafe,
StandingProjectionGainUnsafe,
RuntimeEnvelopeViolated,
CertificateDigestMismatch,
ControlModeUncertified,
ControlModeSwitchTooFast,
YieldGainBoundViolated,
RewardBoundViolated,
ResourceResponseBoundViolated,
StandingResetBoundViolated,
LearningFrozen,
NumericRangeExceeded,
UnsupportedDomain,
ContractViolation,
ExploreFloorOutsideEnvelope,
}
impl core::fmt::Display for StabilityRefusal {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
core::fmt::Debug::fmt(self, f)
}
}
#[cfg(feature = "std")]
impl std::error::Error for StabilityRefusal {}
impl StabilityRefusal {
pub fn from_u32(val: u32) -> Option<Self> {
let lookup = [
Some(Self::CertificateMissing),
Some(Self::BlockGainBoundExceeded),
Some(Self::ContractionMarginInsufficient),
Some(Self::LearningRateOutsideEnvelope),
Some(Self::ModeDwellTimeViolated),
Some(Self::QRangeDestabilizing),
Some(Self::MassClampUnsafe),
Some(Self::PriceGainUnsafe),
Some(Self::StandingProjectionGainUnsafe),
Some(Self::RuntimeEnvelopeViolated),
Some(Self::CertificateDigestMismatch),
Some(Self::ControlModeUncertified),
Some(Self::ControlModeSwitchTooFast),
Some(Self::YieldGainBoundViolated),
Some(Self::RewardBoundViolated),
Some(Self::ResourceResponseBoundViolated),
Some(Self::StandingResetBoundViolated),
Some(Self::LearningFrozen),
Some(Self::NumericRangeExceeded),
Some(Self::UnsupportedDomain),
Some(Self::ContractViolation),
Some(Self::ExploreFloorOutsideEnvelope),
None,
None,
None,
None,
None,
None,
None,
None,
None,
];
let in_bounds = const_lt_u32(val, 22);
let idx = const_select_u32(in_bounds, val, 22) as usize;
lookup[idx & 31]
}
}
const REFUSALS: [StabilityRefusal; 32] = [
StabilityRefusal::CertificateMissing,
StabilityRefusal::BlockGainBoundExceeded,
StabilityRefusal::ContractionMarginInsufficient,
StabilityRefusal::LearningRateOutsideEnvelope,
StabilityRefusal::ModeDwellTimeViolated,
StabilityRefusal::QRangeDestabilizing,
StabilityRefusal::MassClampUnsafe,
StabilityRefusal::PriceGainUnsafe,
StabilityRefusal::StandingProjectionGainUnsafe,
StabilityRefusal::RuntimeEnvelopeViolated,
StabilityRefusal::CertificateDigestMismatch,
StabilityRefusal::ControlModeUncertified,
StabilityRefusal::ControlModeSwitchTooFast,
StabilityRefusal::YieldGainBoundViolated,
StabilityRefusal::RewardBoundViolated,
StabilityRefusal::ResourceResponseBoundViolated,
StabilityRefusal::StandingResetBoundViolated,
StabilityRefusal::LearningFrozen,
StabilityRefusal::NumericRangeExceeded,
StabilityRefusal::UnsupportedDomain,
StabilityRefusal::ContractViolation,
StabilityRefusal::ExploreFloorOutsideEnvelope,
StabilityRefusal::CertificateMissing,
StabilityRefusal::CertificateMissing,
StabilityRefusal::CertificateMissing,
StabilityRefusal::CertificateMissing,
StabilityRefusal::CertificateMissing,
StabilityRefusal::CertificateMissing,
StabilityRefusal::CertificateMissing,
StabilityRefusal::CertificateMissing,
StabilityRefusal::CertificateMissing,
StabilityRefusal::CertificateMissing,
];
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum HierarchyRefusal {
Cyclic,
}
#[allow(non_snake_case)]
pub(crate) fn ancestor_doubling_table(parent: &[i32; N]) -> [[i32; N]; 8] {
let mut P = [[-1i32; N]; 8];
unroll_8_static!(j, {
P[0][j] = parent[j];
});
unroll_8_static!(j, {
let parent_node = P[0][j];
let mut p_next = -1i32;
unroll_8_static!(p_idx, {
let matches = const_eq_u32(parent_node as u32, p_idx as u32);
p_next = const_select_u32(matches, parent[p_idx] as u32, p_next as u32) as i32;
});
P[1][j] = p_next;
});
unroll_8_static!(j, {
let parent_node = P[1][j];
let mut p_next = -1i32;
unroll_8_static!(p_idx, {
let matches = const_eq_u32(parent_node as u32, p_idx as u32);
p_next = const_select_u32(matches, parent[p_idx] as u32, p_next as u32) as i32;
});
P[2][j] = p_next;
});
unroll_8_static!(j, {
let parent_node = P[2][j];
let mut p_next = -1i32;
unroll_8_static!(p_idx, {
let matches = const_eq_u32(parent_node as u32, p_idx as u32);
p_next = const_select_u32(matches, parent[p_idx] as u32, p_next as u32) as i32;
});
P[3][j] = p_next;
});
unroll_8_static!(j, {
let parent_node = P[3][j];
let mut p_next = -1i32;
unroll_8_static!(p_idx, {
let matches = const_eq_u32(parent_node as u32, p_idx as u32);
p_next = const_select_u32(matches, parent[p_idx] as u32, p_next as u32) as i32;
});
P[4][j] = p_next;
});
unroll_8_static!(j, {
let parent_node = P[4][j];
let mut p_next = -1i32;
unroll_8_static!(p_idx, {
let matches = const_eq_u32(parent_node as u32, p_idx as u32);
p_next = const_select_u32(matches, parent[p_idx] as u32, p_next as u32) as i32;
});
P[5][j] = p_next;
});
unroll_8_static!(j, {
let parent_node = P[5][j];
let mut p_next = -1i32;
unroll_8_static!(p_idx, {
let matches = const_eq_u32(parent_node as u32, p_idx as u32);
p_next = const_select_u32(matches, parent[p_idx] as u32, p_next as u32) as i32;
});
P[6][j] = p_next;
});
unroll_8_static!(j, {
let parent_node = P[6][j];
let mut p_next = -1i32;
unroll_8_static!(p_idx, {
let matches = const_eq_u32(parent_node as u32, p_idx as u32);
p_next = const_select_u32(matches, parent[p_idx] as u32, p_next as u32) as i32;
});
P[7][j] = p_next;
});
P
}
pub fn check_hierarchy_acyclic(parent: &[i32; N]) -> Result<(), HierarchyRefusal> {
let p = ancestor_doubling_table(parent);
let mut has_cycle = false;
unroll_8_static!(j, {
has_cycle |= p[7][j] != -1;
});
if has_cycle {
Err(HierarchyRefusal::Cyclic)
} else {
Ok(())
}
}
const LEAF_RECIP: [NonNegativeFixed; 9] = [
NonNegativeFixed::from_bits(0),
NonNegativeFixed::from_bits(65536), NonNegativeFixed::from_bits(32768), NonNegativeFixed::from_bits(21845), NonNegativeFixed::from_bits(16384), NonNegativeFixed::from_bits(13107), NonNegativeFixed::from_bits(10922), NonNegativeFixed::from_bits(9362), NonNegativeFixed::from_bits(8192), ];
pub fn wrap_result(
pi_res: [NonNegativeFixed; N],
err_code: u32,
) -> Result<[NonNegativeFixed; N], StabilityRefusal> {
let err_val = REFUSALS[(err_code as usize) & 31];
let is_ok = const_eq_u32(err_code, u32::MAX);
let outcomes = [Err(err_val), Ok(pi_res)];
outcomes[(is_ok as usize) & 1]
}
#[inline(always)]
pub fn const_select_u32(condition: u32, a: u32, b: u32) -> u32 {
let cond = core::hint::black_box(condition);
let cond_val = (cond | cond.wrapping_neg()) >> 31;
let mask = 0u32.wrapping_sub(cond_val);
(core::hint::black_box(a) & mask) | (core::hint::black_box(b) & !mask)
}
#[inline(always)]
pub fn const_lt_u32(a: u32, b: u32) -> u32 {
let a_bb = core::hint::black_box(a);
let b_bb = core::hint::black_box(b);
((a_bb ^ ((a_bb ^ b_bb) | (a_bb.wrapping_sub(b_bb) ^ b_bb))) >> 31) & 1
}
#[inline(always)]
pub fn const_eq_u32(a: u32, b: u32) -> u32 {
let x = core::hint::black_box(a) ^ core::hint::black_box(b);
let nonzero = (x | x.wrapping_neg()) >> 31;
1u32.wrapping_sub(nonzero)
}
#[inline(always)]
pub fn const_select_bool(condition: u32, a: bool, b: bool) -> bool {
const_select_u32(condition, a as u32, b as u32) != 0
}
#[inline(always)]
pub(crate) fn const_max_i32(a: i32, b: i32) -> i32 {
let diff_64 = (a as i64).wrapping_sub(b as i64);
let is_lt = (diff_64 >> 63) & 1;
const_select_u32(is_lt as u32, b as u32, a as u32) as i32
}
#[doc(hidden)]
#[deprecated(
note = "CMCA-102/CMCA-114: authority chain pending Hoare-logic verification, do not use in production code"
)]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct CertifiedLearning {
_sealed: (),
}
#[allow(deprecated)]
impl CertifiedLearning {
#[inline(always)]
#[allow(deprecated)]
pub(crate) const fn new() -> Self {
Self { _sealed: () }
}
#[inline(always)]
#[deprecated(
note = "CMCA-102/CMCA-114: authority chain pending Hoare-logic verification, do not use in production code"
)]
#[allow(deprecated)]
pub const fn admit_learning() -> Self {
Self { _sealed: () }
}
}
#[doc(hidden)]
#[deprecated(
note = "CMCA-102/CMCA-114: authority chain pending Hoare-logic verification, do not use in production code"
)]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct CertifiedSelectionOnly {
_sealed: (),
}
#[allow(deprecated)]
impl CertifiedSelectionOnly {
#[inline(always)]
#[allow(deprecated)]
pub(crate) const fn new() -> Self {
Self { _sealed: () }
}
#[inline(always)]
#[deprecated(
note = "CMCA-102/CMCA-114: authority chain pending Hoare-logic verification, do not use in production code"
)]
#[allow(deprecated)]
pub const fn admit_selection_only() -> Self {
Self { _sealed: () }
}
}
#[doc(hidden)]
#[deprecated(
note = "CMCA-102/CMCA-114: authority chain pending Hoare-logic verification, do not use in production code"
)]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct AdmittedControlState {
pub(crate) digest: u64,
}
#[allow(deprecated)]
impl AdmittedControlState {
#[inline(always)]
#[allow(deprecated)]
pub(crate) const fn new(digest: u64) -> Self {
Self { digest }
}
#[inline(always)]
#[deprecated(
note = "CMCA-102/CMCA-114: authority chain pending Hoare-logic verification, do not use in production code"
)]
#[allow(deprecated)]
pub const fn admit_control_state(digest: u64) -> Self {
Self { digest }
}
}
#[doc(hidden)]
#[deprecated(
note = "CMCA-102/CMCA-114: authority chain pending Hoare-logic verification, do not use in production code"
)]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct CertificateReceipt {
pub(crate) digest: u64,
}
#[allow(deprecated)]
impl CertificateReceipt {
#[inline(always)]
#[allow(deprecated)]
pub(crate) const fn new(digest: u64) -> Self {
Self { digest }
}
#[inline(always)]
#[deprecated(
note = "CMCA-102/CMCA-114: authority chain pending Hoare-logic verification, do not use in production code"
)]
#[allow(deprecated)]
pub const fn admit_certificate(digest: u64) -> Self {
Self { digest }
}
}
#[doc(hidden)]
#[deprecated(
note = "CMCA-102/CMCA-114: authority chain pending Hoare-logic verification, do not use in production code"
)]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct EnvelopeReceipt {
pub(crate) digest: u64,
}
#[allow(deprecated)]
impl EnvelopeReceipt {
#[inline(always)]
#[allow(deprecated)]
pub(crate) const fn new(digest: u64) -> Self {
Self { digest }
}
#[inline(always)]
#[deprecated(
note = "CMCA-102/CMCA-114: authority chain pending Hoare-logic verification, do not use in production code"
)]
#[allow(deprecated)]
pub const fn admit_envelope(digest: u64) -> Self {
Self { digest }
}
}
#[doc(hidden)]
#[deprecated(
note = "CMCA-102/CMCA-114: authority chain pending Hoare-logic verification, do not use in production code"
)]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct OutcomeReceipt {
pub(crate) digest: u64,
}
#[allow(deprecated)]
impl OutcomeReceipt {
#[inline(always)]
#[allow(deprecated)]
pub(crate) const fn new(digest: u64) -> Self {
Self { digest }
}
#[inline(always)]
#[deprecated(
note = "CMCA-102/CMCA-114: authority chain pending Hoare-logic verification, do not use in production code"
)]
#[allow(deprecated)]
pub const fn admit_outcome(digest: u64) -> Self {
Self { digest }
}
}
#[doc(hidden)]
#[deprecated(
note = "CMCA-102/CMCA-114: authority chain pending Hoare-logic verification, do not use in production code"
)]
#[derive(Debug, PartialEq, Eq)]
pub struct AdaptiveUpdate<Mode> {
_mode: core::marker::PhantomData<Mode>,
}
#[allow(deprecated)]
impl<Mode> Clone for AdaptiveUpdate<Mode> {
#[inline(always)]
fn clone(&self) -> Self {
*self
}
}
#[allow(deprecated)]
impl<Mode> Copy for AdaptiveUpdate<Mode> {}
#[allow(deprecated)]
impl AdaptiveUpdate<CertifiedLearning> {
#[inline(always)]
#[deprecated(
note = "CMCA-102/CMCA-114: authority chain pending Hoare-logic verification, do not use in production code"
)]
pub fn admit_adaptive_update(
state: AdmittedControlState,
cert: CertificateReceipt,
env: EnvelopeReceipt,
outcome: OutcomeReceipt,
temperature: NonNegativeFixed,
distinguishability: NonNegativeFixed,
_mode: CertifiedLearning,
) -> Option<Self> {
let temp_ceil = ((crate::generated::stability_profile::PROFILE
.temperature_ceiling
.raw
* 65536)
/ 1_000_000_000) as u32;
let dist_floor = ((crate::generated::stability_profile::PROFILE
.distinguishability_floor
.raw
* 65536)
/ 1_000_000_000) as u32;
let temp_ok = (const_lt_u32(temp_ceil, temperature.val) == 0) as u32;
let dist_ok = (const_lt_u32(distinguishability.val, dist_floor) == 0) as u32;
let digests_ok = (((state.digest ^ cert.digest)
| (state.digest ^ env.digest)
| (state.digest ^ outcome.digest))
== 0) as u32;
let ok = temp_ok & dist_ok & digests_ok;
let outcomes = [
None,
Some(Self {
_mode: core::marker::PhantomData,
}),
];
outcomes[(ok as usize) & 1]
}
}
#[inline(always)]
pub fn power(base: NonNegativeFixed, exponent: SignedFixed) -> NonNegativeFixed {
let base_is_zero = const_eq_u32(base.val, 0);
let log_val = base.log2();
let product = exponent.saturating_mul(log_val);
let pow_val = product.exp2();
let exp_val = exponent.val;
let exp_gt_zero = (((0i32.wrapping_sub(exp_val)) >> 31) & 1) as u32;
let exp_eq_zero = const_eq_u32(exponent.val as u32, 0);
let zero_res = const_select_u32(
exp_eq_zero,
NonNegativeFixed::ONE.val,
const_select_u32(exp_gt_zero, 0, u32::MAX),
);
let exp_lt_zero = const_select_u32(exp_gt_zero | exp_eq_zero, 0, u32::MAX);
let zero_base_err = const_select_u32(
exp_lt_zero,
StabilityRefusal::UnsupportedDomain as u32,
u32::MAX,
);
NonNegativeFixed {
val: const_select_u32(base_is_zero, zero_res, pow_val.val),
err: const_select_u32(base_is_zero, zero_base_err, pow_val.err),
}
}
#[inline(always)]
pub(crate) fn clip(
val: NonNegativeFixed,
min_val: NonNegativeFixed,
max_val: NonNegativeFixed,
) -> NonNegativeFixed {
let lt_min = const_lt_u32(val.val, min_val.val);
let val_or_min = const_select_u32(lt_min, min_val.val, val.val);
let gt_max = const_lt_u32(max_val.val, val_or_min);
NonNegativeFixed::from_bits(const_select_u32(gt_max, max_val.val, val_or_min))
}
#[cfg(test)]
mod clip_tests {
use super::*;
fn fx(v: u32) -> NonNegativeFixed {
NonNegativeFixed::from_bits(v)
}
#[test]
fn clip_clamps_values_above_max_down_to_max() {
let result = clip(fx(1_000_000), fx(0), fx(500_000));
assert_eq!(result.val, 500_000, "value above max must clamp to max");
}
#[test]
fn clip_clamps_values_below_min_up_to_min() {
let result = clip(fx(10), fx(100), fx(500_000));
assert_eq!(result.val, 100, "value below min must clamp to min");
}
#[test]
fn clip_passes_in_range_values_through_unchanged() {
let result = clip(fx(250_000), fx(0), fx(500_000));
assert_eq!(
result.val, 250_000,
"in-range value must pass through as identity"
);
}
#[test]
fn clip_at_exact_bounds_is_identity() {
assert_eq!(clip(fx(0), fx(0), fx(500_000)).val, 0);
assert_eq!(clip(fx(500_000), fx(0), fx(500_000)).val, 500_000);
}
}
#[inline(never)]
#[allow(clippy::too_many_arguments)] fn flow_step(
parent: &[i32; N],
is_leaf: &[bool; N],
is_subtree_leaf: &[[bool; N]; N],
rho: &[NonNegativeFixed; N],
child_w: &[[NonNegativeFixed; N]; N],
cw_sum: &[NonNegativeFixed; N],
leaf_w: &[[NonNegativeFixed; N]; N],
lw_sum: &[NonNegativeFixed; N],
alloc_flow: &mut [NonNegativeFixed; N],
flat_alloc: &mut [NonNegativeFixed; N],
) {
unroll_8_static!(v, {
let has_children = !is_leaf[v & 7];
let flat_part = NonNegativeFixed::from_bits(const_select_u32(
has_children as u32,
((NonNegativeFixed::ONE - rho[v & 7]) * alloc_flow[v & 7]).val,
0,
));
let desc_part = NonNegativeFixed::from_bits(const_select_u32(
has_children as u32,
(rho[v & 7] * alloc_flow[v & 7]).val,
0,
));
#[allow(unused_variables)]
let l_cond = const_eq_u32(lw_sum[v & 7].val, 0);
#[cfg(feature = "mutant_3")]
let lw_denom = NonNegativeFixed::ONE.val;
#[cfg(not(feature = "mutant_3"))]
let lw_denom = const_select_u32(l_cond, NonNegativeFixed::ONE.val, lw_sum[v & 7].val);
let c_cond = const_eq_u32(cw_sum[v & 7].val, 0);
let cw_denom = const_select_u32(c_cond, NonNegativeFixed::ONE.val, cw_sum[v & 7].val);
unroll_8_static!(x, {
let is_sub = is_subtree_leaf[v & 7][x & 7] & has_children;
let flat_addition = flat_part
* leaf_w[v & 7][x & 7].saturating_div(NonNegativeFixed::from_bits(lw_denom));
flat_alloc[x & 7] +=
NonNegativeFixed::from_bits(const_select_u32(is_sub as u32, flat_addition.val, 0));
let is_child = (parent[x & 7] == v as i32) & has_children;
let flow_addition = desc_part
* child_w[v & 7][x & 7].saturating_div(NonNegativeFixed::from_bits(cw_denom));
alloc_flow[x & 7] += NonNegativeFixed::from_bits(const_select_u32(
is_child as u32,
flow_addition.val,
0,
));
});
alloc_flow[v & 7] = NonNegativeFixed::from_bits(const_select_u32(
has_children as u32,
0,
alloc_flow[v & 7].val,
));
});
}
#[inline(never)]
#[allow(clippy::too_many_arguments)] pub(crate) fn compute_pi_kq_for_kq(
k_actual: usize,
q_idx: usize,
q_val_mutated: SignedFixed,
parent: &[i32; N],
is_leaf: &[bool; N],
is_subtree_leaf: &[[bool; N]; N],
node_masses: &[[NonNegativeFixed; N]; K],
local_weights: &[[NonNegativeFixed; 2 * Q]; N],
) -> [NonNegativeFixed; N] {
let mut a_roots = [0i32; N];
let mut a_max_root = i32::MIN;
unroll_8_static!(i, {
let is_r = parent[i & 7] == -1;
let a_i = (((q_val_mutated.val as i64)
.wrapping_mul(node_masses[k_actual & 3][i & 7].log2().val as i64))
>> 16) as i32;
a_roots[i & 7] = const_select_u32(is_r as u32, a_i as u32, i32::MIN as u32) as i32;
a_max_root = const_max_i32(a_max_root, a_roots[i & 7]);
});
let mut root_w = [NonNegativeFixed::ZERO; N];
let mut root_w_sum = NonNegativeFixed::ZERO;
unroll_8_static!(i, {
root_w[i & 7] = NonNegativeFixed::from_bits(const_select_u32(
(parent[i & 7] == -1) as u32,
SignedFixed::from_bits(a_roots[i & 7].wrapping_sub(a_max_root))
.exp2()
.val,
0,
));
root_w_sum += root_w[i & 7];
});
let mut alloc_flow = [NonNegativeFixed::ZERO; N];
unroll_8_static!(i, {
let is_r = parent[i & 7] == -1;
let r_cond = const_eq_u32(root_w_sum.val, 0);
let flow_val = root_w[i & 7].saturating_div(NonNegativeFixed::from_bits(const_select_u32(
r_cond,
NonNegativeFixed::ONE.val,
root_w_sum.val,
)));
alloc_flow[i & 7] =
NonNegativeFixed::from_bits(const_select_u32(is_r as u32, flow_val.val, 0));
});
let mut rho = [NonNegativeFixed::ZERO; N];
let mut child_w = [[NonNegativeFixed::ZERO; N]; N];
let mut cw_sum = [NonNegativeFixed::ZERO; N];
let mut leaf_w = [[NonNegativeFixed::ZERO; N]; N];
let mut lw_sum = [NonNegativeFixed::ZERO; N];
unroll_8_static!(v, {
let w_sum =
local_weights[v & 7][(2 * q_idx) & 7] + local_weights[v & 7][(2 * q_idx + 1) & 7];
rho[v & 7] = NonNegativeFixed::from_bits(const_select_u32(
const_eq_u32(w_sum.val, 0),
32768,
local_weights[v & 7][(2 * q_idx + 1) & 7]
.saturating_div(w_sum)
.val,
));
let mut a_c = [0i32; N];
let mut a_max_c = i32::MIN;
unroll_8_static!(c, {
let is_c = parent[c & 7] == v as i32;
a_c[c & 7] = const_select_u32(
is_c as u32,
(((q_val_mutated.val as i64)
.wrapping_mul(node_masses[k_actual & 3][c & 7].log2().val as i64))
>> 16) as u32,
i32::MIN as u32,
) as i32;
a_max_c = const_max_i32(a_max_c, a_c[c & 7]);
});
unroll_8_static!(c, {
let matches = a_c[c & 7] != i32::MIN;
child_w[v & 7][c & 7] = NonNegativeFixed::from_bits(const_select_u32(
matches as u32,
SignedFixed::from_bits(a_c[c & 7].wrapping_sub(a_max_c))
.exp2()
.val,
0,
));
cw_sum[v & 7] += child_w[v & 7][c & 7];
});
let mut a_l = [0i32; N];
let mut a_max_l = i32::MIN;
unroll_8_static!(x, {
let is_sub = is_subtree_leaf[v & 7][x & 7];
a_l[x & 7] = const_select_u32(
is_sub as u32,
(((q_val_mutated.val as i64)
.wrapping_mul(node_masses[k_actual & 3][x & 7].log2().val as i64))
>> 16) as u32,
i32::MIN as u32,
) as i32;
a_max_l = const_max_i32(a_max_l, a_l[x & 7]);
});
unroll_8_static!(x, {
let matches = a_l[x & 7] != i32::MIN;
leaf_w[v & 7][x & 7] = NonNegativeFixed::from_bits(const_select_u32(
matches as u32,
SignedFixed::from_bits(a_l[x & 7].wrapping_sub(a_max_l))
.exp2()
.val,
0,
));
lw_sum[v & 7] += leaf_w[v & 7][x & 7];
});
});
let mut flat_alloc = [NonNegativeFixed::ZERO; N];
flow_step(
parent,
is_leaf,
is_subtree_leaf,
&rho,
&child_w,
&cw_sum,
&leaf_w,
&lw_sum,
&mut alloc_flow,
&mut flat_alloc,
);
flow_step(
parent,
is_leaf,
is_subtree_leaf,
&rho,
&child_w,
&cw_sum,
&leaf_w,
&lw_sum,
&mut alloc_flow,
&mut flat_alloc,
);
flow_step(
parent,
is_leaf,
is_subtree_leaf,
&rho,
&child_w,
&cw_sum,
&leaf_w,
&lw_sum,
&mut alloc_flow,
&mut flat_alloc,
);
flow_step(
parent,
is_leaf,
is_subtree_leaf,
&rho,
&child_w,
&cw_sum,
&leaf_w,
&lw_sum,
&mut alloc_flow,
&mut flat_alloc,
);
flow_step(
parent,
is_leaf,
is_subtree_leaf,
&rho,
&child_w,
&cw_sum,
&leaf_w,
&lw_sum,
&mut alloc_flow,
&mut flat_alloc,
);
flow_step(
parent,
is_leaf,
is_subtree_leaf,
&rho,
&child_w,
&cw_sum,
&leaf_w,
&lw_sum,
&mut alloc_flow,
&mut flat_alloc,
);
flow_step(
parent,
is_leaf,
is_subtree_leaf,
&rho,
&child_w,
&cw_sum,
&leaf_w,
&lw_sum,
&mut alloc_flow,
&mut flat_alloc,
);
flow_step(
parent,
is_leaf,
is_subtree_leaf,
&rho,
&child_w,
&cw_sum,
&leaf_w,
&lw_sum,
&mut alloc_flow,
&mut flat_alloc,
);
let mut res = [NonNegativeFixed::ZERO; N];
unroll_8_static!(x, res[x & 7] = flat_alloc[x & 7] + alloc_flow[x & 7]);
res
}
#[inline(always)]
fn fixed_pow(mass: NonNegativeFixed, q_val: SignedFixed) -> NonNegativeFixed {
let log_m = mass.log2();
let exponent =
SignedFixed::from_bits((((q_val.val as i64).wrapping_mul(log_m.val as i64)) >> 16) as i32);
exponent.exp2()
}
#[inline(always)]
fn fixed_pow_per_node(
q_val: SignedFixed,
node_masses: &[[NonNegativeFixed; N]; K],
) -> [NonNegativeFixed; N] {
let mut mass_pow = [NonNegativeFixed::ZERO; N];
unroll_8_static!(i, {
mass_pow[i & 7] = fixed_pow(node_masses[MEASURE_CACHE][i & 7], q_val);
});
mass_pow
}
#[inline(never)]
fn compute_kappa(
v: usize,
mass_pow: &[NonNegativeFixed; N],
parent: &[i32; N],
is_subtree_leaf: &[[bool; N]; N],
) -> SignedFixed {
let mut sum_meas_den = NonNegativeFixed::ZERO;
unroll_8_static!(c, {
let is_child = parent[c & 7] == v as i32;
sum_meas_den +=
NonNegativeFixed::from_bits(const_select_u32(is_child as u32, mass_pow[c & 7].val, 0));
});
let mut sum_leaf_den = NonNegativeFixed::ZERO;
unroll_8_static!(x, {
let is_sub = is_subtree_leaf[v & 7][x & 7];
sum_leaf_den +=
NonNegativeFixed::from_bits(const_select_u32(is_sub as u32, mass_pow[x & 7].val, 0));
});
let mut kappa = SignedFixed::ZERO;
unroll_8_static!(c, {
let is_child = parent[c & 7] == v as i32;
let mut l_q_c = NonNegativeFixed::ZERO;
unroll_8_static!(x, {
let is_sub_c = is_subtree_leaf[c & 7][x & 7];
l_q_c += NonNegativeFixed::from_bits(const_select_u32(
is_sub_c as u32,
mass_pow[x & 7].val,
0,
));
});
let meas_den_is_zero = sum_meas_den.val == 0;
let s_meas = mass_pow[c & 7].saturating_div(sum_meas_den);
let s_leaf = l_q_c.saturating_div(sum_leaf_den);
let s_leaf_pos = s_leaf.val > 0;
let log_ratio = s_leaf.saturating_div(s_meas).log2();
let term = (((s_leaf.val as i64).wrapping_mul(log_ratio.val as i64)) >> 16) as i32;
let contribution = const_select_u32(
(is_child & s_leaf_pos & !meas_den_is_zero) as u32,
term as u32,
0,
) as i32;
kappa = SignedFixed::from_bits(kappa.val.wrapping_add(contribution));
});
kappa
}
#[cfg(test)]
mod kappa_saturation_tests {
use super::*;
fn to_fixed(v: f64) -> NonNegativeFixed {
NonNegativeFixed::from_bits((v * 65536.0).round() as u32)
}
fn to_signed(v: f64) -> SignedFixed {
SignedFixed::from_bits((v * 65536.0).round() as i32)
}
#[test]
fn fixed_pow_saturates_within_feasible_region_at_q_near_2() {
let q = to_signed(1.99);
let low = fixed_pow(to_fixed(300.0), q);
let high = fixed_pow(to_fixed(1000.0), q);
assert_eq!(
low.val,
NonNegativeFixed::MAX.val,
"expected mass=300 at q=1.99 to saturate to MAX (2^(16/1.99) ~= 263 < 300)"
);
assert_eq!(
high.val,
NonNegativeFixed::MAX.val,
"expected mass=1000 at q=1.99 to saturate to MAX"
);
assert_eq!(low.val, high.val);
}
#[test]
fn fixed_pow_underflows_within_feasible_region_at_q_near_2() {
let q = to_signed(1.99);
let near_floor = fixed_pow(to_fixed(0.000_092), q);
assert_eq!(
near_floor.val, 0,
"expected mass near feasible-region floor at q=1.99 to underflow to 0"
);
}
#[test]
fn compute_kappa_fails_safe_on_direct_child_measure_zero_zero() {
let mut parent = [-1i32; N];
parent[1] = 0;
parent[2] = 1;
let mut is_subtree_leaf = [[false; N]; N];
is_subtree_leaf[1][2] = true;
is_subtree_leaf[0][2] = true;
let q = to_signed(1.99);
let mut node_masses = [[NonNegativeFixed::ZERO; N]; K];
node_masses[MEASURE_CACHE][1] = to_fixed(0.000_092);
node_masses[MEASURE_CACHE][2] = to_fixed(10.0);
let mass_pow = fixed_pow_per_node(q, &node_masses);
let kappa = compute_kappa(0, &mass_pow, &parent, &is_subtree_leaf);
assert_eq!(
kappa.val, 0,
"0/0 s_meas must not inject a spurious divergence signal"
);
}
#[test]
fn compute_kappa_nonzero_for_non_degenerate_case() {
let mut parent = [-1i32; N];
parent[1] = 0;
parent[2] = 0;
parent[3] = 1;
parent[4] = 2;
let mut is_subtree_leaf = [[false; N]; N];
is_subtree_leaf[1][3] = true;
is_subtree_leaf[2][4] = true;
is_subtree_leaf[0][3] = true;
is_subtree_leaf[0][4] = true;
let q = to_signed(0.5);
let mut node_masses = [[NonNegativeFixed::ZERO; N]; K];
node_masses[MEASURE_CACHE][1] = to_fixed(5.0);
node_masses[MEASURE_CACHE][2] = to_fixed(5.0);
node_masses[MEASURE_CACHE][3] = to_fixed(1.0);
node_masses[MEASURE_CACHE][4] = to_fixed(100.0);
let mass_pow = fixed_pow_per_node(q, &node_masses);
let kappa = compute_kappa(0, &mass_pow, &parent, &is_subtree_leaf);
assert!(
kappa.val != 0,
"diverging subtree-leaf mass should produce a nonzero divergence signal"
);
}
}
mod feasible_region;
pub use feasible_region::FeasibleRegion;
#[allow(clippy::too_many_arguments)] #[allow(deprecated)] pub fn allocate_in(
region: &FeasibleRegion,
states: &[PackedSemanticState; N],
lenses: &[LensSpec; Q],
lambda: &[[NonNegativeFixed; Q]; K],
eta: NonNegativeFixed,
parent: &[i32; N],
weights: &mut [[NonNegativeFixed; 2 * Q]; N],
payoffs: &[[NonNegativeFixed; 2 * Q]; N],
zeta: NonNegativeFixed,
epsilon_kappa: NonNegativeFixed,
mu: &[NonNegativeFixed; N],
costs: &[NonNegativeFixed; N],
t: u32,
last_switch_t: &mut u32,
prev_mode: &mut u32,
tau_d: u32,
digest: [u8; 32],
proof: Option<&AdaptiveUpdate<CertifiedLearning>>,
) -> Result<[NonNegativeFixed; N], StabilityRefusal> {
let mut local_weights = *weights;
let mut local_last_switch_t = *last_switch_t;
let mut local_prev_mode = *prev_mode;
let beta_max = region.beta_max;
let m_min = region.m_min;
let m_max = region.m_max;
let mu_max = region.mu_max;
let proof_some = proof.is_some();
let degrade_to_certified_selection = proof.is_none();
let mut digest_match = 1u32;
unroll_32_static!(i, {
digest_match &= const_eq_u32(
digest[i & 31] as u32,
crate::generated::stability_profile::CERTIFICATE_DIGEST[i & 31] as u32,
);
});
let digest_err = const_eq_u32(digest_match, 0) != 0;
let mut gd_ok = true;
unroll_5_static!(i, {
let mut sum_g_d = 0u128;
unroll_5_static!(j, {
let g_raw = crate::generated::stability_profile::GAIN_MATRIX[i][j].raw as u128;
let d_raw = crate::generated::stability_profile::WEIGHT_VECTOR[j].raw as u128;
sum_g_d += g_raw * d_raw;
});
let lhs = sum_g_d / 1_000_000_000;
let d_i_raw = crate::generated::stability_profile::WEIGHT_VECTOR[i].raw as u128;
let delta_raw = crate::generated::stability_profile::CONTRACTION_MARGIN.raw as u128;
let rhs = d_i_raw - (delta_raw * d_i_raw / 1_000_000_000);
gd_ok &= lhs <= rhs;
});
let zeta_w_max_q16 =
((crate::generated::stability_profile::ZETA_W_MAX.raw * 65536) / 1_000_000_000) as u32;
let eta_g_min_q16 =
((crate::generated::stability_profile::ETA_G_MIN.raw * 65536) / 1_000_000_000) as u32;
let eta_g_max_q16 = NonNegativeFixed::ONE.val;
let lr_err = const_lt_u32(zeta_w_max_q16, zeta.val) != 0;
let dwell_err = const_lt_u32(
tau_d,
crate::generated::stability_profile::MODE_DWELL_ROUNDS_MIN,
) != 0;
let mut q_err = false;
unroll_4_static!(q_idx, {
let q_val = lenses[q_idx & 3].q.val;
q_err |= !(-131072..=131072).contains(&q_val);
});
let mut price_err = false;
unroll_8_static!(i, {
price_err |= const_lt_u32(mu_max.val, mu[i & 7].val) != 0;
});
let eta_err =
(const_lt_u32(eta.val, eta_g_min_q16) != 0) | (const_lt_u32(eta_g_max_q16, eta.val) != 0);
let is_zeta_less = const_lt_u32(zeta.val, beta_max.val);
let beta = NonNegativeFixed::from_bits(const_select_u32(is_zeta_less, zeta.val, beta_max.val));
let beta_m_max_q16 =
((crate::generated::stability_profile::BETA_M_MAX.raw * 65536) / 1_000_000_000) as u32;
let beta_err = const_lt_u32(beta_m_max_q16, beta.val) != 0;
let has_error =
!gd_ok | digest_err | lr_err | beta_err | eta_err | dwell_err | q_err | price_err;
let freeze_learning = has_error & degrade_to_certified_selection;
let mut is_leaf = [true; N];
unroll_8_static!(i, {
unroll_8_static!(j, {
let is_match = parent[j & 7] == i as i32;
is_leaf[i & 7] &= !is_match;
});
});
#[allow(non_snake_case)]
let P = ancestor_doubling_table(parent);
let mut has_cycle = false;
unroll_8_static!(j, {
has_cycle |= P[7][j] != -1;
});
#[allow(non_snake_case)]
let P_bb = core::hint::black_box(P);
let mut is_descendant = [[false; N]; N];
unroll_8_static!(i, {
unroll_8_static!(j, {
let mut matched = const_eq_u32(j as u32, i as u32);
unroll_8_static!(level, {
matched |= const_eq_u32(P_bb[level][j] as u32, i as u32);
});
is_descendant[i][j] = matched != 0;
});
});
let is_descendant = core::hint::black_box(is_descendant);
let mut is_subtree_leaf = [[false; N]; N];
unroll_8_static!(i, {
unroll_8_static!(k, {
is_subtree_leaf[i & 7][k & 7] = is_leaf[k & 7] & is_descendant[i & 7][k & 7];
});
});
let mut node_masses = [[NonNegativeFixed::ZERO; N]; K];
unroll_8_static!(i, {
let state = &states[i & 7];
let f_recomp = state.factors[FACTOR_RECOMPUTATION_COST];
let f_verify = state.factors[FACTOR_VERIFICATION_COST];
let f_stand = state.factors[FACTOR_STANDING];
let f_access = state.factors[FACTOR_ACCESS_FREQUENCY];
let f_search = state.factors[FACTOR_SEARCH_DEMAND];
let f_retrieve = state.factors[FACTOR_RETRIEVAL_DEMAND];
let f_sched = state.factors[FACTOR_SCHEDULING_DEMAND];
let f_bval = state.factors[FACTOR_BUSINESS_VALUE];
let f_conseq = state.factors[FACTOR_DOWNSTREAM_CONSEQUENCE];
let m_cache = (f_recomp * NonNegativeFixed::from_num(5) + f_verify) * f_access * f_stand;
let m_search = (f_bval + f_conseq) * f_search * f_stand;
let m_retrieval = f_bval * f_retrieve;
let m_sched = f_bval * f_sched;
node_masses[MEASURE_CACHE][i & 7] = m_cache;
node_masses[MEASURE_RETRIEVAL][i & 7] = m_retrieval;
node_masses[MEASURE_SCHEDULING][i & 7] = m_sched;
node_masses[MEASURE_SEARCH][i & 7] = m_search;
});
unroll_4_static!(k, {
unroll_8_static!(i, {
node_masses[k & 3][i & 7] = clip(node_masses[k & 3][i & 7], m_min, m_max);
});
});
let mut root_idx = 0usize;
unroll_8_static!(i, {
let is_root = parent[i & 7] == -1;
root_idx = const_select_u32(is_root as u32, i as u32, root_idx as u32) as usize;
});
let mut root_weights = [NonNegativeFixed::ZERO; 2 * Q];
unroll_8_static!(idx, {
let matches = const_eq_u32(root_idx as u32, idx as u32);
unroll_8_static!(e, {
root_weights[e & 7] = NonNegativeFixed::from_bits(const_select_u32(
matches,
local_weights[idx & 7][e & 7].val,
root_weights[e & 7].val,
));
});
});
let mut max_w = NonNegativeFixed::ZERO;
let mut dom_mode = 0u32;
unroll_8_static!(e, {
let w = root_weights[e & 7];
let is_greater = const_lt_u32(max_w.val, w.val);
max_w = NonNegativeFixed::from_bits(const_select_u32(is_greater, w.val, max_w.val));
dom_mode = const_select_u32(is_greater, e as u32, dom_mode);
});
let switch_wanted = dom_mode != local_prev_mode;
let can_switch = t.wrapping_sub(local_last_switch_t) >= tau_d;
let update_allowed = !(switch_wanted & !can_switch) & !freeze_learning & proof_some;
let mut mass_pow_by_q = [[NonNegativeFixed::ZERO; N]; Q];
unroll_4_static!(q_idx, {
let mut q_val_mutated = SignedFixed::from_bits(lenses[q_idx & 3].q.val);
#[cfg(feature = "mutant_2")]
{
q_val_mutated = SignedFixed::from_bits(0i32.wrapping_sub(q_val_mutated.val));
}
mass_pow_by_q[q_idx & 3] = fixed_pow_per_node(q_val_mutated, &node_masses);
});
unroll_8_static!(v, {
let has_children = !is_leaf[v & 7];
let mut is_subtree_leaf_v = [false; N];
unroll_8_static!(x, {
is_subtree_leaf_v[x] = is_subtree_leaf[v & 7][x & 7];
});
unroll_4_static!(q_idx, {
let w_flat = local_weights[v & 7][(2 * q_idx) & 7];
let w_desc = local_weights[v & 7][(2 * q_idx + 1) & 7];
let kappa = compute_kappa(v, &mass_pow_by_q[q_idx & 3], parent, &is_subtree_leaf);
let kappa_exceeds = kappa.val > (epsilon_kappa.val as i32);
let is_updating = has_children & update_allowed & kappa_exceeds;
local_weights[v & 7][(2 * q_idx) & 7] = NonNegativeFixed::from_bits(const_select_u32(
is_updating as u32,
(w_flat
* SignedFixed::from_bits((beta * payoffs[v & 7][(2 * q_idx) & 7]).val as i32)
.exp())
.val,
w_flat.val,
));
local_weights[v & 7][(2 * q_idx + 1) & 7] =
NonNegativeFixed::from_bits(const_select_u32(
is_updating as u32,
(w_desc
* SignedFixed::from_bits(
(beta * payoffs[v & 7][(2 * q_idx + 1) & 7]).val as i32,
)
.exp())
.val,
w_desc.val,
));
});
unroll_4_static!(q_idx, {
let w_flat = local_weights[v & 7][(2 * q_idx) & 7];
let w_desc = local_weights[v & 7][(2 * q_idx + 1) & 7];
let sum_div = w_flat + w_desc;
local_weights[v & 7][(2 * q_idx) & 7] = NonNegativeFixed::from_bits(const_select_u32(
update_allowed as u32,
w_flat.saturating_div(sum_div).val,
w_flat.val,
));
local_weights[v & 7][(2 * q_idx + 1) & 7] =
NonNegativeFixed::from_bits(const_select_u32(
update_allowed as u32,
w_desc.saturating_div(sum_div).val,
w_desc.val,
));
});
});
let mut new_dom_mode = 0u32;
let mut new_max_w = NonNegativeFixed::ZERO;
unroll_8_static!(idx, {
let matches = const_eq_u32(root_idx as u32, idx as u32);
unroll_8_static!(e, {
root_weights[e & 7] = NonNegativeFixed::from_bits(const_select_u32(
matches,
local_weights[idx & 7][e & 7].val,
root_weights[e & 7].val,
));
});
});
unroll_8_static!(e, {
let w = root_weights[e & 7];
let is_greater = const_lt_u32(new_max_w.val, w.val);
new_max_w = NonNegativeFixed::from_bits(const_select_u32(is_greater, w.val, new_max_w.val));
new_dom_mode = const_select_u32(is_greater, e as u32, new_dom_mode);
});
let did_switch = (new_dom_mode != local_prev_mode) & can_switch & !freeze_learning & proof_some;
local_last_switch_t = const_select_u32(did_switch as u32, t, local_last_switch_t);
local_prev_mode = const_select_u32(did_switch as u32, new_dom_mode, local_prev_mode);
let mut pi_kq = [[[NonNegativeFixed::ZERO; N]; Q]; K];
unroll_4_static!(k, {
#[cfg(feature = "mutant_1")]
const k_actual: usize = 0;
#[cfg(not(feature = "mutant_1"))]
const k_actual: usize = k;
unroll_4_static!(q_idx, {
let q_val_mutated = SignedFixed::from_bits(lenses[q_idx & 3].q.val);
#[cfg(feature = "mutant_2")]
let q_val_mutated = SignedFixed::from_bits(0i32.wrapping_sub(q_val_mutated.val));
let res_kq = compute_pi_kq_for_kq(
k_actual,
q_idx,
q_val_mutated,
parent,
&is_leaf,
&is_subtree_leaf,
&node_masses,
&local_weights,
);
unroll_8_static!(x, pi_kq[k & 3][q_idx & 3][x & 7] = res_kq[x & 7]);
});
});
let mut pi_combined = [NonNegativeFixed::ZERO; N];
unroll_4_static!(k, {
unroll_4_static!(q_idx, {
unroll_8_static!(x, {
let term = lambda[k & 3][q_idx & 3] * pi_kq[k & 3][q_idx & 3][x & 7];
pi_combined[x & 7] += term;
});
});
});
let mut pi_res = [NonNegativeFixed::ZERO; N];
let mut priced_sum = NonNegativeFixed::ZERO;
unroll_8_static!(x, {
#[cfg(feature = "mutant_5")]
let mu_actual = mu_max;
#[cfg(not(feature = "mutant_5"))]
let mu_actual = clip(mu[x & 7], NonNegativeFixed::ZERO, mu_max);
let p = pi_combined[x & 7]
* SignedFixed::from_bits(0i32.wrapping_sub((mu_actual * costs[x & 7]).val as i32))
.exp();
priced_sum +=
NonNegativeFixed::from_bits(const_select_u32(is_leaf[x & 7] as u32, p.val, 0));
});
let psd = NonNegativeFixed::from_bits(const_select_u32(
const_eq_u32(priced_sum.val, 0),
NonNegativeFixed::ONE.val,
priced_sum.val,
));
let mut nl = 0u32;
unroll_8_static!(i, {
nl += is_leaf[i & 7] as u32;
});
unroll_8_static!(x, {
#[cfg(feature = "mutant_5")]
let mu_actual = mu_max;
#[cfg(not(feature = "mutant_5"))]
let mu_actual = clip(mu[x & 7], NonNegativeFixed::ZERO, mu_max);
let p_mu = (pi_combined[x & 7]
* SignedFixed::from_bits(0i32.wrapping_sub((mu_actual * costs[x & 7]).val as i32))
.exp())
.saturating_div(psd);
#[cfg(feature = "mutant_4")]
let eta_actual = zeta;
#[cfg(not(feature = "mutant_4"))]
let eta_actual = eta;
let mut nl_recip = NonNegativeFixed::ZERO;
unroll_9_static!(idx, {
let matches = const_eq_u32(nl, idx as u32);
nl_recip = NonNegativeFixed::from_bits(const_select_u32(
matches,
LEAF_RECIP[idx].val,
nl_recip.val,
));
});
let val = (eta_actual * nl_recip) + ((NonNegativeFixed::ONE - eta_actual) * p_mu);
let pi_val = pi_res[x & 7];
pi_res[x & 7] = NonNegativeFixed::from_bits(const_select_u32(
is_leaf[x & 7] as u32,
val.val,
pi_val.val,
));
});
let mut numeric_err = u32::MAX;
unroll_8_static!(x, {
numeric_err = crate::fixed::branchless_err_acc(numeric_err, pi_res[x & 7].err);
});
let numeric_has_err = const_eq_u32(numeric_err, u32::MAX) == 0;
let has_error = has_error | has_cycle;
let selection_critical_error = q_err | price_err | eta_err | numeric_has_err;
let has_refusal = selection_critical_error | (has_error & !degrade_to_certified_selection);
unroll_8_static!(v, {
unroll_8_static!(e, {
weights[v & 7][e & 7] = NonNegativeFixed::from_bits(const_select_u32(
has_refusal as u32,
weights[v & 7][e & 7].val,
local_weights[v & 7][e & 7].val,
));
});
});
*last_switch_t = const_select_u32(has_refusal as u32, *last_switch_t, local_last_switch_t);
*prev_mode = const_select_u32(has_refusal as u32, *prev_mode, local_prev_mode);
let err_val = const_select_u32(
has_cycle as u32,
StabilityRefusal::ContractViolation as u32,
const_select_u32(
q_err as u32,
5,
const_select_u32(
dwell_err as u32,
4,
const_select_u32(
price_err as u32,
StabilityRefusal::PriceGainUnsafe as u32,
const_select_u32(
eta_err as u32,
StabilityRefusal::ExploreFloorOutsideEnvelope as u32,
const_select_u32(
(lr_err | beta_err) as u32,
3,
const_select_u32(
(!gd_ok) as u32,
1,
const_select_u32(
digest_err as u32,
10,
const_select_u32(numeric_has_err as u32, numeric_err, 7),
),
),
),
),
),
),
),
);
wrap_result(
pi_res,
const_select_u32(has_refusal as u32, err_val, u32::MAX),
)
}
#[allow(clippy::too_many_arguments)] #[allow(deprecated)] pub fn allocate(
states: &[PackedSemanticState; N],
lenses: &[LensSpec; Q],
lambda: &[[NonNegativeFixed; Q]; K],
eta: NonNegativeFixed,
parent: &[i32; N],
weights: &mut [[NonNegativeFixed; 2 * Q]; N],
payoffs: &[[NonNegativeFixed; 2 * Q]; N],
zeta: NonNegativeFixed,
epsilon_kappa: NonNegativeFixed,
mu: &[NonNegativeFixed; N],
costs: &[NonNegativeFixed; N],
t: u32,
last_switch_t: &mut u32,
prev_mode: &mut u32,
tau_d: u32,
digest: [u8; 32],
proof: Option<&AdaptiveUpdate<CertifiedLearning>>,
) -> Result<[NonNegativeFixed; N], StabilityRefusal> {
allocate_in(
&FeasibleRegion::CURRENT,
states,
lenses,
lambda,
eta,
parent,
weights,
payoffs,
zeta,
epsilon_kappa,
mu,
costs,
t,
last_switch_t,
prev_mode,
tau_d,
digest,
proof,
)
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum LensSelectionRefusal {
MeasureIndexOutOfRange { measure: usize },
LensIndexOutOfRange { lens_idx: usize },
QMagnitudeExceeded { q: SignedFixed },
Cyclic,
}
impl core::fmt::Display for LensSelectionRefusal {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
core::fmt::Debug::fmt(self, f)
}
}
#[cfg(feature = "std")]
impl std::error::Error for LensSelectionRefusal {}
pub fn allocate_single_lens(
states: &[PackedSemanticState; N],
lenses: &[LensSpec; Q],
measure: usize,
lens_idx: usize,
parent: &[i32; N],
weights: &[[NonNegativeFixed; 2 * Q]; N],
) -> Result<[NonNegativeFixed; N], LensSelectionRefusal> {
if measure >= K {
return Err(LensSelectionRefusal::MeasureIndexOutOfRange { measure });
}
if lens_idx >= Q {
return Err(LensSelectionRefusal::LensIndexOutOfRange { lens_idx });
}
let q = lenses[lens_idx].q;
if q.to_bits().unsigned_abs() > crate::generated_profile::MAX_LENS_MAGNITUDE << 16 {
return Err(LensSelectionRefusal::QMagnitudeExceeded { q });
}
if check_hierarchy_acyclic(parent).is_err() {
return Err(LensSelectionRefusal::Cyclic);
}
let region = &FeasibleRegion::CURRENT;
let m_min = region.m_min;
let m_max = region.m_max;
let mut is_leaf = [true; N];
unroll_8_static!(i, {
unroll_8_static!(j, {
let is_match = parent[j & 7] == i as i32;
is_leaf[i & 7] &= !is_match;
});
});
#[allow(non_snake_case)]
let P = ancestor_doubling_table(parent);
#[allow(non_snake_case)]
let P_bb = core::hint::black_box(P);
let mut is_descendant = [[false; N]; N];
unroll_8_static!(i, {
unroll_8_static!(j, {
let mut matched = const_eq_u32(j as u32, i as u32);
unroll_8_static!(level, {
matched |= const_eq_u32(P_bb[level][j] as u32, i as u32);
});
is_descendant[i][j] = matched != 0;
});
});
let is_descendant = core::hint::black_box(is_descendant);
let mut is_subtree_leaf = [[false; N]; N];
unroll_8_static!(i, {
unroll_8_static!(k, {
is_subtree_leaf[i & 7][k & 7] = is_leaf[k & 7] & is_descendant[i & 7][k & 7];
});
});
let mut node_masses = [[NonNegativeFixed::ZERO; N]; K];
unroll_8_static!(i, {
let state = &states[i & 7];
let f_recomp = state.factors[FACTOR_RECOMPUTATION_COST];
let f_verify = state.factors[FACTOR_VERIFICATION_COST];
let f_stand = state.factors[FACTOR_STANDING];
let f_access = state.factors[FACTOR_ACCESS_FREQUENCY];
let f_search = state.factors[FACTOR_SEARCH_DEMAND];
let f_retrieve = state.factors[FACTOR_RETRIEVAL_DEMAND];
let f_sched = state.factors[FACTOR_SCHEDULING_DEMAND];
let f_bval = state.factors[FACTOR_BUSINESS_VALUE];
let f_conseq = state.factors[FACTOR_DOWNSTREAM_CONSEQUENCE];
let m_cache = (f_recomp * NonNegativeFixed::from_num(5) + f_verify) * f_access * f_stand;
let m_search = (f_bval + f_conseq) * f_search * f_stand;
let m_retrieval = f_bval * f_retrieve;
let m_sched = f_bval * f_sched;
node_masses[MEASURE_CACHE][i & 7] = m_cache;
node_masses[MEASURE_RETRIEVAL][i & 7] = m_retrieval;
node_masses[MEASURE_SCHEDULING][i & 7] = m_sched;
node_masses[MEASURE_SEARCH][i & 7] = m_search;
});
unroll_4_static!(k, {
unroll_8_static!(i, {
node_masses[k & 3][i & 7] = clip(node_masses[k & 3][i & 7], m_min, m_max);
});
});
Ok(compute_pi_kq_for_kq(
measure,
lens_idx,
q,
parent,
&is_leaf,
&is_subtree_leaf,
&node_masses,
weights,
))
}
pub struct AuthorityCompileFailTests;