use alloc::{
format,
string::{String, ToString},
vec,
vec::Vec,
};
use crate::{
algebra::{ResourceVector, WideResourceVector},
outcome::CandidatePhase,
wire::{BindingEpoch, ConnectionIncarnation, DeliverySeq, Generation},
};
use super::binding_fate_fixture::{
TwoExitClaims, two_identity_ledgers, two_identity_order_restore, two_identity_sequence_restore,
};
use super::binding_fate_tests::{frontier_owner_with_limit, ordinary_token};
use super::{
BindingFateMeasurementError, BindingFateTerminal, BindingTerminalAdmission,
BindingTerminalCauseClass, LiveFrontierError, LiveFrontierOwner,
};
use crate::lifecycle::{
ActiveBinding, AdmissionOrder, BindingTerminalDisposition, ClaimFrontiers,
ClaimFrontiersRestore, ClosureAccounting, ClosureState, CommittedDiedTerminal,
DiedBindingTransition, FrontierBinding, FrontierParticipant, MarkerProvenance,
RetainedCausalRecord, RetainedCausalRecordKind, RetainedRecordCharge, SealedBindingFateToken,
};
pub(super) const DEPARTED_PEER: u64 = 5;
fn generation(value: u64) -> Result<Generation, String> {
Generation::new(value).ok_or_else(|| "F8 fixture generation must be nonzero".to_string())
}
fn peer_epoch() -> Result<BindingEpoch, String> {
Ok(BindingEpoch::new(
ConnectionIncarnation::new(9, 1),
generation(1)?,
))
}
fn clear_accounting() -> Result<ClosureAccounting, String> {
ClosureAccounting::try_new(
ClosureState::Clear,
0,
0,
0,
0,
ResourceVector::default(),
WideResourceVector::default(),
ResourceVector::new(16, 1024),
0,
2,
)
.map_err(|error| format!("F8 fixture accounting refused: {error:?}"))
}
pub(super) fn committed_died_terminal(
active: ActiveBinding,
cursor: DeliverySeq,
) -> Result<CommittedDiedTerminal, String> {
let high_watermark = cursor
.checked_add(1)
.ok_or_else(|| "F8 terminal high watermark overflow".to_string())?;
let candidate_sequence = high_watermark
.checked_add(1)
.ok_or_else(|| "F8 committed terminal sequence overflow".to_string())?;
let owner = frontier_owner_with_limit(
active.conversation_id,
active.participant_id,
active.binding_epoch,
cursor,
high_watermark,
1,
)?;
let prepared = owner
.prepare_binding_terminal(
active,
BindingTerminalCauseClass::Died,
0,
candidate_sequence,
high_watermark,
)
.map_err(|refused| {
format!(
"F8 committed terminal prepare refused: {:?}",
refused.error()
)
})?;
let key = prepared.candidate_key();
let BindingTerminalAdmission::Commit(committed) =
prepared.admit(key.bind_v3_charge(ResourceVector::new(1, 73)))
else {
return Err("F8 Died selector did not commit the ordinary terminal".to_string());
};
let (owner, position) = committed.into_parts();
drop(owner);
let DiedBindingTransition::Committed(terminal) =
active.connection_lost(BindingTerminalDisposition::Committed(position))
else {
return Err("F8 committed selector position did not produce committed Died".to_string());
};
Ok(terminal)
}
fn marker_pinned_owner(
conversation_id: u64,
participant_id: u64,
binding_epoch: BindingEpoch,
cursor: DeliverySeq,
marker_seq: DeliverySeq,
charged: bool,
) -> Result<LiveFrontierOwner, String> {
if cursor >= marker_seq {
return Err(
"F8 fixture needs an UNACKED marker: P1's cursor must sit below it".to_string(),
);
}
let high_watermark = marker_seq;
let identity_slot_limit = participant_id
.max(DEPARTED_PEER)
.checked_add(1)
.ok_or_else(|| "F8 fixture identity slot limit overflow".to_string())?;
let claims = TwoExitClaims::above(high_watermark)?;
let (sequence, order) = two_identity_ledgers(high_watermark)?;
let marker_order = AdmissionOrder::new(0, CandidatePhase::CompactionMarker, participant_id);
let marker_record = RetainedCausalRecord {
delivery_seq: marker_seq,
admission_order: marker_order,
kind: RetainedCausalRecordKind::CompactionMarker {
participant_index: participant_id,
provenance: MarkerProvenance::NonProductM,
},
};
let frontiers = ClaimFrontiers::restore(
ClaimFrontiersRestore {
conversation_id,
active_identities: vec![
FrontierParticipant::new(
participant_id,
cursor,
FrontierBinding::Detached(binding_epoch),
),
FrontierParticipant::new(
DEPARTED_PEER,
high_watermark,
FrontierBinding::Detached(peer_epoch()?),
),
],
identity_slot_limit,
retained_floor: u128::from(marker_seq),
retained_record_limit: 2,
retained_records: vec![marker_record],
active_marker_anchors: vec![marker_seq],
historical_marker_deliveries: vec![],
historical_causal_facts: vec![],
sequence: two_identity_sequence_restore(claims, participant_id, DEPARTED_PEER),
order: two_identity_order_restore(participant_id, DEPARTED_PEER),
recovery_marker_delivery_seq: None,
},
sequence,
order,
)
.map_err(|error| format!("F8 fixture frontier refused: {error:?}"))?;
let retained_charges: Vec<RetainedRecordCharge> = if charged {
vec![RetainedRecordCharge::new(
marker_seq,
marker_order,
ResourceVector::new(1, 1),
)]
} else {
vec![]
};
Ok(LiveFrontierOwner::from_test_parts(
frontiers,
clear_accounting()?,
retained_charges,
2,
))
}
struct IncidentFixture {
owner: LiveFrontierOwner,
token: SealedBindingFateToken,
terminal: CommittedDiedTerminal,
marker_seq: DeliverySeq,
hard_observer_progress: DeliverySeq,
}
fn incident_fixture(charged: bool) -> Result<IncidentFixture, String> {
let (token, binding, cursor) = ordinary_token()?;
let marker_seq = cursor
.checked_add(1)
.ok_or_else(|| "F8 fixture marker sequence overflow".to_string())?;
let terminal = committed_died_terminal(binding, cursor)?;
let owner = marker_pinned_owner(
binding.conversation_id,
binding.participant_id,
binding.binding_epoch,
cursor,
marker_seq,
charged,
)?;
let hard_observer_progress = owner.frontiers().sequence().ledger().high_watermark();
Ok(IncidentFixture {
owner,
token,
terminal,
marker_seq,
hard_observer_progress,
})
}
fn refusal_of(charged: bool) -> Result<BindingFateMeasurementError, String> {
let fixture = incident_fixture(charged)?;
match fixture.owner.prepare_binding_fate(
fixture.token,
BindingFateTerminal::Ordinary(fixture.terminal),
fixture.hard_observer_progress,
) {
Ok(_) => Err(format!(
"F8 §3.3 pole expected a refused measurement (charged={charged}) and got a \
successful one — the fixture no longer mints the refusal it exists to \
discriminate"
)),
Err(refused) => Ok(refused.error()),
}
}
#[test]
fn a_retained_unacked_marker_pins_the_measured_floor() -> Result<(), String> {
let fixture = incident_fixture(true)?;
let marker_seq = fixture.marker_seq;
let prepared = fixture
.owner
.prepare_binding_fate(
fixture.token,
BindingFateTerminal::Ordinary(fixture.terminal),
fixture.hard_observer_progress,
)
.map_err(|refused| {
format!(
"F8 §3.1: a departing peer measured a floor across P1's retained unacked \
marker at {marker_seq} and the measurement refused: {:?}",
refused.error()
)
})?;
let measured_floor = prepared.fate().resulting_floor();
if measured_floor > marker_seq {
return Err(format!(
"F8 §3.1: the measured floor {measured_floor} crossed the retained marker at \
{marker_seq}"
));
}
let (owner, _, _) = prepared.into_parts();
if !owner
.frontiers()
.retained_marker_records()
.iter()
.any(|record| record.delivery_seq == marker_seq)
{
return Err(format!(
"F8 §3.1: the pinned marker at {marker_seq} was released by a measurement that \
was supposed to stop short of it"
));
}
Ok(())
}
#[test]
fn a_retained_charge_refusal_carries_its_own_cause() -> Result<(), String> {
let refused = refusal_of(false)?;
let BindingFateMeasurementError::OwnerTransition(cause) = refused else {
return Err(format!(
"F8 §3.3: a retained-charge mismatch did not refuse through the owner transition \
at all: {refused:?}"
));
};
if cause != LiveFrontierError::RetainedCharge {
return Err(format!(
"F8 §3.3: the owner-transition carrier arrived holding {cause:?}, but the refusal \
was raised by the retained-charge preflight at \
binding_fate_transition.rs:34 — the carrier is transporting the wrong cause"
));
}
Ok(())
}
#[test]
fn the_retired_precedence_pole_backstop_names_itself_if_it_ever_fires() -> Result<(), String> {
let fixture = incident_fixture(true)?;
match fixture.owner.prepare_binding_fate(
fixture.token,
BindingFateTerminal::Ordinary(fixture.terminal),
fixture.hard_observer_progress,
) {
Ok(_) => Ok(()),
Err(refused) => {
let error = refused.error();
if matches!(
error,
BindingFateMeasurementError::OwnerTransition(LiveFrontierError::Precedence)
) {
return Err(format!(
"F8 §3.3 BACKSTOP FIRING, BY NAME: the RETIRED Precedence premise has \
RETURNED. The §1 incident fixture refused with {error:?}, where §3.1's \
clamp should have carried the measurement through. This sentinel \
supersedes a_precedence_refusal_is_told_apart_from_its_four_siblings; if \
you are reading this, that retirement must be reconsidered — do not \
silence this test"
));
}
Err(format!(
"F8 §3.3 BACKSTOP, BY NAME: the §1 incident fixture stopped measuring, but NOT \
through the retired Precedence premise — it refused with {error:?}. The \
retirement still stands; the fixture does not. Report this, do not silence it"
))
}
}
}
#[test]
fn a_non_owner_transition_failure_stays_outside_the_owner_transition_carrier() -> Result<(), String>
{
let fixture = incident_fixture(true)?;
let refused = match fixture.owner.prepare_binding_fate(
fixture.token,
BindingFateTerminal::Recovered,
fixture.hard_observer_progress,
) {
Ok(_) => {
return Err(
"F8 §3.3 negative pole ONE: a Recovered terminal was accepted for an Ordinary \
token"
.to_string(),
);
}
Err(refused) => refused.error(),
};
if refused != BindingFateMeasurementError::Terminal {
return Err(format!(
"F8 §3.3 negative pole ONE: the terminal-class failure changed class: {refused:?}"
));
}
if matches!(refused, BindingFateMeasurementError::OwnerTransition { .. }) {
return Err(format!(
"F8 §3.3 negative pole ONE: a non-owner-transition failure wore the owner-transition \
carrier: {refused:?}"
));
}
Ok(())
}