use alloc::{
format,
string::{String, ToString},
vec,
vec::Vec,
};
use crate::{
algebra::{ResourceVector, WideResourceVector},
outcome::CandidatePhase,
wire::{BindingEpoch, ConnectionIncarnation, DeliverySeq, Generation},
};
use super::LiveFrontierOwner;
use super::binding_fate_f8_tests::{DEPARTED_PEER, committed_died_terminal};
use super::binding_fate_fixture::{
TwoExitClaims, two_identity_ledgers, two_identity_order_restore, two_identity_sequence_restore,
};
use super::binding_fate_tests::ordinary_token;
use crate::lifecycle::{
AdmissionOrder, ClaimFrontiers, ClaimFrontiersRestore, ClosureAccounting, ClosureState,
CommittedDiedTerminal, FrontierBinding, FrontierParticipant, MarkerProvenance,
PendingDiedOrdinaryFinalizer, RetainedCausalRecord, RetainedCausalRecordKind,
RetainedRecordCharge,
};
#[derive(Clone, Copy, PartialEq, Eq)]
enum SuffixRow {
Marker,
Ordinary,
}
fn generation(value: u64) -> Result<Generation, String> {
Generation::new(value).ok_or_else(|| "finalizer fixture generation must be nonzero".to_string())
}
fn peer_epoch() -> Result<BindingEpoch, String> {
Ok(BindingEpoch::new(
ConnectionIncarnation::new(9, 1),
generation(1)?,
))
}
const SUFFIX_CHARGE: ResourceVector = ResourceVector::new(1, 1);
fn clear_accounting() -> Result<ClosureAccounting, String> {
ClosureAccounting::try_new(
ClosureState::Clear,
0,
0,
0,
0,
ResourceVector::default(),
WideResourceVector::new(
u128::from(SUFFIX_CHARGE.entries),
u128::from(SUFFIX_CHARGE.bytes),
),
ResourceVector::new(16, 1024),
0,
2,
)
.map_err(|error| format!("finalizer fixture accounting refused: {error:?}"))
}
fn suffix_frontier(
conversation_id: u64,
participant_id: u64,
binding_epoch: BindingEpoch,
cursor: DeliverySeq,
suffix_seq: DeliverySeq,
row: SuffixRow,
) -> Result<LiveFrontierOwner, String> {
if cursor >= suffix_seq {
return Err(
"finalizer fixture needs an UNACKED suffix: the cursor must sit below it".to_string(),
);
}
let high_watermark = suffix_seq;
let identity_slot_limit = participant_id
.max(DEPARTED_PEER)
.checked_add(1)
.ok_or_else(|| "finalizer fixture identity slot limit overflow".to_string())?;
let claims = TwoExitClaims::above(high_watermark)?;
let (sequence, order) = two_identity_ledgers(high_watermark)?;
let (phase, kind) = match row {
SuffixRow::Marker => (
CandidatePhase::CompactionMarker,
RetainedCausalRecordKind::CompactionMarker {
participant_index: participant_id,
provenance: MarkerProvenance::NonProductM,
},
),
SuffixRow::Ordinary => (
CandidatePhase::OrdinaryRecord,
RetainedCausalRecordKind::OrdinaryRecord {
participant_index: participant_id,
},
),
};
let suffix_order = AdmissionOrder::new(0, phase, participant_id);
let suffix_record = RetainedCausalRecord {
delivery_seq: suffix_seq,
admission_order: suffix_order,
kind,
};
let active_marker_anchors = match row {
SuffixRow::Marker => vec![suffix_seq],
SuffixRow::Ordinary => vec![],
};
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(suffix_seq),
retained_record_limit: 2,
retained_records: vec![suffix_record],
active_marker_anchors,
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!("finalizer fixture frontier refused: {error:?}"))?;
let retained_charges: Vec<RetainedRecordCharge> = vec![RetainedRecordCharge::new(
suffix_seq,
suffix_order,
SUFFIX_CHARGE,
)];
Ok(LiveFrontierOwner::from_test_parts(
frontiers,
clear_accounting()?,
retained_charges,
2,
))
}
struct MeasuredFinalizer {
finalizer: PendingDiedOrdinaryFinalizer,
measured_floor: DeliverySeq,
}
fn measured_finalizer(
row: SuffixRow,
suffix_seq_from_cursor: u64,
) -> Result<MeasuredFinalizer, String> {
let (token, binding, cursor) = ordinary_token()?;
let suffix_seq = cursor
.checked_add(suffix_seq_from_cursor)
.ok_or_else(|| "finalizer fixture suffix sequence overflow".to_string())?;
let terminal: CommittedDiedTerminal = committed_died_terminal(binding, cursor)?;
let owner = suffix_frontier(
binding.conversation_id,
binding.participant_id,
binding.binding_epoch,
cursor,
suffix_seq,
row,
)?;
let hard_observer_progress = owner.frontiers().sequence().ledger().high_watermark();
let prepared = owner
.prepare_pending_died_ordinary_finalizer(token, terminal, hard_observer_progress)
.map_err(|refused| {
format!(
"PRECEDENCE-CLAMP fixture: the finalizer measurement itself refused: {:?}",
refused.error()
)
})?;
let (_, fate, finalizer) = prepared.into_parts();
Ok(MeasuredFinalizer {
measured_floor: fate.resulting_floor(),
finalizer,
})
}
#[test]
fn a_floor_subsumed_while_the_finalizer_waited_installs_as_a_no_op() -> Result<(), String> {
let (_, binding, cursor) = ordinary_token()?;
let measured = measured_finalizer(SuffixRow::Marker, 1)?;
let marker_seq = cursor
.checked_add(1)
.ok_or_else(|| "fixture marker sequence overflow".to_string())?;
if measured.measured_floor != marker_seq {
return Err(format!(
"PRECEDENCE-CLAMP M1a: the fixture's frozen floor is {} and not the pinned marker at \
{marker_seq} — the premise moved",
measured.measured_floor
));
}
let advanced_seq = marker_seq
.checked_add(1)
.ok_or_else(|| "fixture advanced sequence overflow".to_string())?;
let advanced = suffix_frontier(
binding.conversation_id,
binding.participant_id,
binding.binding_epoch,
cursor,
advanced_seq,
SuffixRow::Ordinary,
)?;
let retained_floor_before = advanced.frontiers().retained_floor();
let owner = advanced
.complete_pending_died_ordinary_finalizer(measured.finalizer)
.map_err(|error| {
format!(
"PRECEDENCE-CLAMP M1a: a fate floor of {} was subsumed by a retained floor that \
had already advanced to {retained_floor_before}, and the finalizer refused \
{error:?} instead of treating it as the no-op it is. The enclosing source row is \
durable, so this refusal repeats on every boot, forever",
measured.measured_floor
)
})?;
let retained_floor_after = owner.frontiers().retained_floor();
if retained_floor_after != retained_floor_before {
return Err(format!(
"PRECEDENCE-CLAMP M1a: a subsumed fate floor moved the retained floor from \
{retained_floor_before} to {retained_floor_after}. A subsumed floor installs NOTHING; \
driving it backwards would eat rows the frontier still owes"
));
}
Ok(())
}
#[test]
fn a_marker_retained_while_the_finalizer_waited_pins_the_installed_floor() -> Result<(), String> {
let (_, binding, cursor) = ordinary_token()?;
let measured = measured_finalizer(SuffixRow::Ordinary, 1)?;
let marker_seq = cursor
.checked_add(1)
.ok_or_else(|| "fixture marker sequence overflow".to_string())?;
let expected_floor = marker_seq
.checked_add(1)
.ok_or_else(|| "fixture measured floor overflow".to_string())?;
if measured.measured_floor != expected_floor {
return Err(format!(
"PRECEDENCE-CLAMP M1: the unpinned fixture froze a floor of {} rather than \
{expected_floor} — the premise moved",
measured.measured_floor
));
}
let pinned = suffix_frontier(
binding.conversation_id,
binding.participant_id,
binding.binding_epoch,
cursor,
marker_seq,
SuffixRow::Marker,
)?;
let owner = pinned
.complete_pending_died_ordinary_finalizer(measured.finalizer)
.map_err(|error| {
format!(
"PRECEDENCE-CLAMP M1: a frozen floor of {} crossed a marker retained at \
{marker_seq} while the finalizer waited, and the second enforcer refused \
{error:?}. The enclosing source row is durable, so this refusal repeats on every \
boot, forever",
measured.measured_floor
)
})?;
let installed = owner.frontiers().retained_floor();
if installed != u128::from(marker_seq) {
return Err(format!(
"PRECEDENCE-CLAMP M1/M2: the installed floor is {installed}, not the pinned marker at \
{marker_seq}. Clamping short of the marker silently destroys a legal floor advance; \
clamping past it eats the marker"
));
}
if !owner
.frontiers()
.retained_marker_records()
.iter()
.any(|record| record.delivery_seq == marker_seq)
{
return Err(format!(
"PRECEDENCE-CLAMP M1: the marker at {marker_seq} was released by a finalizer that was \
supposed to stop exactly at it"
));
}
Ok(())
}
#[test]
fn an_uncontested_finalizer_floor_installs_unchanged() -> Result<(), String> {
let (_, binding, cursor) = ordinary_token()?;
let measured = measured_finalizer(SuffixRow::Ordinary, 1)?;
let suffix_seq = cursor
.checked_add(1)
.ok_or_else(|| "fixture suffix sequence overflow".to_string())?;
let unchanged = suffix_frontier(
binding.conversation_id,
binding.participant_id,
binding.binding_epoch,
cursor,
suffix_seq,
SuffixRow::Ordinary,
)?;
let owner = unchanged
.complete_pending_died_ordinary_finalizer(measured.finalizer)
.map_err(|error| {
format!("PRECEDENCE-CLAMP F5: an uncontested finalizer floor refused: {error:?}")
})?;
let installed = owner.frontiers().retained_floor();
if installed != u128::from(measured.measured_floor) {
return Err(format!(
"PRECEDENCE-CLAMP F5: an uncontested floor of {} installed as {installed}. Marker-free \
floors must be byte-identical to the pre-clamp tree",
measured.measured_floor
));
}
Ok(())
}