use std::collections::{BTreeMap, BTreeSet};
use time::OffsetDateTime;
use crate::aggregation::{AggregationError, ReleasedTotals, aggregate_released_with_carry};
use crate::dedup::{DedupDecision, DedupStore, DedupWindow, RecordKey};
use crate::disposition::{
BatchReconciliation, Disposition, HoldReason, RejectReason, SuppressReason,
};
use crate::lateness::Lateness;
use crate::partial::{PartialRun, Reassembly};
use crate::quality::{QualityReport, score_batch};
use crate::record::{NodeId, UsageRecord};
use crate::sequence::{SequenceObservation, SequenceSpace, SequenceTracker};
use crate::validation::{Finding, Rule, ValidationConfig, ValidationReport, validate_records};
pub trait Suppression {
fn suppress(&self, record: &UsageRecord) -> Option<SuppressReason>;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct NoSuppression;
impl Suppression for NoSuppression {
fn suppress(&self, _record: &UsageRecord) -> Option<SuppressReason> {
None
}
}
impl<F> Suppression for F
where
F: Fn(&UsageRecord) -> Option<SuppressReason>,
{
fn suppress(&self, record: &UsageRecord) -> Option<SuppressReason> {
self(record)
}
}
#[derive(Debug, Clone, Default)]
pub struct ProcessConfig {
pub validation: ValidationConfig,
pub suppress_zero_usage: bool,
}
impl ProcessConfig {
#[must_use]
pub fn suppressing_zero_usage(mut self) -> Self {
self.suppress_zero_usage = true;
self
}
}
#[derive(Debug, Clone, Copy)]
pub struct Batch<'a> {
records: &'a [UsageRecord],
carried_in: usize,
}
impl<'a> Batch<'a> {
#[must_use]
pub const fn new(records: &'a [UsageRecord]) -> Self {
Self {
records,
carried_in: 0,
}
}
#[must_use]
pub const fn with_carry(records: &'a [UsageRecord], carried_in: usize) -> Option<Self> {
if carried_in > records.len() {
None
} else {
Some(Self {
records,
carried_in,
})
}
}
#[must_use]
pub const fn records(&self) -> &'a [UsageRecord] {
self.records
}
#[must_use]
pub const fn carried_in(&self) -> usize {
self.carried_in
}
#[must_use]
pub const fn ingested(&self) -> usize {
self.records.len() - self.carried_in
}
#[must_use]
pub const fn is_carried(&self, index: usize) -> bool {
index < self.carried_in
}
}
#[derive(Debug, Clone)]
pub struct ProcessState {
dedup: DedupStore,
space: SequenceSpace,
sequences: BTreeMap<NodeId, SequenceTracker>,
}
impl ProcessState {
#[must_use]
pub fn new(window: DedupWindow) -> Self {
Self::in_space(window, SequenceSpace::U32)
}
#[must_use]
pub fn in_space(window: DedupWindow, space: SequenceSpace) -> Self {
Self {
dedup: DedupStore::new(window),
space,
sequences: BTreeMap::new(),
}
}
#[must_use]
pub const fn dedup(&self) -> &DedupStore {
&self.dedup
}
pub const fn dedup_mut(&mut self) -> &mut DedupStore {
&mut self.dedup
}
#[must_use]
pub fn tracker(&self, node: &NodeId) -> Option<&SequenceTracker> {
self.sequences.get(node)
}
pub fn trackers(&self) -> impl Iterator<Item = (&NodeId, &SequenceTracker)> {
self.sequences.iter()
}
#[must_use]
pub fn with_tracker(mut self, node: NodeId, tracker: SequenceTracker) -> Option<Self> {
if tracker.space() != self.space {
return None;
}
self.sequences.insert(node, tracker);
Some(self)
}
#[must_use]
pub fn with_dedup(mut self, dedup: DedupStore) -> Self {
self.dedup = dedup;
self
}
#[must_use]
pub const fn space(&self) -> SequenceSpace {
self.space
}
pub fn incomplete_sources(&self) -> impl Iterator<Item = (&NodeId, &SequenceTracker)> {
self.sequences
.iter()
.filter(|(_, tracker)| !tracker.is_complete())
}
#[must_use]
pub fn is_complete(&self) -> bool {
self.sequences.values().all(SequenceTracker::is_complete)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SequenceGap {
pub node: NodeId,
pub missing: Vec<u32>,
pub missing_count: u64,
}
impl SequenceGap {
#[must_use]
pub fn is_truncated(&self) -> bool {
self.missing_count > self.missing.len() as u64
}
}
#[derive(Debug, Clone)]
pub struct ProcessOutcome {
dispositions: Vec<Disposition>,
carried_in: usize,
reconciliation: BatchReconciliation,
findings: ValidationReport,
quality: QualityReport,
totals: Result<ReleasedTotals, AggregationError>,
gaps: Vec<SequenceGap>,
}
impl ProcessOutcome {
#[must_use]
pub fn dispositions(&self) -> &[Disposition] {
&self.dispositions
}
#[must_use]
pub fn carried_dispositions(&self) -> &[Disposition] {
&self.dispositions[..self.carried_in]
}
#[must_use]
pub fn ingested_dispositions(&self) -> &[Disposition] {
&self.dispositions[self.carried_in..]
}
#[must_use]
pub const fn reconciliation(&self) -> &BatchReconciliation {
&self.reconciliation
}
#[must_use]
pub const fn findings(&self) -> &ValidationReport {
&self.findings
}
#[must_use]
pub const fn quality(&self) -> &QualityReport {
&self.quality
}
pub fn totals(&self) -> Result<ReleasedTotals, AggregationError> {
self.totals
}
#[must_use]
pub fn sequence_gaps(&self) -> &[SequenceGap] {
&self.gaps
}
#[must_use]
pub const fn is_releasable(&self) -> bool {
!self.quality.blocks_release()
}
}
#[must_use]
pub fn process(
batch: &Batch<'_>,
config: &ProcessConfig,
as_of: OffsetDateTime,
state: &mut ProcessState,
) -> ProcessOutcome {
process_with(batch, config, as_of, state, &NoSuppression)
}
#[must_use]
pub fn process_with(
batch: &Batch<'_>,
config: &ProcessConfig,
as_of: OffsetDateTime,
state: &mut ProcessState,
suppression: &impl Suppression,
) -> ProcessOutcome {
let records = batch.records();
let mut findings = validate_records(records, &config.validation, as_of);
let stateless = findings.clone();
let gaps = observe_sequences(records, state, &mut findings);
let incomplete = incomplete_sources(records, state);
let runs = assess_runs(records);
let mut dispositions = Vec::with_capacity(records.len());
let mut reconciliation = BatchReconciliation::EMPTY;
for (index, record) in records.iter().enumerate() {
let carried = batch.is_carried(index);
let disposition = disposition_for(
index,
record,
carried,
config,
as_of,
state,
&stateless,
&runs,
&incomplete,
suppression,
&mut findings,
);
if carried {
reconciliation.observe_carried(&disposition);
} else {
reconciliation.observe(&disposition);
}
dispositions.push(disposition);
}
findings.apply(&config.validation);
let quality = score_batch(&reconciliation, &findings, true);
let totals = aggregate_released_with_carry(records, &dispositions, batch.carried_in());
ProcessOutcome {
dispositions,
carried_in: batch.carried_in(),
reconciliation,
findings,
quality,
totals,
gaps,
}
}
#[allow(clippy::too_many_arguments)]
fn disposition_for(
index: usize,
record: &UsageRecord,
carried: bool,
config: &ProcessConfig,
as_of: OffsetDateTime,
state: &mut ProcessState,
stateless: &ValidationReport,
runs: &BTreeMap<RecordKey, Reassembly>,
incomplete: &BTreeSet<NodeId>,
suppression: &impl Suppression,
findings: &mut ValidationReport,
) -> Disposition {
let key = match RecordKey::of(record) {
Ok(key) => key,
Err(reason) => {
findings.push(Finding::not_keyable(index, reason));
return Disposition::Rejected(RejectReason::NotKeyable(reason));
}
};
if !carried
&& let DedupDecision::Duplicate { .. } =
state.dedup.observe(key.clone(), record.opened.to_utc())
{
findings.push(Finding::duplicate(index, &key));
return Disposition::Duplicate(key);
}
if let Some(reason) = record.party.unattributable_reason() {
return Disposition::Rejected(RejectReason::Unattributable(reason));
}
match config
.validation
.lateness
.classify(record.opened.to_utc(), as_of)
{
Lateness::Future(_) => return Disposition::Rejected(RejectReason::FutureTimestamp),
Lateness::BeyondDeadline(_) => {
return Disposition::Rejected(RejectReason::BeyondDeadline);
}
Lateness::OnTime | Lateness::Late(_) => {}
}
if stateless.record_blocked(index) {
return Disposition::Rejected(RejectReason::Malformed);
}
if record.partial.is_some()
&& let Some(scope) = key.session_scope()
&& let Some(assessment) = runs.get(&scope)
{
match assessment {
Reassembly::Orphan { .. } => {
return Disposition::Rejected(RejectReason::Malformed);
}
Reassembly::Incomplete { .. } => {
return Disposition::Held(HoldReason::AwaitingPartial);
}
Reassembly::Complete { .. } | Reassembly::Empty => {}
}
}
if let Some(reason) = suppression.suppress(record) {
return Disposition::Suppressed(reason);
}
if config.suppress_zero_usage && record.is_zero_usage() {
return Disposition::Suppressed(SuppressReason::ZeroUsage);
}
if incomplete.contains(&record.provenance.node_id) {
return Disposition::Held(HoldReason::SequenceGap);
}
Disposition::Billable
}
fn observe_sequences(
records: &[UsageRecord],
state: &mut ProcessState,
findings: &mut ValidationReport,
) -> Vec<SequenceGap> {
let mut seen: BTreeSet<(&NodeId, u32)> = BTreeSet::new();
let mut gaps: Vec<SequenceGap> = Vec::new();
for record in records {
let Some(sequence) = record.provenance.file_sequence else {
continue;
};
let node = &record.provenance.node_id;
if !seen.insert((node, sequence)) {
continue;
}
let tracker = state
.sequences
.entry(node.clone())
.or_insert_with(|| SequenceTracker::new(state.space));
if let SequenceObservation::Gap {
missing,
missing_count,
} = tracker.observe_default(sequence)
{
findings.push(Finding::sequence_gap(node, &missing, missing_count));
gaps.push(SequenceGap {
node: node.clone(),
missing,
missing_count,
});
}
}
gaps
}
fn incomplete_sources(records: &[UsageRecord], state: &ProcessState) -> BTreeSet<NodeId> {
let mut found = BTreeSet::new();
for record in records {
let node = &record.provenance.node_id;
if found.contains(node) {
continue;
}
if state
.sequences
.get(node)
.is_some_and(|tracker| !tracker.is_complete())
{
found.insert(node.clone());
}
}
found
}
fn assess_runs(records: &[UsageRecord]) -> BTreeMap<RecordKey, Reassembly> {
let mut runs: BTreeMap<RecordKey, PartialRun> = BTreeMap::new();
for record in records {
let (Some(partial), Ok(key)) = (record.partial, RecordKey::of(record)) else {
continue;
};
let Some(scope) = key.session_scope() else {
continue;
};
runs.entry(scope).or_default().push(partial);
}
runs.into_iter()
.map(|(scope, run)| {
let assessment = run.assess();
(scope, assessment)
})
.collect()
}
#[must_use]
pub fn reassembly_finding(record_index: usize, assessment: &Reassembly) -> Option<Finding> {
Finding::reassembly(record_index, assessment)
}
#[must_use]
pub const fn rule_for(disposition: &Disposition) -> Option<Rule> {
match disposition {
Disposition::Duplicate(_) => Some(Rule::DuplicateRecord),
Disposition::Rejected(RejectReason::NotKeyable(_)) => Some(Rule::NotKeyable),
Disposition::Rejected(RejectReason::Unattributable(_)) => Some(Rule::UnattributableParty),
Disposition::Rejected(RejectReason::BeyondDeadline) => Some(Rule::BeyondDeadline),
Disposition::Rejected(RejectReason::FutureTimestamp) => Some(Rule::FutureTimestamp),
Disposition::Held(HoldReason::AwaitingPartial) => Some(Rule::IncompleteReassembly),
Disposition::Held(HoldReason::SequenceGap) => Some(Rule::SequenceGap),
_ => None,
}
}
#[cfg(feature = "serde")]
mod serde_impl {
use super::{ProcessState, SequenceGap};
use crate::dedup::DedupStore;
use crate::record::NodeId;
use crate::sequence::{SequenceSpace, SequenceTracker};
use serde::de;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::collections::BTreeMap;
#[derive(Serialize, Deserialize)]
#[serde(rename = "ProcessState")]
struct StateRepr {
dedup: DedupStore,
space: SequenceSpace,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
sequences: BTreeMap<NodeId, SequenceTracker>,
}
impl Serialize for ProcessState {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
StateRepr {
dedup: self.dedup().clone(),
space: self.space(),
sequences: self
.trackers()
.map(|(node, tracker)| (node.clone(), tracker.clone()))
.collect(),
}
.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for ProcessState {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let r = StateRepr::deserialize(deserializer)?;
let mut state =
ProcessState::in_space(r.dedup.window(), r.space).with_dedup(r.dedup.clone());
for (node, tracker) in r.sequences {
state = state.with_tracker(node, tracker).ok_or_else(|| {
de::Error::custom("every tracker to follow the state's own sequence space")
})?;
}
Ok(state)
}
}
#[derive(Serialize, Deserialize)]
#[serde(rename = "SequenceGap")]
struct Repr {
node: NodeId,
missing: Vec<u32>,
missing_count: u64,
}
impl Serialize for SequenceGap {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
Repr {
node: self.node.clone(),
missing: self.missing.clone(),
missing_count: self.missing_count,
}
.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for SequenceGap {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let r = Repr::deserialize(deserializer)?;
Ok(SequenceGap {
node: r.node,
missing: r.missing,
missing_count: r.missing_count,
})
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::correlation::{ChargingId, CorrelationKeys};
use crate::partial::{PartialFormat, PartialInfo, RecordClosureCause};
use crate::party::{ChargedParty, SubscriberRef};
use crate::record::{RecordType, SourceRef};
use crate::volume::{Octets, VolumePair};
use std::net::Ipv4Addr;
use time::{Duration, macros::datetime};
const NOW: OffsetDateTime = datetime!(2026-07-28 12:00:00 UTC);
fn window() -> DedupWindow {
DedupWindow::from_bound(Duration::days(7)).expect("positive")
}
fn session(charging_id: u32) -> UsageRecord {
UsageRecord::new(
RecordType::PduSession,
ChargedParty::Subscriber(SubscriberRef::new("imsi-262021234567890".parse().unwrap())),
"2026-07-28T10:00:00+02:00".parse().unwrap(),
SourceRef::new("pgw-01".parse().unwrap(), 0).with_file_sequence(1),
)
.with_closed("2026-07-28T10:30:00+02:00".parse().unwrap())
.with_volume(VolumePair::new(Octets::new(1_000), Octets::new(4_000)))
.with_correlation(
CorrelationKeys::default()
.with_charging_id(ChargingId::new(charging_id))
.with_gateway(Ipv4Addr::new(10, 0, 0, 1).into()),
)
}
#[test]
fn a_clean_batch_releases_and_balances() {
let records: Vec<UsageRecord> = (1..=5).map(session).collect();
let mut state = ProcessState::new(window());
let outcome = process(
&Batch::new(&records),
&ProcessConfig::default(),
NOW,
&mut state,
);
assert_eq!(outcome.reconciliation().released(), 5);
assert!(outcome.reconciliation().balances());
assert!(outcome.is_releasable());
assert_eq!(outcome.totals().unwrap().total().records(), 5);
}
#[test]
fn deduplication_runs_before_judgement() {
let mut broken = session(1);
broken.closed = Some("2026-07-28T09:00:00+02:00".parse().unwrap()); let records = vec![broken.clone(), broken];
let mut state = ProcessState::new(window());
let outcome = process(
&Batch::new(&records),
&ProcessConfig::default(),
NOW,
&mut state,
);
assert_eq!(outcome.reconciliation().rejected(), 1);
assert_eq!(outcome.reconciliation().duplicate(), 1);
assert!(outcome.reconciliation().balances());
}
#[test]
fn an_unkeyable_record_is_rejected_first() {
let bare = UsageRecord::new(
RecordType::PduSession,
ChargedParty::Subscriber(SubscriberRef::new("imsi-262021234567890".parse().unwrap())),
"2026-07-28T10:00:00+02:00".parse().unwrap(),
SourceRef::new("pgw-01".parse().unwrap(), 0),
);
let records = vec![bare];
let mut state = ProcessState::new(window());
let outcome = process(
&Batch::new(&records),
&ProcessConfig::default(),
NOW,
&mut state,
);
assert_eq!(outcome.reconciliation().rejected(), 1);
assert!(matches!(
outcome.dispositions()[0],
Disposition::Rejected(RejectReason::NotKeyable(_))
));
assert!(outcome.findings().has(Rule::NotKeyable));
}
#[test]
fn an_unfinished_partial_run_is_held_in_full() {
let mut first = session(7);
first.partial = Some(PartialInfo::new(
1,
PartialFormat::FullyQualified,
RecordClosureCause::VolumeLimit,
));
first.correlation.record_sequence_number = Some(1);
let mut second = session(7);
second.partial = Some(PartialInfo::new(
2,
PartialFormat::Reduced,
RecordClosureCause::VolumeLimit,
));
second.correlation.record_sequence_number = Some(2);
let records = vec![first, second];
let mut state = ProcessState::new(window());
let outcome = process(
&Batch::new(&records),
&ProcessConfig::default(),
NOW,
&mut state,
);
assert_eq!(outcome.reconciliation().held(), 2);
assert_eq!(outcome.reconciliation().released(), 0);
assert!(outcome.reconciliation().balances());
assert!(
!outcome.quality().is_final(),
"a held record reopens a period"
);
}
#[test]
fn a_sequence_hole_holds_its_own_source() {
let mut first = session(1);
first.provenance = first.provenance.clone().with_file_sequence(1);
let mut third = session(2);
third.provenance = third.provenance.clone().with_file_sequence(3);
let records = vec![first, third];
let mut state = ProcessState::new(window());
let outcome = process(
&Batch::new(&records),
&ProcessConfig::default(),
NOW,
&mut state,
);
assert_eq!(outcome.sequence_gaps().len(), 1);
assert_eq!(outcome.sequence_gaps()[0].missing, vec![2]);
assert_eq!(outcome.sequence_gaps()[0].missing_count, 1);
assert!(outcome.findings().has(Rule::SequenceGap));
assert_eq!(
outcome.dispositions(),
&[
Disposition::Held(HoldReason::SequenceGap),
Disposition::Held(HoldReason::SequenceGap),
]
);
assert_eq!(outcome.reconciliation().released(), 0);
assert!(outcome.reconciliation().balances());
assert!(!state.is_complete());
}
#[test]
fn a_sequence_hole_can_be_escalated_to_block_the_batch() {
let mut first = session(1);
first.provenance = first.provenance.clone().with_file_sequence(1);
let mut third = session(2);
third.provenance = third.provenance.clone().with_file_sequence(3);
let records = vec![first, third];
let mut state = ProcessState::new(window());
let config = ProcessConfig {
validation: ValidationConfig::default().escalating(Rule::SequenceGap),
..ProcessConfig::default()
};
let outcome = process(&Batch::new(&records), &config, NOW, &mut state);
assert_eq!(
outcome.findings().severity_of(Rule::SequenceGap),
Some(crate::validation::Severity::Blocking),
"escalation reaches the stateful rules too"
);
assert!(!outcome.is_releasable());
}
#[test]
fn a_carried_record_is_not_counted_as_newly_ingested() {
let records: Vec<UsageRecord> = (1..=3).map(session).collect();
let batch = Batch::with_carry(&records, 1).unwrap();
let mut state = ProcessState::new(window());
let outcome = process(&batch, &ProcessConfig::default(), NOW, &mut state);
assert_eq!(outcome.reconciliation().carried_in(), 1);
assert_eq!(outcome.reconciliation().ingested(), 2);
assert_eq!(outcome.carried_dispositions().len(), 1);
assert_eq!(outcome.ingested_dispositions().len(), 2);
assert!(outcome.reconciliation().balances());
assert!(Batch::with_carry(&records, 4).is_none());
}
#[test]
fn a_suppression_policy_is_the_callers() {
let records: Vec<UsageRecord> = (1..=3).map(session).collect();
let mut state = ProcessState::new(window());
let only_the_first = |record: &UsageRecord| {
(record.correlation.charging_id == Some(ChargingId::new(1)))
.then_some(SuppressReason::TestIdentity)
};
let outcome = process_with(
&Batch::new(&records),
&ProcessConfig::default(),
NOW,
&mut state,
&only_the_first,
);
assert_eq!(outcome.reconciliation().suppressed(), 1);
assert_eq!(outcome.reconciliation().released(), 2);
assert!(outcome.reconciliation().balances());
}
#[test]
fn every_record_reaches_exactly_one_outcome() {
let mut records: Vec<UsageRecord> = (1..=4).map(session).collect();
records.push(session(1)); records.push(UsageRecord::new(
RecordType::PduSession,
ChargedParty::Unattributable(crate::party::UnattributableReason::IdentityAbsent),
"2026-07-28T10:00:00+02:00".parse().unwrap(),
SourceRef::new("pgw-01".parse().unwrap(), 9),
)); let mut ancient = session(9);
ancient.opened = "2026-01-01T10:00:00+02:00".parse().unwrap();
records.push(ancient);
let mut state = ProcessState::new(window());
let outcome = process(
&Batch::new(&records),
&ProcessConfig::default(),
NOW,
&mut state,
);
assert_eq!(outcome.dispositions().len(), records.len());
assert_eq!(
outcome.reconciliation().presented(),
Some(records.len() as u64)
);
assert!(outcome.reconciliation().balances());
}
}