use std::fmt;
use time::OffsetDateTime;
use crate::cdrtime::CdrTimestamp;
use crate::dedup::{NotKeyable, RecordKey};
use crate::jurisdiction::{Ambiguity, usage_country};
use crate::lateness::{Lateness, LatenessPolicy};
use crate::partial::{OrphanReason, Reassembly};
use crate::record::{PrimaryMeasure, UsageRecord};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Rule {
UnassignedOffset,
FutureTimestamp,
ClosedBeforeOpened,
DurationExceedsSpan,
ImplausibleVolume,
ZeroUsage,
ContainerSumMismatch,
UnattributableParty,
NotKeyable,
BeyondDeadline,
LateArrival,
ServingNetworkAbsent,
QuantityDoesNotMatchService,
CheckDigitFailure,
VolumeOverflow,
UnorderedSeries,
DuplicateRecord,
SequenceGap,
OrphanPartial,
IncompleteReassembly,
JurisdictionConflict,
}
impl Rule {
pub const ALL: &'static [Self] = &[
Self::UnassignedOffset,
Self::FutureTimestamp,
Self::ClosedBeforeOpened,
Self::DurationExceedsSpan,
Self::ImplausibleVolume,
Self::ZeroUsage,
Self::ContainerSumMismatch,
Self::UnattributableParty,
Self::NotKeyable,
Self::BeyondDeadline,
Self::LateArrival,
Self::ServingNetworkAbsent,
Self::QuantityDoesNotMatchService,
Self::CheckDigitFailure,
Self::VolumeOverflow,
Self::UnorderedSeries,
Self::DuplicateRecord,
Self::SequenceGap,
Self::OrphanPartial,
Self::IncompleteReassembly,
Self::JurisdictionConflict,
];
#[must_use]
pub const fn code(self) -> &'static str {
match self {
Self::UnassignedOffset => "V01",
Self::FutureTimestamp => "V02",
Self::ClosedBeforeOpened => "V03",
Self::DurationExceedsSpan => "V04",
Self::ImplausibleVolume => "V05",
Self::ZeroUsage => "V06",
Self::ContainerSumMismatch => "V07",
Self::UnattributableParty => "V08",
Self::NotKeyable => "V09",
Self::BeyondDeadline => "V10",
Self::LateArrival => "V11",
Self::ServingNetworkAbsent => "V12",
Self::QuantityDoesNotMatchService => "V13",
Self::CheckDigitFailure => "V14",
Self::VolumeOverflow => "V15",
Self::UnorderedSeries => "V16",
Self::DuplicateRecord => "V17",
Self::SequenceGap => "V18",
Self::OrphanPartial => "V19",
Self::IncompleteReassembly => "V20",
Self::JurisdictionConflict => "V21",
}
}
#[must_use]
pub const fn describe(self) -> &'static str {
match self {
Self::UnassignedOffset => "UTC offset outside the assigned range",
Self::FutureTimestamp => "record opens after the evaluation instant",
Self::ClosedBeforeOpened => "record closes before it opens",
Self::DurationExceedsSpan => "chargeable duration exceeds the wall-clock span",
Self::ImplausibleVolume => "volume exceeds what the elapsed time could carry",
Self::ZeroUsage => "record carries no quantity",
Self::ContainerSumMismatch => "container sum disagrees with the record total",
Self::UnattributableParty => "no charged party could be determined",
Self::NotKeyable => "no natural key, so the record cannot be deduplicated",
Self::BeyondDeadline => "past the inclusion deadline",
Self::LateArrival => "late, but still billable",
Self::ServingNetworkAbsent => "serving network absent",
Self::QuantityDoesNotMatchService => {
"quantity does not match what the service measures"
}
Self::CheckDigitFailure => "identifier check digit does not verify",
Self::VolumeOverflow => "volume overflows when summed",
Self::UnorderedSeries => "input is not in ascending instant order",
Self::DuplicateRecord => "retransmission of a record already seen",
Self::SequenceGap => "source sequence has an unfilled hole",
Self::OrphanPartial => "run of partials cannot be reassembled",
Self::IncompleteReassembly => "run of partials is missing members",
Self::JurisdictionConflict => {
"serving network and reported location disagree on the country"
}
}
}
#[must_use]
pub const fn default_severity(self) -> Severity {
match self {
Self::UnassignedOffset
| Self::FutureTimestamp
| Self::ClosedBeforeOpened
| Self::DurationExceedsSpan
| Self::ContainerSumMismatch
| Self::UnattributableParty
| Self::NotKeyable
| Self::BeyondDeadline
| Self::VolumeOverflow
| Self::SequenceGap
| Self::OrphanPartial
| Self::IncompleteReassembly
| Self::JurisdictionConflict => Severity::Blocking,
Self::ImplausibleVolume
| Self::ZeroUsage
| Self::LateArrival
| Self::ServingNetworkAbsent
| Self::QuantityDoesNotMatchService
| Self::CheckDigitFailure
| Self::UnorderedSeries
| Self::DuplicateRecord => Severity::Warning,
}
}
}
impl fmt::Display for Rule {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} {}", self.code(), self.describe())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Severity {
Warning,
Blocking,
}
impl Severity {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Warning => "WARNING",
Self::Blocking => "BLOCKING",
}
}
}
impl fmt::Display for Severity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Finding {
pub rule: Rule,
pub severity: Severity,
pub record_index: Option<usize>,
pub detail: String,
}
impl Finding {
#[must_use]
pub fn new(rule: Rule, record_index: usize, detail: impl Into<String>) -> Self {
Self {
rule,
severity: rule.default_severity(),
record_index: Some(record_index),
detail: detail.into(),
}
}
#[must_use]
pub fn batch(rule: Rule, detail: impl Into<String>) -> Self {
Self {
rule,
severity: rule.default_severity(),
record_index: None,
detail: detail.into(),
}
}
#[must_use]
pub fn duplicate(record_index: usize, key: &RecordKey) -> Self {
Self::new(Rule::DuplicateRecord, record_index, key.to_string())
}
#[must_use]
pub fn not_keyable(record_index: usize, reason: NotKeyable) -> Self {
Self::new(Rule::NotKeyable, record_index, reason.to_string())
}
#[must_use]
pub fn sequence_gap(source: &str, missing: &[u32]) -> Self {
Self::batch(Rule::SequenceGap, format!("{source} missing {missing:?}"))
}
#[must_use]
pub fn reassembly(record_index: usize, assessment: &Reassembly) -> Option<Self> {
match assessment {
Reassembly::Orphan { reason, have } => Some(Self::new(
Rule::OrphanPartial,
record_index,
match reason {
OrphanReason::FirstRecordMissing => {
format!("run begins at {:?}, not 1", have.first())
}
OrphanReason::FirstRecordNotFullyQualified => {
"first partial is reduced and has no basis to complete from".to_owned()
}
},
)),
Reassembly::Incomplete { missing, .. } if !missing.is_empty() => Some(Self::new(
Rule::IncompleteReassembly,
record_index,
format!("missing partials {missing:?}"),
)),
_ => None,
}
}
#[must_use]
pub fn escalated(mut self) -> Self {
self.severity = Severity::Blocking;
self
}
#[must_use]
pub const fn blocks_billing(&self) -> bool {
matches!(self.severity, Severity::Blocking)
}
}
impl fmt::Display for Finding {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "[{}] {}", self.severity, self.rule)?;
if let Some(index) = self.record_index {
write!(f, " at record {index}")?;
}
if !self.detail.is_empty() {
write!(f, ": {}", self.detail)?;
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ValidationConfig {
pub lateness: LatenessPolicy,
pub max_octets_per_second: u64,
pub escalate: Vec<Rule>,
}
impl Default for ValidationConfig {
fn default() -> Self {
Self {
lateness: LatenessPolicy::tap3(),
max_octets_per_second: 10_000_000_000,
escalate: Vec::new(),
}
}
}
impl ValidationConfig {
#[must_use]
pub fn severity_of(&self, rule: Rule) -> Severity {
if self.escalate.contains(&rule) {
Severity::Blocking
} else {
rule.default_severity()
}
}
#[must_use]
pub fn escalating(mut self, rule: Rule) -> Self {
if !self.escalate.contains(&rule) {
self.escalate.push(rule);
}
self
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ValidationReport {
findings: Vec<Finding>,
}
impl ValidationReport {
#[must_use]
pub const fn new() -> Self {
Self {
findings: Vec::new(),
}
}
pub fn push(&mut self, finding: Finding) {
self.findings.push(finding);
}
#[must_use]
pub fn findings(&self) -> &[Finding] {
&self.findings
}
#[must_use]
pub fn len(&self) -> usize {
self.findings.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.findings.is_empty()
}
#[must_use]
pub fn has(&self, rule: Rule) -> bool {
self.findings.iter().any(|f| f.rule == rule)
}
#[must_use]
pub fn severity_of(&self, rule: Rule) -> Option<Severity> {
self.findings
.iter()
.filter(|f| f.rule == rule)
.map(|f| f.severity)
.max()
}
#[must_use]
pub fn blocking_count(&self) -> usize {
self.findings.iter().filter(|f| f.blocks_billing()).count()
}
#[must_use]
pub fn blocks_billing(&self) -> bool {
self.blocking_count() > 0
}
#[must_use]
pub fn for_record(&self, index: usize) -> Vec<&Finding> {
self.findings
.iter()
.filter(|f| f.record_index == Some(index))
.collect()
}
#[must_use]
pub fn record_blocked(&self, index: usize) -> bool {
self.findings
.iter()
.any(|f| f.record_index == Some(index) && f.blocks_billing())
}
}
impl fmt::Display for ValidationReport {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{} finding(s), {} blocking",
self.findings.len(),
self.blocking_count()
)
}
}
impl FromIterator<Finding> for ValidationReport {
fn from_iter<I: IntoIterator<Item = Finding>>(iter: I) -> Self {
Self {
findings: iter.into_iter().collect(),
}
}
}
#[must_use]
pub fn validate_records(
records: &[UsageRecord],
config: &ValidationConfig,
as_of: OffsetDateTime,
) -> ValidationReport {
let mut report = ValidationReport::new();
for (index, record) in records.iter().enumerate() {
validate_one(record, index, config, as_of, &mut report);
}
check_ordering(records, &mut report);
for finding in &mut report.findings {
finding.severity = config.severity_of(finding.rule);
}
report
}
fn validate_one(
record: &UsageRecord,
index: usize,
config: &ValidationConfig,
as_of: OffsetDateTime,
report: &mut ValidationReport,
) {
for (label, timestamp) in [("opened", Some(record.opened)), ("closed", record.closed)] {
if let Some(timestamp) = timestamp
&& !timestamp.offset().is_assigned()
{
report.push(Finding::new(
Rule::UnassignedOffset,
index,
format!("{label} offset {}", timestamp.offset()),
));
}
}
match config.lateness.classify(record.opened.to_utc(), as_of) {
Lateness::Future(by) => report.push(Finding::new(
Rule::FutureTimestamp,
index,
format!("opens {by} ahead of the evaluation instant"),
)),
Lateness::BeyondDeadline(age) => report.push(Finding::new(
Rule::BeyondDeadline,
index,
format!("{age} old"),
)),
Lateness::Late(age) => {
report.push(Finding::new(Rule::LateArrival, index, format!("{age} old")))
}
Lateness::OnTime => {}
}
if let Some(closed) = record.closed {
if closed.to_utc() < record.opened.to_utc() {
report.push(Finding::new(
Rule::ClosedBeforeOpened,
index,
format!("{} before {}", closed, record.opened),
));
} else if let (Some(duration), Some(span)) = (record.duration, record.wall_clock_span())
&& duration > span
{
report.push(Finding::new(
Rule::DurationExceedsSpan,
index,
format!("{duration} s billed over a {span} s span"),
));
}
}
if let (Some(volume), Some(span)) = (record.volume, record.wall_clock_span())
&& !span.is_zero()
&& let Some(total) = volume.checked_total()
{
let ceiling = u128::from(span.get()) * u128::from(config.max_octets_per_second);
if u128::from(total.get()) > ceiling {
report.push(Finding::new(
Rule::ImplausibleVolume,
index,
format!("{total} octets in {span} s"),
));
}
}
if let Some(volume) = record.volume
&& volume.checked_total().is_none()
{
report.push(Finding::new(
Rule::VolumeOverflow,
index,
format!("{volume} overflows when summed"),
));
}
if record.is_zero_usage() {
report.push(Finding::new(Rule::ZeroUsage, index, "no quantity recorded"));
}
if let Some(false) = record.containers_agree() {
let detail = match record.containers.discrepancy(record.volume) {
Some((up, down)) => format!("record exceeds containers by {up}/{down} octets"),
None => "record total and container sum differ".to_owned(),
};
report.push(Finding::new(Rule::ContainerSumMismatch, index, detail));
}
if let Some(reason) = record.party.unattributable_reason() {
report.push(Finding::new(
Rule::UnattributableParty,
index,
reason.to_string(),
));
}
if let Err(reason) = RecordKey::of(record) {
report.push(Finding::not_keyable(index, reason));
}
if record.serving_plmn.is_none() && record.record_type.service_domain().is_subscriber_bound() {
report.push(Finding::new(
Rule::ServingNetworkAbsent,
index,
"no serving network on a subscriber-bound record",
));
}
if !record.is_zero_usage() {
let populated = match record.record_type.service_domain().primary_measure() {
PrimaryMeasure::Duration => record.duration.is_some(),
PrimaryMeasure::Volume => record.volume.is_some() || !record.containers.is_empty(),
PrimaryMeasure::Events => record.events.is_some(),
};
if !populated {
report.push(Finding::new(
Rule::QuantityDoesNotMatchService,
index,
format!(
"{} is measured by {:?}",
record.record_type.service_domain(),
record.record_type.service_domain().primary_measure()
),
));
}
}
if let Some(Ambiguity::Conflicting { serving, reported }) = usage_country(record).ambiguity() {
report.push(Finding::new(
Rule::JurisdictionConflict,
index,
format!("serving network in {serving}, reported location in {reported}"),
));
}
if let Some(iccid) = record.iccid
&& iccid.has_check_digit()
&& !iccid.luhn_valid()
{
report.push(Finding::new(
Rule::CheckDigitFailure,
index,
format!("ICCID {iccid}"),
));
}
}
fn check_ordering(records: &[UsageRecord], report: &mut ValidationReport) {
let out_of_order = records
.windows(2)
.filter(|pair| {
CdrTimestamp::cmp_instant(&pair[1].opened, &pair[0].opened) == std::cmp::Ordering::Less
})
.count();
if out_of_order > 0 {
report.push(Finding::batch(
Rule::UnorderedSeries,
format!(
"{out_of_order} descending step(s) in {} records",
records.len()
),
));
}
}
#[cfg(feature = "serde")]
mod serde_impl {
use super::{Finding, Rule, Severity, ValidationReport};
use serde::de::{self, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;
impl Serialize for Rule {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(self.code())
}
}
impl<'de> Deserialize<'de> for Rule {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct V;
impl Visitor<'_> for V {
type Value = Rule;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("a rule code such as \"V07\"")
}
fn visit_str<E: de::Error>(self, v: &str) -> Result<Rule, E> {
Rule::ALL
.iter()
.find(|r| r.code() == v)
.copied()
.ok_or_else(|| de::Error::custom(format!("unknown rule {v:?}")))
}
}
deserializer.deserialize_str(V)
}
}
impl Serialize for Severity {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(self.as_str())
}
}
impl<'de> Deserialize<'de> for Severity {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct V;
impl Visitor<'_> for V {
type Value = Severity;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("\"WARNING\" or \"BLOCKING\"")
}
fn visit_str<E: de::Error>(self, v: &str) -> Result<Severity, E> {
match v {
"WARNING" => Ok(Severity::Warning),
"BLOCKING" => Ok(Severity::Blocking),
other => Err(de::Error::custom(format!("unknown severity {other:?}"))),
}
}
}
deserializer.deserialize_str(V)
}
}
#[derive(Serialize, Deserialize)]
#[serde(rename = "Finding")]
struct FindingRepr {
rule: Rule,
severity: Severity,
#[serde(default, skip_serializing_if = "Option::is_none")]
record_index: Option<usize>,
detail: String,
}
impl Serialize for Finding {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
FindingRepr {
rule: self.rule,
severity: self.severity,
record_index: self.record_index,
detail: self.detail.clone(),
}
.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for Finding {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let r = FindingRepr::deserialize(deserializer)?;
Ok(Finding {
rule: r.rule,
severity: r.severity,
record_index: r.record_index,
detail: r.detail,
})
}
}
impl Serialize for ValidationReport {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
self.findings().serialize(serializer)
}
}
impl<'de> Deserialize<'de> for ValidationReport {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
Vec::<Finding>::deserialize(deserializer).map(ValidationReport::from_iter)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::cdrtime::Seconds;
use crate::container::{ChangeCondition, ContainerSet, RatingGroup, ServiceDataContainer};
use crate::correlation::{ChargingId, CorrelationKeys};
use crate::party::{ChargedParty, SubscriberRef, UnattributableReason};
use crate::record::{RecordType, SourceRef};
use crate::volume::{Octets, VolumePair};
use std::net::Ipv4Addr;
use time::macros::datetime;
const NOW: OffsetDateTime = datetime!(2026-07-28 12:00:00 UTC);
fn keys() -> CorrelationKeys {
CorrelationKeys::default()
.with_charging_id(ChargingId::new(1))
.with_gateway(Ipv4Addr::new(10, 0, 0, 1).into())
}
fn call() -> UsageRecord {
UsageRecord::new(
RecordType::MobileOriginatedCall,
ChargedParty::Subscriber(SubscriberRef::new("imsi-262021234567890".parse().unwrap())),
"2026-07-28T10:00:00+02:00".parse().unwrap(),
SourceRef::new("msc-01".parse().unwrap(), 0),
)
.with_networks("262-02".parse().unwrap(), "262-02".parse().unwrap())
.with_correlation(keys())
.with_closed("2026-07-28T10:01:00+02:00".parse().unwrap())
.with_duration(Seconds::new(55))
}
fn run(records: &[UsageRecord]) -> ValidationReport {
validate_records(records, &ValidationConfig::default(), NOW)
}
#[test]
fn a_rule_that_did_not_fire_has_no_severity() {
let report = run(&[call()]);
assert_eq!(report.severity_of(Rule::ZeroUsage), None);
assert_eq!(report.severity_of(Rule::BeyondDeadline), None);
}
#[test]
fn a_clean_record_produces_nothing() {
let report = run(&[call()]);
assert!(report.is_empty(), "{:?}", report.findings());
assert!(!report.blocks_billing());
}
#[test]
fn a_duration_longer_than_the_span_is_blocking() {
let record = call()
.with_closed("2026-07-28T10:00:10+02:00".parse().unwrap())
.with_duration(Seconds::new(55));
let report = run(&[record]);
assert!(report.has(Rule::DurationExceedsSpan));
assert_eq!(
report.severity_of(Rule::DurationExceedsSpan),
Some(Severity::Blocking)
);
assert!(report.record_blocked(0));
}
#[test]
fn a_record_closing_before_it_opens_fires_one_rule_not_two() {
let record = call().with_closed("2026-07-28T09:00:00+02:00".parse().unwrap());
let report = run(&[record]);
assert!(report.has(Rule::ClosedBeforeOpened));
assert!(!report.has(Rule::DurationExceedsSpan));
}
#[test]
fn the_lateness_policy_drives_three_rules() {
assert!(!run(&[call()]).has(Rule::BeyondDeadline));
let old = UsageRecord::new(
RecordType::MobileOriginatedCall,
ChargedParty::Subscriber(SubscriberRef::new("imsi-262021234567890".parse().unwrap())),
"2026-01-01T10:00:00+02:00".parse().unwrap(),
SourceRef::new("msc-01".parse().unwrap(), 0),
)
.with_networks("262-02".parse().unwrap(), "262-02".parse().unwrap())
.with_correlation(keys())
.with_duration(Seconds::new(10));
let report = run(&[old]);
assert!(report.has(Rule::BeyondDeadline));
assert_eq!(
report.severity_of(Rule::BeyondDeadline),
Some(Severity::Blocking)
);
let ahead = UsageRecord::new(
RecordType::MobileOriginatedCall,
ChargedParty::Subscriber(SubscriberRef::new("imsi-262021234567890".parse().unwrap())),
"2026-08-01T10:00:00+02:00".parse().unwrap(),
SourceRef::new("msc-01".parse().unwrap(), 0),
)
.with_networks("262-02".parse().unwrap(), "262-02".parse().unwrap())
.with_correlation(keys())
.with_duration(Seconds::new(10));
assert!(run(&[ahead]).has(Rule::FutureTimestamp));
}
#[test]
fn a_container_mismatch_reports_how_far_out_it_is() {
let record = 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_networks("262-02".parse().unwrap(), "262-02".parse().unwrap())
.with_correlation(keys())
.with_volume(VolumePair::new(Octets::new(150), Octets::new(900)))
.with_containers(ContainerSet::from(vec![
ServiceDataContainer::new(RatingGroup::new(10), ChangeCondition::RecordClosure)
.with_volume(VolumePair::new(Octets::new(100), Octets::new(900))),
]));
let report = run(&[record]);
assert!(report.has(Rule::ContainerSumMismatch));
let finding = report
.findings()
.iter()
.find(|f| f.rule == Rule::ContainerSumMismatch)
.unwrap();
assert!(finding.detail.contains("50/0"), "{}", finding.detail);
assert!(finding.blocks_billing());
}
#[test]
fn an_unattributable_record_and_an_unkeyable_one_both_block() {
let lost = UsageRecord::new(
RecordType::MobileOriginatedCall,
ChargedParty::Unattributable(UnattributableReason::IdentityAbsent),
"2026-07-28T10:00:00+02:00".parse().unwrap(),
SourceRef::new("msc-01".parse().unwrap(), 0),
)
.with_networks("262-02".parse().unwrap(), "262-02".parse().unwrap())
.with_duration(Seconds::new(10));
let report = run(&[lost]);
assert!(report.has(Rule::UnattributableParty));
assert!(report.has(Rule::NotKeyable));
assert!(report.record_blocked(0));
}
#[test]
fn an_implausible_volume_is_caught_but_does_not_block() {
let record = 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_networks("262-02".parse().unwrap(), "262-02".parse().unwrap())
.with_correlation(keys())
.with_closed("2026-07-28T10:00:01+02:00".parse().unwrap())
.with_volume(VolumePair::new(Octets::new(u64::MAX / 2), Octets::ZERO));
let report = run(&[record]);
assert!(report.has(Rule::ImplausibleVolume));
assert_eq!(
report.severity_of(Rule::ImplausibleVolume),
Some(Severity::Warning)
);
assert!(!report.record_blocked(0));
}
#[test]
fn disorder_is_reported_once_for_the_whole_slice() {
let mut early = call();
early.opened = "2026-07-28T09:00:00+02:00".parse().unwrap();
early.closed = Some("2026-07-28T09:01:00+02:00".parse().unwrap());
let report = run(&[call(), early.clone(), call(), early]);
let unordered: Vec<_> = report
.findings()
.iter()
.filter(|f| f.rule == Rule::UnorderedSeries)
.collect();
assert_eq!(unordered.len(), 1);
assert!(unordered[0].detail.contains('2'), "{}", unordered[0].detail);
assert_eq!(unordered[0].record_index, None, "disorder is batch-level");
}
#[test]
fn findings_point_into_the_callers_slice() {
let broken = call()
.with_closed("2026-07-28T10:00:01+02:00".parse().unwrap())
.with_duration(Seconds::new(999));
let report = run(&[call(), broken, call()]);
let finding = report
.findings()
.iter()
.find(|f| f.rule == Rule::DurationExceedsSpan)
.unwrap();
assert_eq!(finding.record_index, Some(1));
assert_eq!(report.for_record(1).len(), 1);
assert!(report.for_record(0).is_empty());
}
#[test]
fn escalation_raises_a_warning_to_blocking() {
let record = call().with_duration(Seconds::ZERO).with_events(0);
assert_eq!(
run(std::slice::from_ref(&record)).severity_of(Rule::ZeroUsage),
Some(Severity::Warning)
);
let strict = ValidationConfig::default().escalating(Rule::ZeroUsage);
let report = validate_records(&[record], &strict, NOW);
assert_eq!(
report.severity_of(Rule::ZeroUsage),
Some(Severity::Blocking)
);
assert!(report.blocks_billing());
}
#[test]
fn an_unassigned_offset_is_reported_for_either_timestamp() {
let odd = CdrTimestamp::new(
call().opened.local(),
crate::cdrtime::QuarterHourOffset::from_encoded(79).unwrap(),
);
let mut record = call();
record.opened = odd;
let report = run(&[record]);
assert!(report.has(Rule::UnassignedOffset));
assert_eq!(
report.severity_of(Rule::UnassignedOffset),
Some(Severity::Blocking)
);
}
#[test]
fn the_catalogue_is_complete_and_distinct() {
assert_eq!(Rule::ALL.len(), 21);
let mut codes: Vec<&str> = Rule::ALL.iter().map(|r| r.code()).collect();
codes.sort_unstable();
codes.dedup();
assert_eq!(codes.len(), Rule::ALL.len(), "codes must be distinct");
for (position, rule) in Rule::ALL.iter().enumerate() {
assert_eq!(rule.code(), format!("V{:02}", position + 1));
assert!(!rule.describe().is_empty());
assert!(rule.to_string().starts_with(rule.code()));
}
}
#[test]
fn a_country_disagreement_is_a_blocking_finding() {
use crate::location::{Ncgi, Nci, UserLocation};
use crate::session::SessionContext;
let confused = call()
.with_networks("214-07".parse().unwrap(), "262-02".parse().unwrap())
.with_session(
SessionContext::none().with_location(UserLocation::Ncgi(Ncgi::new(
"232-01".parse().unwrap(),
Nci::new(0x0_1234_5678).unwrap(),
))),
);
let report = validate_records(
std::slice::from_ref(&confused),
&ValidationConfig::default(),
datetime!(2026-07-28 12:00 UTC),
);
let finding = report
.findings()
.iter()
.find(|f| f.rule == Rule::JurisdictionConflict)
.expect("V21 fires");
assert_eq!(finding.severity, Severity::Blocking);
assert!(finding.detail.contains("214"), "{}", finding.detail);
assert!(finding.detail.contains("232"), "{}", finding.detail);
let agreeing = call()
.with_networks("214-07".parse().unwrap(), "262-02".parse().unwrap())
.with_session(
SessionContext::none().with_location(UserLocation::Ncgi(Ncgi::new(
"214-07".parse().unwrap(),
Nci::new(0x0_1234_5678).unwrap(),
))),
);
let clean = validate_records(
std::slice::from_ref(&agreeing),
&ValidationConfig::default(),
datetime!(2026-07-28 12:00 UTC),
);
assert_eq!(clean.severity_of(Rule::JurisdictionConflict), None);
}
#[test]
fn stateful_outcomes_join_the_same_catalogue() {
let key = RecordKey::of(&call()).unwrap();
let duplicate = Finding::duplicate(3, &key);
assert_eq!(duplicate.rule, Rule::DuplicateRecord);
assert_eq!(duplicate.record_index, Some(3));
let gap = Finding::sequence_gap("pgw-01", &[12, 13]);
assert_eq!(gap.rule, Rule::SequenceGap);
assert_eq!(gap.record_index, None);
assert!(gap.blocks_billing());
let complete = Reassembly::Complete { count: 3 };
assert_eq!(Finding::reassembly(0, &complete), None);
let orphan = Reassembly::Orphan {
reason: OrphanReason::FirstRecordNotFullyQualified,
have: vec![1],
};
let finding = Finding::reassembly(0, &orphan).unwrap();
assert_eq!(finding.rule, Rule::OrphanPartial);
assert!(finding.blocks_billing());
}
#[test]
fn an_open_partial_run_is_not_a_finding() {
let open = Reassembly::Incomplete {
have: vec![1, 2],
missing: vec![],
terminated: false,
};
assert_eq!(Finding::reassembly(0, &open), None);
let holed = Reassembly::Incomplete {
have: vec![1, 3],
missing: vec![2],
terminated: true,
};
assert!(Finding::reassembly(0, &holed).is_some());
}
}