#![no_std]
#![forbid(unsafe_code)]
pub const CONTRACT_JOURNEY_ID: &str = "J-CORE-TEST-MATRIX";
pub const OLD_WRONG_CORE_GUARD: &str = "God-spec implementation with no enforceable contracts";
pub const CCF_CORE_V1_VERSION: &str = env!("CARGO_PKG_VERSION");
pub mod qac {
pub const QAC_JOURNEY_ID: &str = "J-QAC-REFERENCE";
pub const QAC_STORY_ID: &str = "CCFV1-01";
pub const SCALAR_ACCUMULATOR_OLD_WRONG_PATH: &str = "Scalar accumulator update";
pub const ARITHMETIC_INTERPOLATION_OLD_WRONG_PATH: &str = "Arithmetic interpolation regression";
pub const MISSING_POSITIVE_DIAGONAL_GAUGE_OLD_WRONG_PATH: &str =
"Missing positive diagonal gauges";
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Matrix3 {
pub entries: [[f64; 3]; 3],
}
impl Matrix3 {
pub const fn new(entries: [[f64; 3]; 3]) -> Self {
Self { entries }
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PositiveDiagonal3 {
diagonal: [f64; 3],
}
impl PositiveDiagonal3 {
pub fn try_new(diagonal: [f64; 3]) -> Result<Self, QacError> {
if diagonal
.iter()
.all(|entry| entry.is_finite() && *entry > 0.0)
{
Ok(Self { diagonal })
} else {
Err(QacError::NonPositiveGauge)
}
}
pub const fn diagonal(self) -> [f64; 3] {
self.diagonal
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct QacInputs3 {
pub prior_a_t: Matrix3,
pub reference_r_t: Matrix3,
pub left_l_t: PositiveDiagonal3,
pub right_c_t: PositiveDiagonal3,
pub alpha_t: f64,
pub epsilon_floor: f64,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct NegativeGuardReport {
pub old_wrong_path: &'static str,
pub rejected: bool,
pub kappa_excursion: f64,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum QacError {
NonPositiveEntry,
NonPositiveGauge,
InvalidAlpha,
}
pub fn qac_update_3x3(inputs: &QacInputs3) -> Result<Matrix3, QacError> {
validate_inputs(inputs)?;
let mut entries = [[0.0_f64; 3]; 3];
for (row, output_row) in entries.iter_mut().enumerate() {
for (col, output) in output_row.iter_mut().enumerate() {
let prior = inputs.prior_a_t.entries[row][col];
let reference = inputs.reference_r_t.entries[row][col];
let log_geodesic = libm::exp(
(1.0 - inputs.alpha_t) * libm::log(prior)
+ inputs.alpha_t * libm::log(reference),
);
*output =
inputs.left_l_t.diagonal[row] * log_geodesic * inputs.right_c_t.diagonal[col];
}
}
Ok(Matrix3::new(entries))
}
pub fn reject_arithmetic_interpolation_regression(
inputs: &QacInputs3,
) -> Result<NegativeGuardReport, QacError> {
validate_inputs(inputs)?;
let canonical = qac_update_3x3(inputs)?;
let mut substitute = [[0.0_f64; 3]; 3];
for (row, output_row) in substitute.iter_mut().enumerate() {
for (col, output) in output_row.iter_mut().enumerate() {
let prior = inputs.prior_a_t.entries[row][col];
let reference = inputs.reference_r_t.entries[row][col];
let interpolated = (1.0 - inputs.alpha_t) * prior + inputs.alpha_t * reference;
*output =
inputs.left_l_t.diagonal[row] * interpolated * inputs.right_c_t.diagonal[col];
}
}
let kappa_excursion = max_abs_diff(Matrix3::new(substitute), canonical);
Ok(NegativeGuardReport {
old_wrong_path: ARITHMETIC_INTERPOLATION_OLD_WRONG_PATH,
rejected: kappa_excursion > inputs.epsilon_floor,
kappa_excursion,
})
}
pub fn reject_scalar_accumulator_update(
inputs: &QacInputs3,
) -> Result<NegativeGuardReport, QacError> {
validate_inputs(inputs)?;
let canonical = qac_update_3x3(inputs)?;
let prior_mean = matrix_mean(inputs.prior_a_t);
let reference_mean = matrix_mean(inputs.reference_r_t);
let scalar = (1.0 - inputs.alpha_t) * prior_mean + inputs.alpha_t * reference_mean;
let substitute = Matrix3::new([[scalar; 3]; 3]);
let kappa_excursion = max_abs_diff(substitute, canonical);
Ok(NegativeGuardReport {
old_wrong_path: SCALAR_ACCUMULATOR_OLD_WRONG_PATH,
rejected: kappa_excursion > inputs.epsilon_floor,
kappa_excursion,
})
}
pub fn reject_missing_positive_diagonal_gauge(
inputs: &QacInputs3,
) -> Result<NegativeGuardReport, QacError> {
validate_inputs(inputs)?;
let canonical = qac_update_3x3(inputs)?;
let mut substitute = [[0.0_f64; 3]; 3];
for (row, output_row) in substitute.iter_mut().enumerate() {
for (col, output) in output_row.iter_mut().enumerate() {
let prior = inputs.prior_a_t.entries[row][col];
let reference = inputs.reference_r_t.entries[row][col];
*output = libm::exp(
(1.0 - inputs.alpha_t) * libm::log(prior)
+ inputs.alpha_t * libm::log(reference),
);
}
}
let kappa_excursion = max_abs_diff(Matrix3::new(substitute), canonical);
Ok(NegativeGuardReport {
old_wrong_path: MISSING_POSITIVE_DIAGONAL_GAUGE_OLD_WRONG_PATH,
rejected: kappa_excursion > inputs.epsilon_floor,
kappa_excursion,
})
}
fn validate_inputs(inputs: &QacInputs3) -> Result<(), QacError> {
if !inputs.alpha_t.is_finite() || !(0.0..=1.0).contains(&inputs.alpha_t) {
return Err(QacError::InvalidAlpha);
}
if !inputs.epsilon_floor.is_finite() || inputs.epsilon_floor <= 0.0 {
return Err(QacError::NonPositiveEntry);
}
validate_strict_positive_matrix(inputs.prior_a_t, inputs.epsilon_floor)?;
validate_strict_positive_matrix(inputs.reference_r_t, inputs.epsilon_floor)?;
validate_positive_diagonal(inputs.left_l_t)?;
validate_positive_diagonal(inputs.right_c_t)?;
Ok(())
}
fn validate_positive_diagonal(diagonal: PositiveDiagonal3) -> Result<(), QacError> {
if diagonal
.diagonal()
.iter()
.all(|entry| entry.is_finite() && *entry > 0.0)
{
Ok(())
} else {
Err(QacError::NonPositiveGauge)
}
}
fn validate_strict_positive_matrix(
matrix: Matrix3,
epsilon_floor: f64,
) -> Result<(), QacError> {
for row in matrix.entries {
for entry in row {
if !entry.is_finite() || entry <= epsilon_floor {
return Err(QacError::NonPositiveEntry);
}
}
}
Ok(())
}
fn max_abs_diff(left: Matrix3, right: Matrix3) -> f64 {
let mut max = 0.0_f64;
for row in 0..3 {
for col in 0..3 {
max = max.max((left.entries[row][col] - right.entries[row][col]).abs());
}
}
max
}
fn matrix_mean(matrix: Matrix3) -> f64 {
let mut total = 0.0_f64;
for row in matrix.entries {
for entry in row {
total += entry;
}
}
total / 9.0
}
}
pub mod min_gate {
const WEIGHTED_AVERAGE_INSTANT_WEIGHT: f64 = 0.3;
const WEIGHTED_AVERAGE_CONTEXT_WEIGHT: f64 = 0.7;
const SOFT_MIN_TEMPERATURE: f64 = 0.25;
const CONSTANT_ALPHA: f64 = 0.35;
pub const MIN_GATE_JOURNEY_ID: &str = "J-MIN-GATE-EXACT";
pub const MIN_GATE_STORY_ID: &str = "CCFV1-02";
pub const WEIGHTED_AVERAGE_GATE_OLD_WRONG_PATH: &str = "Weighted-average gate";
pub const SOFT_MIN_GATE_OLD_WRONG_PATH: &str = "Soft-min gate";
pub const CONSTANT_ALPHA_OLD_WRONG_PATH: &str = "Constant alpha as canonical";
pub const PER_ELEMENT_ALPHA_OLD_WRONG_PATH: &str = "Per-element alpha";
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RhoConfig {
alpha_min: f64,
alpha_max: f64,
}
impl RhoConfig {
pub fn try_new(alpha_min: f64, alpha_max: f64) -> Result<Self, MinGateError> {
if alpha_min.is_finite()
&& alpha_max.is_finite()
&& alpha_min >= 0.0
&& alpha_min <= alpha_max
&& alpha_max <= 1.0
{
Ok(Self {
alpha_min,
alpha_max,
})
} else {
Err(MinGateError::InvalidRhoConfig)
}
}
pub const fn alpha_min(self) -> f64 {
self.alpha_min
}
pub const fn alpha_max(self) -> f64 {
self.alpha_max
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MinGateInputs {
pub c_inst: f64,
pub c_ctx: f64,
pub rho: RhoConfig,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MinGateReport {
pub g_t: f64,
pub alpha_t: f64,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MinGateNegativeGuardReport {
pub old_wrong_path: &'static str,
pub rejected: bool,
pub canonical_g_t: f64,
pub observed_g_t: f64,
pub canonical_alpha_t: f64,
pub observed_alpha_t: f64,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MinGateError {
NotImplemented,
InvalidCeiling,
InvalidRhoConfig,
}
pub fn hard_min_gate_step(inputs: &MinGateInputs) -> Result<MinGateReport, MinGateError> {
validate_inputs(inputs)?;
let g_t = hard_min(inputs.c_inst, inputs.c_ctx);
Ok(MinGateReport {
g_t,
alpha_t: rho(inputs.rho, g_t),
})
}
pub fn reject_weighted_average_gate(
inputs: &MinGateInputs,
) -> Result<MinGateNegativeGuardReport, MinGateError> {
validate_inputs(inputs)?;
let observed_g_t = WEIGHTED_AVERAGE_INSTANT_WEIGHT * inputs.c_inst
+ WEIGHTED_AVERAGE_CONTEXT_WEIGHT * inputs.c_ctx;
Ok(negative_gate_report(
inputs,
WEIGHTED_AVERAGE_GATE_OLD_WRONG_PATH,
observed_g_t,
rho(inputs.rho, observed_g_t),
))
}
pub fn reject_soft_min_gate(
inputs: &MinGateInputs,
) -> Result<MinGateNegativeGuardReport, MinGateError> {
validate_inputs(inputs)?;
let observed_g_t = soft_min(inputs.c_inst, inputs.c_ctx);
Ok(negative_gate_report(
inputs,
SOFT_MIN_GATE_OLD_WRONG_PATH,
observed_g_t,
rho(inputs.rho, observed_g_t),
))
}
pub fn reject_constant_alpha(
inputs: &MinGateInputs,
) -> Result<MinGateNegativeGuardReport, MinGateError> {
validate_inputs(inputs)?;
let canonical_g_t = hard_min(inputs.c_inst, inputs.c_ctx);
Ok(negative_gate_report(
inputs,
CONSTANT_ALPHA_OLD_WRONG_PATH,
canonical_g_t,
CONSTANT_ALPHA,
))
}
pub fn reject_per_element_alpha(
inputs: &MinGateInputs,
) -> Result<MinGateNegativeGuardReport, MinGateError> {
validate_inputs(inputs)?;
let observed_g_t = inputs.c_inst.max(inputs.c_ctx);
Ok(negative_gate_report(
inputs,
PER_ELEMENT_ALPHA_OLD_WRONG_PATH,
observed_g_t,
rho(inputs.rho, observed_g_t),
))
}
fn validate_inputs(inputs: &MinGateInputs) -> Result<(), MinGateError> {
validate_ceiling(inputs.c_inst)?;
validate_ceiling(inputs.c_ctx)?;
RhoConfig::try_new(inputs.rho.alpha_min(), inputs.rho.alpha_max())?;
Ok(())
}
fn validate_ceiling(ceiling: f64) -> Result<(), MinGateError> {
if ceiling.is_finite() && (0.0..=1.0).contains(&ceiling) {
Ok(())
} else {
Err(MinGateError::InvalidCeiling)
}
}
fn hard_min(c_inst: f64, c_ctx: f64) -> f64 {
c_inst.min(c_ctx)
}
fn rho(config: RhoConfig, g_t: f64) -> f64 {
config.alpha_min() + (config.alpha_max() - config.alpha_min()) * g_t
}
fn soft_min(c_inst: f64, c_ctx: f64) -> f64 {
let x = -c_inst / SOFT_MIN_TEMPERATURE;
let y = -c_ctx / SOFT_MIN_TEMPERATURE;
let max = x.max(y);
-SOFT_MIN_TEMPERATURE * (max + libm::log(libm::exp(x - max) + libm::exp(y - max)))
}
fn negative_gate_report(
inputs: &MinGateInputs,
old_wrong_path: &'static str,
observed_g_t: f64,
observed_alpha_t: f64,
) -> MinGateNegativeGuardReport {
let canonical_g_t = hard_min(inputs.c_inst, inputs.c_ctx);
let canonical_alpha_t = rho(inputs.rho, canonical_g_t);
MinGateNegativeGuardReport {
old_wrong_path,
rejected: observed_g_t.to_bits() != canonical_g_t.to_bits()
|| observed_alpha_t.to_bits() != canonical_alpha_t.to_bits(),
canonical_g_t,
observed_g_t,
canonical_alpha_t,
observed_alpha_t,
}
}
}
pub mod sinkhorn {
use super::qac::{qac_update_3x3, Matrix3, QacInputs3};
const SIZE: usize = 3;
const SINKHORN_ITERATIONS: usize = 200;
pub const SINKHORN_GAUGE_JOURNEY_ID: &str = "J-SINKHORN-GAUGE-ONLY";
pub const SINKHORN_GAUGE_STORY_ID: &str = "CCFV1-03";
pub const SINKHORN_CAUSAL_DYNAMICS_OLD_WRONG_PATH: &str =
"Sinkhorn/Birkhoff as causal trust dynamics";
pub const FORCED_BIRKHOFF_CANONICAL_STATE_OLD_WRONG_PATH: &str =
"Forced Birkhoff canonical state";
pub const MUTATING_CANONICAL_PRESENTATION_OLD_WRONG_PATH: &str =
"Mutating canonical state through presentation";
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SinkhornGaugeInputs3 {
pub canonical_state: Matrix3,
pub qac_inputs: QacInputs3,
pub tolerance: f64,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SinkhornPresentationReport {
pub presentation: Matrix3,
pub row_sum_max_error: f64,
pub column_sum_max_error: f64,
pub quotient_state_delta: f64,
pub kappa_delta: f64,
pub canonical_state_preserved: bool,
pub strict_positive_canonical: bool,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SinkhornNegativeGuardReport {
pub old_wrong_path: &'static str,
pub rejected: bool,
pub canonical_state_delta: f64,
pub quotient_state_delta: f64,
pub kappa_delta: f64,
pub canonical_mutated: bool,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SinkhornGaugeError {
NotImplemented,
InvalidCanonicalState,
InvalidTolerance,
}
pub fn present_sinkhorn_gauge_only(
inputs: &SinkhornGaugeInputs3,
) -> Result<SinkhornPresentationReport, SinkhornGaugeError> {
validate_inputs(inputs)?;
let presentation = sinkhorn_presentation(inputs.canonical_state);
let canonical_quotient = quotient_state(inputs.canonical_state)?;
let presentation_quotient = quotient_state(presentation)?;
let quotient_state_delta = max_abs_diff(canonical_quotient, presentation_quotient);
let kappa_before = max_abs(canonical_quotient);
let kappa_after = max_abs(presentation_quotient);
Ok(SinkhornPresentationReport {
presentation,
row_sum_max_error: max_unit_sum_error(row_sums(presentation)),
column_sum_max_error: max_unit_sum_error(column_sums(presentation)),
quotient_state_delta,
kappa_delta: (kappa_after - kappa_before).abs(),
canonical_state_preserved: canonical_state_preserved(inputs),
strict_positive_canonical: is_strict_positive_matrix(
inputs.canonical_state,
inputs.qac_inputs.epsilon_floor,
),
})
}
pub fn reject_sinkhorn_as_causal_dynamics(
inputs: &SinkhornGaugeInputs3,
) -> Result<SinkhornNegativeGuardReport, SinkhornGaugeError> {
negative_guard_report(inputs, SINKHORN_CAUSAL_DYNAMICS_OLD_WRONG_PATH)
}
pub fn reject_forced_birkhoff_canonical_state(
inputs: &SinkhornGaugeInputs3,
) -> Result<SinkhornNegativeGuardReport, SinkhornGaugeError> {
negative_guard_report(inputs, FORCED_BIRKHOFF_CANONICAL_STATE_OLD_WRONG_PATH)
}
pub fn reject_mutating_canonical_state_through_presentation(
inputs: &SinkhornGaugeInputs3,
) -> Result<SinkhornNegativeGuardReport, SinkhornGaugeError> {
negative_guard_report(inputs, MUTATING_CANONICAL_PRESENTATION_OLD_WRONG_PATH)
}
fn validate_inputs(inputs: &SinkhornGaugeInputs3) -> Result<(), SinkhornGaugeError> {
if !inputs.tolerance.is_finite() || inputs.tolerance <= 0.0 {
return Err(SinkhornGaugeError::InvalidTolerance);
}
if !is_strict_positive_matrix(inputs.canonical_state, inputs.qac_inputs.epsilon_floor) {
return Err(SinkhornGaugeError::InvalidCanonicalState);
}
let expected = qac_update_3x3(&inputs.qac_inputs)
.map_err(|_| SinkhornGaugeError::InvalidCanonicalState)?;
if max_abs_diff(inputs.canonical_state, expected) > inputs.tolerance {
return Err(SinkhornGaugeError::InvalidCanonicalState);
}
Ok(())
}
fn is_strict_positive_matrix(matrix: Matrix3, epsilon_floor: f64) -> bool {
matrix.entries.iter().all(|row| {
row.iter()
.all(|entry| entry.is_finite() && *entry > epsilon_floor)
})
}
fn canonical_state_preserved(inputs: &SinkhornGaugeInputs3) -> bool {
qac_update_3x3(&inputs.qac_inputs)
.map(|expected| max_abs_diff(inputs.canonical_state, expected) <= inputs.tolerance)
.unwrap_or(false)
}
fn sinkhorn_presentation(matrix: Matrix3) -> Matrix3 {
let mut entries = matrix.entries;
for _ in 0..SINKHORN_ITERATIONS {
for row in 0..SIZE {
let sum = entries[row]
.iter()
.fold(0.0_f64, |total, entry| total + *entry);
let scale = 1.0 / sum;
for col in 0..SIZE {
entries[row][col] *= scale;
}
}
for col in 0..SIZE {
let sum = (0..SIZE).fold(0.0_f64, |total, row| total + entries[row][col]);
let scale = 1.0 / sum;
for row in 0..SIZE {
entries[row][col] *= scale;
}
}
}
Matrix3::new(entries)
}
fn quotient_state(matrix: Matrix3) -> Result<Matrix3, SinkhornGaugeError> {
if !is_strict_positive_matrix(matrix, 0.0) {
return Err(SinkhornGaugeError::InvalidCanonicalState);
}
let mut log_entries = [[0.0_f64; SIZE]; SIZE];
for row in 0..SIZE {
for col in 0..SIZE {
log_entries[row][col] = libm::log(matrix.entries[row][col]);
}
}
let mut row_means = [0.0_f64; SIZE];
for row in 0..SIZE {
row_means[row] = mean(log_entries[row]);
}
let mut column_means = [0.0_f64; SIZE];
for col in 0..SIZE {
column_means[col] =
(0..SIZE).fold(0.0_f64, |total, row| total + log_entries[row][col]) / SIZE as f64;
}
let grand_mean = mean(row_means);
let mut quotient = [[0.0_f64; SIZE]; SIZE];
for row in 0..SIZE {
for col in 0..SIZE {
quotient[row][col] =
log_entries[row][col] - row_means[row] - column_means[col] + grand_mean;
}
}
Ok(Matrix3::new(quotient))
}
fn row_sums(matrix: Matrix3) -> [f64; SIZE] {
let mut sums = [0.0_f64; SIZE];
for row in 0..SIZE {
sums[row] = matrix.entries[row]
.iter()
.fold(0.0_f64, |total, entry| total + *entry);
}
sums
}
fn column_sums(matrix: Matrix3) -> [f64; SIZE] {
let mut sums = [0.0_f64; SIZE];
for col in 0..SIZE {
sums[col] = (0..SIZE).fold(0.0_f64, |total, row| total + matrix.entries[row][col]);
}
sums
}
fn max_unit_sum_error(sums: [f64; SIZE]) -> f64 {
sums.iter()
.fold(0.0_f64, |max, sum| max.max((*sum - 1.0).abs()))
}
fn mean(values: [f64; SIZE]) -> f64 {
values.iter().fold(0.0_f64, |total, value| total + *value) / SIZE as f64
}
fn max_abs(matrix: Matrix3) -> f64 {
let mut max = 0.0_f64;
for row in matrix.entries {
for entry in row {
max = max.max(entry.abs());
}
}
max
}
fn max_abs_diff(left: Matrix3, right: Matrix3) -> f64 {
let mut max = 0.0_f64;
for row in 0..SIZE {
for col in 0..SIZE {
max = max.max((left.entries[row][col] - right.entries[row][col]).abs());
}
}
max
}
fn negative_guard_report(
inputs: &SinkhornGaugeInputs3,
old_wrong_path: &'static str,
) -> Result<SinkhornNegativeGuardReport, SinkhornGaugeError> {
validate_inputs(inputs)?;
let presentation = present_sinkhorn_gauge_only(inputs)?;
let canonical_state_delta = max_abs_diff(presentation.presentation, inputs.canonical_state);
Ok(SinkhornNegativeGuardReport {
old_wrong_path,
rejected: canonical_state_delta > inputs.tolerance,
canonical_state_delta,
quotient_state_delta: presentation.quotient_state_delta,
kappa_delta: presentation.kappa_delta,
canonical_mutated: canonical_state_delta > inputs.tolerance,
})
}
}
pub mod kappa {
pub const KAPPA_DYNAMIC_FLOOR_JOURNEY_ID: &str = "J-KAPPA-DYNAMIC-FLOOR";
pub const KAPPA_DYNAMIC_FLOOR_STORY_ID: &str = "CCFV1-04";
pub const FIXED_KAPPA_THEOREM_OLD_WRONG_PATH: &str =
concat!("Fixed kappa_t < ", "1e-9 theorem");
pub const PERIODIC_CERTIFICATE_OLD_WRONG_PATH: &str = "Periodic/on-demand certificate";
pub const NO_FAIL_CLOSED_EXCURSION_OLD_WRONG_PATH: &str = "No fail-closed excursion";
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct KappaFloorTick {
pub tick_id: u64,
pub dimension_n: usize,
pub epsilon_q: f64,
pub delta_alpha_t: f64,
pub e_t: f64,
pub policy_margin: f64,
pub kappa_hat_t: f64,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum KappaCertificateStatus {
WithinDynamicFloor,
FailClosedExcursion,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct KappaDynamicFloorReport {
pub tick_id: u64,
pub kappa_hat_t: f64,
pub floor_t: f64,
pub epsilon_q: f64,
pub delta_alpha_t: f64,
pub e_t: f64,
pub policy_margin: f64,
pub threshold_t: f64,
pub certificate_status: KappaCertificateStatus,
pub fail_closed: bool,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct KappaNegativeGuardReport {
pub old_wrong_path: &'static str,
pub rejected: bool,
pub kappa_hat_t: f64,
pub floor_t: f64,
pub policy_margin: f64,
pub fail_closed: bool,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum KappaDynamicFloorError {
InvalidInput,
NotImplemented,
}
pub fn classify_dynamic_floor_tick(
tick: &KappaFloorTick,
) -> Result<KappaDynamicFloorReport, KappaDynamicFloorError> {
validate_tick(tick)?;
let floor_t = dynamic_floor(tick);
let threshold_t = floor_t + tick.policy_margin;
if !threshold_t.is_finite() {
return Err(KappaDynamicFloorError::InvalidInput);
}
let fail_closed = tick.kappa_hat_t > threshold_t;
Ok(KappaDynamicFloorReport {
tick_id: tick.tick_id,
kappa_hat_t: tick.kappa_hat_t,
floor_t,
epsilon_q: tick.epsilon_q,
delta_alpha_t: tick.delta_alpha_t,
e_t: tick.e_t,
policy_margin: tick.policy_margin,
threshold_t,
certificate_status: if fail_closed {
KappaCertificateStatus::FailClosedExcursion
} else {
KappaCertificateStatus::WithinDynamicFloor
},
fail_closed,
})
}
pub fn reject_fixed_kappa_theorem_threshold(
tick: &KappaFloorTick,
) -> Result<KappaNegativeGuardReport, KappaDynamicFloorError> {
let report = classify_dynamic_floor_tick(tick)?;
Ok(KappaNegativeGuardReport {
old_wrong_path: FIXED_KAPPA_THEOREM_OLD_WRONG_PATH,
rejected: true,
kappa_hat_t: report.kappa_hat_t,
floor_t: report.floor_t,
policy_margin: report.policy_margin,
fail_closed: report.fail_closed,
})
}
pub fn reject_periodic_certificate(
ticks: &[KappaFloorTick],
) -> Result<KappaNegativeGuardReport, KappaDynamicFloorError> {
let last = ticks.last().ok_or(KappaDynamicFloorError::InvalidInput)?;
for tick in ticks {
validate_tick(tick)?;
}
let report = classify_dynamic_floor_tick(last)?;
Ok(KappaNegativeGuardReport {
old_wrong_path: PERIODIC_CERTIFICATE_OLD_WRONG_PATH,
rejected: ticks.len() > 1,
kappa_hat_t: report.kappa_hat_t,
floor_t: report.floor_t,
policy_margin: report.policy_margin,
fail_closed: report.fail_closed,
})
}
pub fn reject_no_fail_closed_excursion(
tick: &KappaFloorTick,
) -> Result<KappaNegativeGuardReport, KappaDynamicFloorError> {
let report = classify_dynamic_floor_tick(tick)?;
Ok(KappaNegativeGuardReport {
old_wrong_path: NO_FAIL_CLOSED_EXCURSION_OLD_WRONG_PATH,
rejected: report.fail_closed,
kappa_hat_t: report.kappa_hat_t,
floor_t: report.floor_t,
policy_margin: report.policy_margin,
fail_closed: report.fail_closed,
})
}
fn validate_tick(tick: &KappaFloorTick) -> Result<(), KappaDynamicFloorError> {
if tick.dimension_n == 0
|| !tick.epsilon_q.is_finite()
|| tick.epsilon_q <= 0.0
|| !tick.delta_alpha_t.is_finite()
|| !tick.e_t.is_finite()
|| tick.e_t < 0.0
|| !tick.policy_margin.is_finite()
|| tick.policy_margin < 0.0
|| !tick.kappa_hat_t.is_finite()
|| tick.kappa_hat_t < 0.0
{
Err(KappaDynamicFloorError::InvalidInput)
} else {
Ok(())
}
}
fn dynamic_floor(tick: &KappaFloorTick) -> f64 {
2.0 * tick.dimension_n as f64 * tick.epsilon_q + tick.delta_alpha_t.abs() * tick.e_t
}
use super::qac::Matrix3;
const N: usize = 3;
fn strict_positive_finite(matrix: &Matrix3) -> bool {
matrix
.entries
.iter()
.flatten()
.all(|value| value.is_finite() && *value > 0.0)
}
fn log_matrix(matrix: &Matrix3) -> [[f64; N]; N] {
let mut out = [[0.0_f64; N]; N];
for (row, out_row) in out.iter_mut().enumerate() {
for (col, slot) in out_row.iter_mut().enumerate() {
*slot = libm::log(matrix.entries[row][col]);
}
}
out
}
fn gauge_center(matrix: &[[f64; N]; N]) -> [[f64; N]; N] {
let n = N as f64;
let mut row_mean = [0.0_f64; N];
let mut col_mean = [0.0_f64; N];
let mut grand = 0.0_f64;
for row in 0..N {
for col in 0..N {
row_mean[row] += matrix[row][col];
col_mean[col] += matrix[row][col];
grand += matrix[row][col];
}
}
for value in row_mean.iter_mut() {
*value /= n;
}
for value in col_mean.iter_mut() {
*value /= n;
}
grand /= n * n;
let mut out = [[0.0_f64; N]; N];
for row in 0..N {
for col in 0..N {
out[row][col] = matrix[row][col] - row_mean[row] - col_mean[col] + grand;
}
}
out
}
fn frobenius(matrix: &[[f64; N]; N]) -> f64 {
let mut sum = 0.0_f64;
for row in matrix.iter() {
for value in row.iter() {
sum += value * value;
}
}
libm::sqrt(sum)
}
pub fn compute_kappa_hat(
prior_a_t: &Matrix3,
reference_r_t: &Matrix3,
realized_a_next: &Matrix3,
alpha_t: f64,
) -> Result<f64, KappaDynamicFloorError> {
if !alpha_t.is_finite()
|| !(0.0..=1.0).contains(&alpha_t)
|| !strict_positive_finite(prior_a_t)
|| !strict_positive_finite(reference_r_t)
|| !strict_positive_finite(realized_a_next)
{
return Err(KappaDynamicFloorError::InvalidInput);
}
let log_a = log_matrix(prior_a_t);
let log_r = log_matrix(reference_r_t);
let log_next = log_matrix(realized_a_next);
let mut residual = [[0.0_f64; N]; N];
for row in 0..N {
for col in 0..N {
residual[row][col] = log_next[row][col]
- (1.0 - alpha_t) * log_a[row][col]
- alpha_t * log_r[row][col];
}
}
Ok(frobenius(&gauge_center(&residual)))
}
pub fn quotient_distance(a: &Matrix3, b: &Matrix3) -> Result<f64, KappaDynamicFloorError> {
if !strict_positive_finite(a) || !strict_positive_finite(b) {
return Err(KappaDynamicFloorError::InvalidInput);
}
let log_a = log_matrix(a);
let log_b = log_matrix(b);
let mut diff = [[0.0_f64; N]; N];
for row in 0..N {
for col in 0..N {
diff[row][col] = log_a[row][col] - log_b[row][col];
}
}
Ok(frobenius(&gauge_center(&diff)))
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct CertificateInputs {
pub tick_id: u64,
pub prior_a_t: Matrix3,
pub reference_r_t: Matrix3,
pub realized_a_next: Matrix3,
pub alpha_t: f64,
pub delta_alpha_t: f64,
pub epsilon_q: f64,
pub policy_margin: f64,
}
pub fn certify_update(
inputs: &CertificateInputs,
) -> Result<KappaDynamicFloorReport, KappaDynamicFloorError> {
let kappa_hat_t = compute_kappa_hat(
&inputs.prior_a_t,
&inputs.reference_r_t,
&inputs.realized_a_next,
inputs.alpha_t,
)?;
let e_t = quotient_distance(&inputs.prior_a_t, &inputs.reference_r_t)?;
let tick = KappaFloorTick {
tick_id: inputs.tick_id,
dimension_n: N,
epsilon_q: inputs.epsilon_q,
delta_alpha_t: inputs.delta_alpha_t,
e_t,
policy_margin: inputs.policy_margin,
kappa_hat_t,
};
classify_dynamic_floor_tick(&tick)
}
}
pub mod endpoint {
use super::kappa::{
classify_dynamic_floor_tick, compute_kappa_hat, quotient_distance, KappaCertificateStatus,
KappaFloorTick,
};
use super::qac::Matrix3;
const STRUCTURAL_TOLERANCE: f64 = 1.0e-12;
pub const ENDPOINT_HYBRID_JOURNEY_ID: &str = "J-ENDPOINT-HYBRID";
pub const ENDPOINT_HYBRID_STORY_ID: &str = "CCFV1-05";
pub const KAPPA_ALONE_ENDPOINT_OLD_WRONG_PATH: &str = "Endpoint steps certified by kappa alone";
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum EndpointKind {
Interior,
AlphaZeroNoop,
AlphaOneTarget,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum EndpointStructuralStatus {
NotRequired,
VerifiedNoop,
VerifiedTarget,
Missing,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum EndpointCertificateStatus {
Interior,
VerifiedEndpoint,
RejectedMissingStructuralVerification,
RejectedKappaExcursion,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct EndpointHybridTick {
pub tick_id: u64,
pub alpha_t: f64,
pub delta_alpha_t: f64,
pub epsilon_q: f64,
pub policy_margin: f64,
pub prior_state: Matrix3,
pub reference_state: Matrix3,
pub observed_state: Matrix3,
pub structural_verification_enabled: bool,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct EndpointHybridReport {
pub tick_id: u64,
pub alpha_t: f64,
pub endpoint_kind: EndpointKind,
pub endpoint_structural_status: EndpointStructuralStatus,
pub endpoint_certificate_status: EndpointCertificateStatus,
pub kappa_certificate_status: KappaCertificateStatus,
pub kappa_hat_t: f64,
pub floor_t: f64,
pub policy_margin: f64,
pub state_max_error: f64,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct EndpointNegativeGuardReport {
pub old_wrong_path: &'static str,
pub rejected: bool,
pub endpoint_structural_status: EndpointStructuralStatus,
pub endpoint_certificate_status: EndpointCertificateStatus,
pub kappa_certificate_status: KappaCertificateStatus,
pub kappa_hat_t: f64,
pub floor_t: f64,
pub policy_margin: f64,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum EndpointHybridError {
InvalidInput,
NotImplemented,
}
pub fn classify_endpoint_hybrid_tick(
tick: &EndpointHybridTick,
) -> Result<EndpointHybridReport, EndpointHybridError> {
validate_tick(tick)?;
let kappa_hat_t = compute_kappa_hat(
&tick.prior_state,
&tick.reference_state,
&tick.observed_state,
tick.alpha_t,
)
.map_err(|_| EndpointHybridError::InvalidInput)?;
let e_t = quotient_distance(&tick.prior_state, &tick.reference_state)
.map_err(|_| EndpointHybridError::InvalidInput)?;
let kappa_floor_tick = KappaFloorTick {
tick_id: tick.tick_id,
dimension_n: 3,
epsilon_q: tick.epsilon_q,
delta_alpha_t: tick.delta_alpha_t,
e_t,
policy_margin: tick.policy_margin,
kappa_hat_t,
};
let kappa_report = classify_dynamic_floor_tick(&kappa_floor_tick)
.map_err(|_| EndpointHybridError::InvalidInput)?;
let endpoint_kind = endpoint_kind(tick.alpha_t);
let (endpoint_structural_status, state_max_error) = structural_status(endpoint_kind, tick);
let endpoint_certificate_status = endpoint_certificate_status(
endpoint_kind,
endpoint_structural_status,
kappa_report.certificate_status,
);
Ok(EndpointHybridReport {
tick_id: tick.tick_id,
alpha_t: tick.alpha_t,
endpoint_kind,
endpoint_structural_status,
endpoint_certificate_status,
kappa_certificate_status: kappa_report.certificate_status,
kappa_hat_t: kappa_report.kappa_hat_t,
floor_t: kappa_report.floor_t,
policy_margin: kappa_report.policy_margin,
state_max_error,
})
}
pub fn reject_kappa_alone_endpoint_certificate(
tick: &EndpointHybridTick,
) -> Result<EndpointNegativeGuardReport, EndpointHybridError> {
let report = classify_endpoint_hybrid_tick(tick)?;
Ok(EndpointNegativeGuardReport {
old_wrong_path: KAPPA_ALONE_ENDPOINT_OLD_WRONG_PATH,
rejected: report.endpoint_kind != EndpointKind::Interior
&& report.endpoint_structural_status == EndpointStructuralStatus::Missing
&& report.kappa_certificate_status == KappaCertificateStatus::WithinDynamicFloor,
endpoint_structural_status: report.endpoint_structural_status,
endpoint_certificate_status: report.endpoint_certificate_status,
kappa_certificate_status: report.kappa_certificate_status,
kappa_hat_t: report.kappa_hat_t,
floor_t: report.floor_t,
policy_margin: report.policy_margin,
})
}
fn validate_tick(tick: &EndpointHybridTick) -> Result<(), EndpointHybridError> {
if !tick.alpha_t.is_finite()
|| !(0.0..=1.0).contains(&tick.alpha_t)
|| !tick.delta_alpha_t.is_finite()
|| !tick.epsilon_q.is_finite()
|| tick.epsilon_q <= 0.0
|| !tick.policy_margin.is_finite()
|| tick.policy_margin < 0.0
|| !matrix_is_finite(tick.prior_state)
|| !matrix_is_finite(tick.reference_state)
|| !matrix_is_finite(tick.observed_state)
{
Err(EndpointHybridError::InvalidInput)
} else {
Ok(())
}
}
fn endpoint_kind(alpha_t: f64) -> EndpointKind {
if alpha_t == 0.0 {
EndpointKind::AlphaZeroNoop
} else if alpha_t == 1.0 {
EndpointKind::AlphaOneTarget
} else {
EndpointKind::Interior
}
}
fn structural_status(
endpoint_kind: EndpointKind,
tick: &EndpointHybridTick,
) -> (EndpointStructuralStatus, f64) {
match endpoint_kind {
EndpointKind::Interior => (EndpointStructuralStatus::NotRequired, 0.0),
EndpointKind::AlphaZeroNoop => {
let state_max_error = max_abs_diff(tick.observed_state, tick.prior_state);
if tick.structural_verification_enabled && state_max_error <= STRUCTURAL_TOLERANCE {
(EndpointStructuralStatus::VerifiedNoop, state_max_error)
} else {
(EndpointStructuralStatus::Missing, state_max_error)
}
}
EndpointKind::AlphaOneTarget => {
let state_max_error = max_abs_diff(tick.observed_state, tick.reference_state);
if tick.structural_verification_enabled && state_max_error <= STRUCTURAL_TOLERANCE {
(EndpointStructuralStatus::VerifiedTarget, state_max_error)
} else {
(EndpointStructuralStatus::Missing, state_max_error)
}
}
}
}
fn endpoint_certificate_status(
endpoint_kind: EndpointKind,
structural_status: EndpointStructuralStatus,
kappa_status: KappaCertificateStatus,
) -> EndpointCertificateStatus {
match endpoint_kind {
EndpointKind::Interior => EndpointCertificateStatus::Interior,
EndpointKind::AlphaZeroNoop | EndpointKind::AlphaOneTarget => {
if structural_status == EndpointStructuralStatus::Missing {
EndpointCertificateStatus::RejectedMissingStructuralVerification
} else if kappa_status == KappaCertificateStatus::FailClosedExcursion {
EndpointCertificateStatus::RejectedKappaExcursion
} else {
EndpointCertificateStatus::VerifiedEndpoint
}
}
}
}
fn matrix_is_finite(matrix: Matrix3) -> bool {
matrix
.entries
.iter()
.all(|row| row.iter().all(|entry| entry.is_finite()))
}
fn max_abs_diff(left: Matrix3, right: Matrix3) -> f64 {
let mut max_error = 0.0_f64;
for row in 0..3 {
for col in 0..3 {
max_error = max_error.max((left.entries[row][col] - right.entries[row][col]).abs());
}
}
max_error
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PrecheckReason {
Passed,
ScaffoldOnly,
ContractsMissing,
TicketJourneyUnmapped,
OldWrongCore,
NonPositiveEntry,
SingularNormalizationTarget,
NotFiniteInput,
AlphaOutOfRange,
UnknownContext,
ForbiddenCategoryWrite,
}
pub mod precheck {
use super::qac::Matrix3;
use super::PrecheckReason;
pub const PRECHECK_FORBIDDEN_JOURNEY_ID: &str = "J-PRECHECK-FORBIDDEN";
pub const PRECHECK_FORBIDDEN_STORY_ID: &str = "CCFV1-06";
pub const EPSILON_T_NAME_COLLISION_OLD_WRONG_PATH: &str = "epsilon_t name collision";
pub const POST_UPDATE_INVALIDITY_OLD_WRONG_PATH: &str = "Invalidity check after update";
pub const FORBIDDEN_WRITE_BYPASS_OLD_WRONG_PATH: &str = "Forbidden write bypassing guard";
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct AccumulatorSnapshot {
pub update_count: u64,
pub matrix_hash: u64,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PrecheckTick {
pub tick_id: u64,
pub prior_state: Matrix3,
pub reference_state: Matrix3,
pub left_normalization: [f64; 3],
pub right_normalization: [f64; 3],
pub alpha_t: f64,
pub context_known: bool,
pub forbidden_category_write: bool,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CertificateEventClass {
None,
PrecheckFailure,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PrecheckReport {
pub tick_id: u64,
pub precheck_t: PrecheckReason,
pub update_count_before: u64,
pub update_count_after: u64,
pub matrix_hash_before: u64,
pub matrix_hash_after: u64,
pub update_attempted: bool,
pub fail_closed: bool,
pub certificate_event_class: CertificateEventClass,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct PrecheckNegativeGuardReport {
pub old_wrong_path: &'static str,
pub rejected: bool,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PrecheckError {
InvalidInput,
NotImplemented,
}
pub fn run_precheck_before_update(
tick: &PrecheckTick,
before: AccumulatorSnapshot,
) -> Result<PrecheckReport, PrecheckError> {
let precheck_t = precheck_reason(tick).unwrap_or(PrecheckReason::Passed);
let fail_closed = precheck_t != PrecheckReason::Passed;
Ok(PrecheckReport {
tick_id: tick.tick_id,
precheck_t,
update_count_before: before.update_count,
update_count_after: before.update_count,
matrix_hash_before: before.matrix_hash,
matrix_hash_after: before.matrix_hash,
update_attempted: false,
fail_closed,
certificate_event_class: if fail_closed {
CertificateEventClass::PrecheckFailure
} else {
CertificateEventClass::None
},
})
}
pub fn reject_epsilon_t_name_collision() -> Result<PrecheckNegativeGuardReport, PrecheckError> {
Ok(negative_guard_report(
EPSILON_T_NAME_COLLISION_OLD_WRONG_PATH,
))
}
pub fn reject_post_update_invalidity_check(
) -> Result<PrecheckNegativeGuardReport, PrecheckError> {
Ok(negative_guard_report(POST_UPDATE_INVALIDITY_OLD_WRONG_PATH))
}
pub fn reject_forbidden_write_bypassing_guard(
) -> Result<PrecheckNegativeGuardReport, PrecheckError> {
Ok(negative_guard_report(FORBIDDEN_WRITE_BYPASS_OLD_WRONG_PATH))
}
fn precheck_reason(tick: &PrecheckTick) -> Option<PrecheckReason> {
if !matrix_is_finite(tick.prior_state)
|| !matrix_is_finite(tick.reference_state)
|| !diagonal_is_finite(tick.left_normalization)
|| !diagonal_is_finite(tick.right_normalization)
|| !tick.alpha_t.is_finite()
{
return Some(PrecheckReason::NotFiniteInput);
}
if !matrix_is_strictly_positive(tick.prior_state)
|| !matrix_is_strictly_positive(tick.reference_state)
{
return Some(PrecheckReason::NonPositiveEntry);
}
if !diagonal_is_strictly_positive(tick.left_normalization)
|| !diagonal_is_strictly_positive(tick.right_normalization)
{
return Some(PrecheckReason::SingularNormalizationTarget);
}
if !(0.0..=1.0).contains(&tick.alpha_t) {
return Some(PrecheckReason::AlphaOutOfRange);
}
if !tick.context_known {
return Some(PrecheckReason::UnknownContext);
}
if tick.forbidden_category_write {
return Some(PrecheckReason::ForbiddenCategoryWrite);
}
None
}
fn matrix_is_finite(matrix: Matrix3) -> bool {
matrix
.entries
.iter()
.all(|row| row.iter().all(|entry| entry.is_finite()))
}
fn matrix_is_strictly_positive(matrix: Matrix3) -> bool {
matrix
.entries
.iter()
.all(|row| row.iter().all(|entry| *entry > 0.0))
}
fn diagonal_is_finite(diagonal: [f64; 3]) -> bool {
diagonal.iter().all(|entry| entry.is_finite())
}
fn diagonal_is_strictly_positive(diagonal: [f64; 3]) -> bool {
diagonal.iter().all(|entry| *entry > 0.0)
}
const fn negative_guard_report(old_wrong_path: &'static str) -> PrecheckNegativeGuardReport {
PrecheckNegativeGuardReport {
old_wrong_path,
rejected: true,
}
}
}
pub mod context {
use super::qac::{qac_update_3x3, Matrix3, PositiveDiagonal3, QacError, QacInputs3};
const EPSILON_FLOOR: f64 = 1.0e-12;
const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;
pub const CONTEXT_ISOLATION_JOURNEY_ID: &str = "J-CONTEXT-ISOLATION";
pub const CONTEXT_ISOLATION_STORY_ID: &str = "CCFV1-07";
pub const GLOBAL_SHARED_TIMESTAMP_OLD_WRONG_PATH: &str = "Global tick/shared timestamp";
pub const CROSS_CONTEXT_NORMALIZATION_OLD_WRONG_PATH: &str =
"Cross-context normalization leakage";
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ContextAccumulator {
pub context_id: &'static str,
pub state: Matrix3,
pub update_count: u64,
pub last_update_unix_ms: u64,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PerContextAccumulatorStore {
pub first: ContextAccumulator,
pub second: ContextAccumulator,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ContextUpdateTick {
pub context_id: &'static str,
pub reference_state: Matrix3,
pub left_normalization: [f64; 3],
pub right_normalization: [f64; 3],
pub alpha_t: f64,
pub wall_clock_unix_ms: u64,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ContextAccumulatorSnapshot {
pub context_id: &'static str,
pub state: Matrix3,
pub state_hash: u64,
pub update_count: u64,
pub last_update_unix_ms: u64,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ContextIsolationReport {
pub active_context: &'static str,
pub inactive_context: &'static str,
pub active_before: ContextAccumulatorSnapshot,
pub active_after: ContextAccumulatorSnapshot,
pub inactive_before: ContextAccumulatorSnapshot,
pub inactive_after: ContextAccumulatorSnapshot,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ContextNegativeGuardReport {
pub old_wrong_path: &'static str,
pub rejected: bool,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ContextIsolationError {
InvalidInput,
UnknownContext,
NotImplemented,
}
pub fn apply_active_context_update(
store: &mut PerContextAccumulatorStore,
tick: &ContextUpdateTick,
) -> Result<ContextIsolationReport, ContextIsolationError> {
validate_store(store)?;
validate_tick(tick)?;
let first_is_active = store.first.context_id == tick.context_id;
let second_is_active = store.second.context_id == tick.context_id;
if first_is_active == second_is_active {
return Err(ContextIsolationError::UnknownContext);
}
let active_before_accumulator = if first_is_active {
store.first
} else {
store.second
};
let inactive_before_accumulator = if first_is_active {
store.second
} else {
store.first
};
if tick.wall_clock_unix_ms <= active_before_accumulator.last_update_unix_ms {
return Err(ContextIsolationError::InvalidInput);
}
let active_before = snapshot(active_before_accumulator);
let inactive_before = snapshot(inactive_before_accumulator);
let new_state = qac_update_3x3(&QacInputs3 {
prior_a_t: active_before_accumulator.state,
reference_r_t: tick.reference_state,
left_l_t: PositiveDiagonal3::try_new(tick.left_normalization).map_err(map_qac_error)?,
right_c_t: PositiveDiagonal3::try_new(tick.right_normalization)
.map_err(map_qac_error)?,
alpha_t: tick.alpha_t,
epsilon_floor: EPSILON_FLOOR,
})
.map_err(map_qac_error)?;
let updated_active = ContextAccumulator {
context_id: active_before_accumulator.context_id,
state: new_state,
update_count: active_before_accumulator
.update_count
.checked_add(1)
.ok_or(ContextIsolationError::InvalidInput)?,
last_update_unix_ms: tick.wall_clock_unix_ms,
};
if first_is_active {
store.first = updated_active;
} else {
store.second = updated_active;
}
let active_after_accumulator = if first_is_active {
store.first
} else {
store.second
};
let inactive_after_accumulator = if first_is_active {
store.second
} else {
store.first
};
Ok(ContextIsolationReport {
active_context: active_before_accumulator.context_id,
inactive_context: inactive_before_accumulator.context_id,
active_before,
active_after: snapshot(active_after_accumulator),
inactive_before,
inactive_after: snapshot(inactive_after_accumulator),
})
}
pub fn reject_global_shared_timestamp(
) -> Result<ContextNegativeGuardReport, ContextIsolationError> {
Ok(negative_guard_report(
GLOBAL_SHARED_TIMESTAMP_OLD_WRONG_PATH,
))
}
pub fn reject_cross_context_normalization_leakage(
) -> Result<ContextNegativeGuardReport, ContextIsolationError> {
Ok(negative_guard_report(
CROSS_CONTEXT_NORMALIZATION_OLD_WRONG_PATH,
))
}
fn validate_store(store: &PerContextAccumulatorStore) -> Result<(), ContextIsolationError> {
if store.first.context_id.is_empty()
|| store.second.context_id.is_empty()
|| store.first.context_id == store.second.context_id
{
Err(ContextIsolationError::InvalidInput)
} else {
Ok(())
}
}
fn validate_tick(tick: &ContextUpdateTick) -> Result<(), ContextIsolationError> {
if tick.context_id.is_empty() || tick.wall_clock_unix_ms == 0 {
Err(ContextIsolationError::InvalidInput)
} else {
Ok(())
}
}
fn snapshot(accumulator: ContextAccumulator) -> ContextAccumulatorSnapshot {
ContextAccumulatorSnapshot {
context_id: accumulator.context_id,
state: accumulator.state,
state_hash: matrix_hash(accumulator.state),
update_count: accumulator.update_count,
last_update_unix_ms: accumulator.last_update_unix_ms,
}
}
fn matrix_hash(matrix: Matrix3) -> u64 {
let mut hash = FNV_OFFSET;
for row in matrix.entries {
for value in row {
for byte in value.to_bits().to_le_bytes() {
hash ^= byte as u64;
hash = hash.wrapping_mul(FNV_PRIME);
}
}
}
hash
}
const fn negative_guard_report(old_wrong_path: &'static str) -> ContextNegativeGuardReport {
ContextNegativeGuardReport {
old_wrong_path,
rejected: true,
}
}
const fn map_qac_error(_error: QacError) -> ContextIsolationError {
ContextIsolationError::InvalidInput
}
}
pub mod forbidden_policy {
use super::qac::{qac_update_3x3, Matrix3, PositiveDiagonal3, QacError, QacInputs3};
use super::PrecheckReason;
pub const FORBIDDEN_POLICY_JOURNEY_ID: &str = "J-PRECHECK-FORBIDDEN";
pub const FORBIDDEN_POLICY_STORY_ID: &str = "CCFV1-08";
pub const PINNED_ZERO_QAC_OLD_WRONG_PATH: &str = "Pinned zeros inside canonical QAC math";
pub const SKIPPED_MATRIX_COLUMNS_OLD_WRONG_PATH: &str = "Skipped matrix columns";
pub const INVISIBLE_FACEWISE_WRITE_OLD_WRONG_PATH: &str = "Invisible facewise write";
const MATRIX_CELLS: usize = 9;
const MASK_BITS: u16 = 0x01ff;
const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct CategoryIndex {
pub row: usize,
pub col: usize,
}
impl CategoryIndex {
pub const fn new(row: usize, col: usize) -> Self {
Self { row, col }
}
pub fn validate(self) -> Result<Self, ForbiddenPolicyError> {
if self.row < 3 && self.col < 3 {
Ok(self)
} else {
Err(ForbiddenPolicyError::InvalidInput)
}
}
pub const fn bit_index(self) -> usize {
self.row * 3 + self.col
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ForbiddenCategoryMask3 {
bits: u16,
}
impl ForbiddenCategoryMask3 {
pub const fn empty() -> Self {
Self { bits: 0 }
}
pub fn try_from_bits(bits: u16) -> Result<Self, ForbiddenPolicyError> {
if bits & !MASK_BITS == 0 {
Ok(Self { bits })
} else {
Err(ForbiddenPolicyError::InvalidInput)
}
}
pub fn try_from_categories(
categories: &[CategoryIndex],
) -> Result<Self, ForbiddenPolicyError> {
let mut bits = 0_u16;
for category in categories {
let category = category.validate()?;
bits |= 1_u16 << category.bit_index();
}
Self::try_from_bits(bits)
}
pub const fn bits(self) -> u16 {
self.bits
}
pub fn forbids(self, category: CategoryIndex) -> bool {
if category.row >= 3 || category.col >= 3 {
return false;
}
(self.bits & (1_u16 << category.bit_index())) != 0
}
pub fn forbidden_count(self) -> usize {
let mut count = 0_usize;
let mut bit = 0_usize;
while bit < MATRIX_CELLS {
if (self.bits & (1_u16 << bit)) != 0 {
count += 1;
}
bit += 1;
}
count
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ForbiddenPolicyTick {
pub tick_id: u64,
pub prior_state: Matrix3,
pub reference_state: Matrix3,
pub left_normalization: [f64; 3],
pub right_normalization: [f64; 3],
pub alpha_t: f64,
pub epsilon_floor: f64,
pub forbidden_mask: ForbiddenCategoryMask3,
pub target_category: CategoryIndex,
pub update_count_before: u64,
pub matrix_hash_before: u64,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ForbiddenPolicyEventClass {
None,
ForbiddenCategoryWrite,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ForbiddenPolicyReport {
pub tick_id: u64,
pub forbidden_policy_mask_bits: u16,
pub precheck_reason: PrecheckReason,
pub forbidden_category_write: bool,
pub update_count_before: u64,
pub update_count_after: u64,
pub matrix_hash_before: u64,
pub matrix_hash_after: u64,
pub precheck_fail_closed: bool,
pub certificate_event_class: ForbiddenPolicyEventClass,
pub valid_update_min_entry: f64,
pub epsilon_floor: f64,
pub canonical_entries_epsilon_floored: bool,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ForbiddenPolicyNegativeGuardReport {
pub old_wrong_path: &'static str,
pub rejected: bool,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ForbiddenPolicyError {
InvalidInput,
NotImplemented,
}
pub fn apply_forbidden_category_policy(
tick: &ForbiddenPolicyTick,
) -> Result<ForbiddenPolicyReport, ForbiddenPolicyError> {
validate_tick(tick)?;
let target_category = tick.target_category.validate()?;
if tick.forbidden_mask.forbids(target_category) {
return Ok(ForbiddenPolicyReport {
tick_id: tick.tick_id,
forbidden_policy_mask_bits: tick.forbidden_mask.bits(),
precheck_reason: PrecheckReason::ForbiddenCategoryWrite,
forbidden_category_write: true,
update_count_before: tick.update_count_before,
update_count_after: tick.update_count_before,
matrix_hash_before: tick.matrix_hash_before,
matrix_hash_after: tick.matrix_hash_before,
precheck_fail_closed: true,
certificate_event_class: ForbiddenPolicyEventClass::ForbiddenCategoryWrite,
valid_update_min_entry: 0.0,
epsilon_floor: tick.epsilon_floor,
canonical_entries_epsilon_floored: false,
});
}
let updated_state = qac_update_3x3(&QacInputs3 {
prior_a_t: tick.prior_state,
reference_r_t: tick.reference_state,
left_l_t: PositiveDiagonal3::try_new(tick.left_normalization).map_err(map_qac_error)?,
right_c_t: PositiveDiagonal3::try_new(tick.right_normalization)
.map_err(map_qac_error)?,
alpha_t: tick.alpha_t,
epsilon_floor: tick.epsilon_floor,
})
.map_err(map_qac_error)?;
let valid_update_min_entry = matrix_min(updated_state);
let canonical_entries_epsilon_floored = valid_update_min_entry >= tick.epsilon_floor;
if !canonical_entries_epsilon_floored {
return Err(ForbiddenPolicyError::InvalidInput);
}
Ok(ForbiddenPolicyReport {
tick_id: tick.tick_id,
forbidden_policy_mask_bits: tick.forbidden_mask.bits(),
precheck_reason: PrecheckReason::Passed,
forbidden_category_write: false,
update_count_before: tick.update_count_before,
update_count_after: tick
.update_count_before
.checked_add(1)
.ok_or(ForbiddenPolicyError::InvalidInput)?,
matrix_hash_before: tick.matrix_hash_before,
matrix_hash_after: matrix_hash(updated_state),
precheck_fail_closed: false,
certificate_event_class: ForbiddenPolicyEventClass::None,
valid_update_min_entry,
epsilon_floor: tick.epsilon_floor,
canonical_entries_epsilon_floored,
})
}
pub fn reject_pinned_zero_qac_math(
) -> Result<ForbiddenPolicyNegativeGuardReport, ForbiddenPolicyError> {
Ok(negative_guard_report(PINNED_ZERO_QAC_OLD_WRONG_PATH))
}
pub fn reject_skipped_matrix_columns(
) -> Result<ForbiddenPolicyNegativeGuardReport, ForbiddenPolicyError> {
Ok(negative_guard_report(SKIPPED_MATRIX_COLUMNS_OLD_WRONG_PATH))
}
pub fn reject_invisible_facewise_write(
) -> Result<ForbiddenPolicyNegativeGuardReport, ForbiddenPolicyError> {
Ok(negative_guard_report(
INVISIBLE_FACEWISE_WRITE_OLD_WRONG_PATH,
))
}
fn validate_tick(tick: &ForbiddenPolicyTick) -> Result<(), ForbiddenPolicyError> {
tick.target_category.validate()?;
if tick.tick_id == 0
|| !tick.alpha_t.is_finite()
|| !tick.epsilon_floor.is_finite()
|| tick.epsilon_floor <= 0.0
|| !matrix_is_finite(tick.prior_state)
|| !matrix_is_finite(tick.reference_state)
|| !diagonal_is_finite(tick.left_normalization)
|| !diagonal_is_finite(tick.right_normalization)
|| tick.matrix_hash_before != matrix_hash(tick.prior_state)
{
return Err(ForbiddenPolicyError::InvalidInput);
}
Ok(())
}
fn matrix_hash(matrix: Matrix3) -> u64 {
let mut hash = FNV_OFFSET;
for row in matrix.entries {
for value in row {
for byte in value.to_bits().to_le_bytes() {
hash ^= byte as u64;
hash = hash.wrapping_mul(FNV_PRIME);
}
}
}
hash
}
fn matrix_min(matrix: Matrix3) -> f64 {
let mut minimum = matrix.entries[0][0];
for row in matrix.entries {
for value in row {
if value < minimum {
minimum = value;
}
}
}
minimum
}
fn matrix_is_finite(matrix: Matrix3) -> bool {
matrix
.entries
.iter()
.all(|row| row.iter().all(|entry| entry.is_finite()))
}
fn diagonal_is_finite(diagonal: [f64; 3]) -> bool {
diagonal.iter().all(|entry| entry.is_finite())
}
const fn negative_guard_report(
old_wrong_path: &'static str,
) -> ForbiddenPolicyNegativeGuardReport {
ForbiddenPolicyNegativeGuardReport {
old_wrong_path,
rejected: true,
}
}
const fn map_qac_error(_error: QacError) -> ForbiddenPolicyError {
ForbiddenPolicyError::InvalidInput
}
}
pub mod envelope {
pub const ENVELOPE_MONITOR_JOURNEY_ID: &str = "J-ENVELOPE-MONITOR";
pub const ENVELOPE_MONITOR_STORY_ID: &str = "CCFV1-09";
pub const MIN_GATE_CONVERGENCE_OLD_WRONG_PATH: &str =
"Min-gate implies unconditional convergence";
pub const NO_TARGET_MOTION_TELEMETRY_OLD_WRONG_PATH: &str = "No target-motion telemetry";
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum EnvelopeStatus {
InsideEnvelope,
NotCertified,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct EnvelopeMonitorTick {
pub tick_id: u64,
pub previous_b_t: f64,
pub alpha_t: f64,
pub e_t: f64,
pub delta_t: f64,
pub kappa_t: f64,
pub monitored_assumptions_hold: bool,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct EnvelopeMonitorReport {
pub tick_id: u64,
pub previous_b_t: f64,
pub alpha_t: f64,
pub e_t: f64,
pub delta_t: f64,
pub kappa_t: f64,
pub b_t: f64,
pub status: EnvelopeStatus,
pub b_t_bounds_e_t: bool,
pub theorem_failure_claimed: bool,
pub convergence_claimed: bool,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct EnvelopeNegativeGuardReport {
pub old_wrong_path: &'static str,
pub rejected: bool,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum EnvelopeMonitorError {
InvalidInput,
NotImplemented,
}
pub fn compute_envelope_tick(
tick: &EnvelopeMonitorTick,
) -> Result<EnvelopeMonitorReport, EnvelopeMonitorError> {
validate_tick(tick)?;
let b_t = (1.0 - tick.alpha_t) * tick.previous_b_t + (tick.delta_t + tick.kappa_t);
if !b_t.is_finite() {
return Err(EnvelopeMonitorError::InvalidInput);
}
let b_t_bounds_e_t = b_t >= tick.e_t;
let status = if tick.monitored_assumptions_hold && b_t_bounds_e_t {
EnvelopeStatus::InsideEnvelope
} else {
EnvelopeStatus::NotCertified
};
Ok(EnvelopeMonitorReport {
tick_id: tick.tick_id,
previous_b_t: tick.previous_b_t,
alpha_t: tick.alpha_t,
e_t: tick.e_t,
delta_t: tick.delta_t,
kappa_t: tick.kappa_t,
b_t,
status,
b_t_bounds_e_t,
theorem_failure_claimed: false,
convergence_claimed: false,
})
}
pub fn reject_min_gate_unconditional_convergence(
) -> Result<EnvelopeNegativeGuardReport, EnvelopeMonitorError> {
Ok(negative_guard_report(MIN_GATE_CONVERGENCE_OLD_WRONG_PATH))
}
pub fn reject_missing_target_motion_telemetry(
) -> Result<EnvelopeNegativeGuardReport, EnvelopeMonitorError> {
Ok(negative_guard_report(
NO_TARGET_MOTION_TELEMETRY_OLD_WRONG_PATH,
))
}
fn validate_tick(tick: &EnvelopeMonitorTick) -> Result<(), EnvelopeMonitorError> {
if tick.tick_id == 0
|| !tick.previous_b_t.is_finite()
|| tick.previous_b_t < 0.0
|| !tick.alpha_t.is_finite()
|| !(0.0..=1.0).contains(&tick.alpha_t)
|| !tick.e_t.is_finite()
|| tick.e_t < 0.0
|| !tick.delta_t.is_finite()
|| tick.delta_t < 0.0
|| !tick.kappa_t.is_finite()
|| tick.kappa_t < 0.0
{
return Err(EnvelopeMonitorError::InvalidInput);
}
Ok(())
}
const fn negative_guard_report(old_wrong_path: &'static str) -> EnvelopeNegativeGuardReport {
EnvelopeNegativeGuardReport {
old_wrong_path,
rejected: true,
}
}
}
pub mod partition {
pub const LIVE_STATE_ENDPOINT_JOURNEY_ID: &str = "J-LIVE-STATE-ENDPOINT";
pub const STOER_WAGNER_PARTITION_STORY_ID: &str = "CCFV1-10";
pub const STOER_WAGNER_CANONICAL_SOURCE: &str = "stoer_wagner";
pub const COGNITUM_PARTITION_HINT_POLICY: &str = "hint_only";
pub const EXTERNAL_PARTITION_TRUSTED_OLD_WRONG_PATH: &str =
"External partition trusted without verification";
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct WeightedGraph4 {
pub weights: [[f64; 4]; 4],
}
impl WeightedGraph4 {
pub const fn new(weights: [[f64; 4]; 4]) -> Self {
Self { weights }
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Partition4 {
pub side: [bool; 4],
}
impl Partition4 {
pub const fn new(side: [bool; 4]) -> Self {
Self { side }
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PartitionVerificationInput4 {
pub graph: WeightedGraph4,
pub external_hint: Option<Partition4>,
pub disagreement_tolerance: usize,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PartitionTelemetryEvent {
None,
PartitionDisagreement,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PartitionVerificationReport4 {
pub min_cut_weight: f64,
pub canonical_partition: Partition4,
pub canonical_partition_source: &'static str,
pub cognitum_partition_hint: &'static str,
pub disagreement_distance: usize,
pub policy_tolerance: usize,
pub event: PartitionTelemetryEvent,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct PartitionNegativeGuardReport {
pub old_wrong_path: &'static str,
pub rejected: bool,
pub event: PartitionTelemetryEvent,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PartitionVerificationError {
InvalidInput,
NotImplemented,
}
pub fn verify_partition_4(
input: &PartitionVerificationInput4,
) -> Result<PartitionVerificationReport4, PartitionVerificationError> {
validate_input(input)?;
let min_cut = stoer_wagner_min_cut_4(input.graph)?;
let disagreement_distance = input
.external_hint
.map(|hint| partition_distance(min_cut.partition, hint))
.unwrap_or(0);
let event = if input.external_hint.is_some()
&& disagreement_distance > input.disagreement_tolerance
{
PartitionTelemetryEvent::PartitionDisagreement
} else {
PartitionTelemetryEvent::None
};
Ok(PartitionVerificationReport4 {
min_cut_weight: min_cut.weight,
canonical_partition: min_cut.partition,
canonical_partition_source: STOER_WAGNER_CANONICAL_SOURCE,
cognitum_partition_hint: COGNITUM_PARTITION_HINT_POLICY,
disagreement_distance,
policy_tolerance: input.disagreement_tolerance,
event,
})
}
pub fn reject_external_partition_trusted_without_verification(
input: &PartitionVerificationInput4,
) -> Result<PartitionNegativeGuardReport, PartitionVerificationError> {
let report = verify_partition_4(input)?;
Ok(PartitionNegativeGuardReport {
old_wrong_path: EXTERNAL_PARTITION_TRUSTED_OLD_WRONG_PATH,
rejected: input.external_hint.is_some()
&& report.event == PartitionTelemetryEvent::PartitionDisagreement,
event: report.event,
})
}
fn validate_input(
input: &PartitionVerificationInput4,
) -> Result<(), PartitionVerificationError> {
if input.disagreement_tolerance > 4 {
return Err(PartitionVerificationError::InvalidInput);
}
if input
.external_hint
.is_some_and(|partition| !partition_is_nontrivial(partition))
{
return Err(PartitionVerificationError::InvalidInput);
}
for row in 0..4 {
if input.graph.weights[row][row].abs() > 1.0e-12 {
return Err(PartitionVerificationError::InvalidInput);
}
for col in 0..4 {
let weight = input.graph.weights[row][col];
if !weight.is_finite() || weight < 0.0 {
return Err(PartitionVerificationError::InvalidInput);
}
if (input.graph.weights[row][col] - input.graph.weights[col][row]).abs() > 1.0e-12 {
return Err(PartitionVerificationError::InvalidInput);
}
}
}
Ok(())
}
#[derive(Clone, Copy, Debug, PartialEq)]
struct MinCut4 {
weight: f64,
partition: Partition4,
}
fn stoer_wagner_min_cut_4(
graph: WeightedGraph4,
) -> Result<MinCut4, PartitionVerificationError> {
let mut weights = graph.weights;
let mut groups = [
Partition4::new([true, false, false, false]),
Partition4::new([false, true, false, false]),
Partition4::new([false, false, true, false]),
Partition4::new([false, false, false, true]),
];
let mut active = [true; 4];
let mut best = MinCut4 {
weight: f64::INFINITY,
partition: Partition4::new([false, true, false, false]),
};
while active_count(active) > 1 {
let count = active_count(active);
let mut added = [false; 4];
let mut connection_weights = [0.0_f64; 4];
let mut previous = None;
for step in 0..count {
let selected = select_most_tightly_connected(active, added, connection_weights)
.ok_or(PartitionVerificationError::InvalidInput)?;
if step == count - 1 {
let source = previous.ok_or(PartitionVerificationError::InvalidInput)?;
let candidate = MinCut4 {
weight: connection_weights[selected],
partition: normalize_partition(groups[selected]),
};
if candidate.weight < best.weight
|| ((candidate.weight - best.weight).abs() <= 1.0e-12
&& partition_lex_less(candidate.partition, best.partition))
{
best = candidate;
}
merge_vertices(source, selected, &mut weights, &mut groups, &mut active);
} else {
added[selected] = true;
previous = Some(selected);
for vertex in 0..4 {
if active[vertex] && !added[vertex] {
connection_weights[vertex] += weights[selected][vertex];
}
}
}
}
}
if !best.weight.is_finite() {
return Err(PartitionVerificationError::InvalidInput);
}
Ok(best)
}
fn active_count(active: [bool; 4]) -> usize {
active.iter().filter(|is_active| **is_active).count()
}
fn select_most_tightly_connected(
active: [bool; 4],
added: [bool; 4],
connection_weights: [f64; 4],
) -> Option<usize> {
let mut selected: Option<usize> = None;
for vertex in 0..4 {
if !active[vertex] || added[vertex] {
continue;
}
if selected.is_none_or(|current| {
connection_weights[vertex] > connection_weights[current]
|| ((connection_weights[vertex] - connection_weights[current]).abs() <= 1.0e-12
&& vertex < current)
}) {
selected = Some(vertex);
}
}
selected
}
fn merge_vertices(
source: usize,
target: usize,
weights: &mut [[f64; 4]; 4],
groups: &mut [Partition4; 4],
active: &mut [bool; 4],
) {
for vertex in 0..4 {
groups[source].side[vertex] =
groups[source].side[vertex] || groups[target].side[vertex];
}
for vertex in 0..4 {
if active[vertex] && vertex != source && vertex != target {
weights[source][vertex] += weights[target][vertex];
weights[vertex][source] = weights[source][vertex];
}
}
active[target] = false;
}
fn normalize_partition(partition: Partition4) -> Partition4 {
if partition.side[0] {
let mut side = partition.side;
for entry in &mut side {
*entry = !*entry;
}
Partition4::new(side)
} else {
partition
}
}
fn partition_is_nontrivial(partition: Partition4) -> bool {
let first = partition.side[0];
partition.side.iter().any(|side| *side != first)
}
fn partition_distance(canonical: Partition4, hint: Partition4) -> usize {
let canonical = normalize_partition(canonical);
let hint = normalize_partition(hint);
let direct = hamming_distance(canonical, hint);
let complement = hamming_distance(canonical, complement_partition(hint));
direct.min(complement)
}
fn hamming_distance(left: Partition4, right: Partition4) -> usize {
let mut distance = 0;
for index in 0..4 {
if left.side[index] != right.side[index] {
distance += 1;
}
}
distance
}
fn complement_partition(partition: Partition4) -> Partition4 {
let mut side = partition.side;
for entry in &mut side {
*entry = !*entry;
}
Partition4::new(side)
}
fn partition_lex_less(left: Partition4, right: Partition4) -> bool {
for index in 0..4 {
match (left.side[index], right.side[index]) {
(false, true) => return true,
(true, false) => return false,
_ => {}
}
}
false
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ScaffoldReport {
pub version: &'static str,
pub journey_id: &'static str,
pub precheck_t: PrecheckReason,
pub kappa_hat_t: &'static str,
pub kappa_floor_t: &'static str,
pub alpha_t: &'static str,
pub rho: &'static str,
pub old_wrong_core_guard: &'static str,
}
pub const fn scaffold_report() -> ScaffoldReport {
ScaffoldReport {
version: CCF_CORE_V1_VERSION,
journey_id: CONTRACT_JOURNEY_ID,
precheck_t: PrecheckReason::ScaffoldOnly,
kappa_hat_t: "computed-from-update-matrices",
kappa_floor_t: "dynamic-floor-computed",
alpha_t: "rho(g_t)",
rho: "gate-coupled-rho",
old_wrong_core_guard: OLD_WRONG_CORE_GUARD,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn scaffold_report_pins_story_148_contract_values() {
let report = scaffold_report();
assert_eq!(report.version, "1.0.1");
assert_eq!(report.journey_id, "J-CORE-TEST-MATRIX");
assert_eq!(report.precheck_t, PrecheckReason::ScaffoldOnly);
assert_eq!(
report.old_wrong_core_guard,
"God-spec implementation with no enforceable contracts"
);
}
#[test]
fn scaffold_report_exposes_filed_prov6_vocabulary() {
let report = scaffold_report();
assert_eq!(report.kappa_hat_t, "computed-from-update-matrices");
assert_eq!(report.kappa_floor_t, "dynamic-floor-computed");
assert_eq!(report.alpha_t, "rho(g_t)");
assert_eq!(report.rho, "gate-coupled-rho");
}
}