mod common;
use common::{at, day, day_of, dso, fuse, win};
use flexibility::jiff::civil::date;
use flexibility::jiff::tz::TimeZone;
use flexibility::{
Bounds, Envelope, Error, Grid, IspDuration, Limit, MAX_ISPS, Power, Schedule, Series, Window,
};
fn w(watts: i64) -> Power {
Power::from_watts(watts)
}
#[test]
fn sr_001_combination_never_widens() {
let a = Envelope::unbounded(day())
.apply(&Limit::new(
win(16, 0, 20, 0),
Bounds::new(Some(w(-2_000)), Some(w(9_000))).unwrap(),
fuse(),
))
.unwrap();
let b = Envelope::unbounded(day())
.apply(&Limit::new(
win(17, 0, 19, 0),
Bounds::new(Some(w(-5_000)), Some(w(4_200))).unwrap(),
dso(),
))
.unwrap();
for c in [a.combine(&b).unwrap(), b.combine(&a).unwrap()] {
for isp in 1..=96 {
let (ab, bb, cb) = (
a.bounds(isp).unwrap(),
b.bounds(isp).unwrap(),
c.bounds(isp).unwrap(),
);
for side in [ab, bb] {
if let Some(max) = side.max() {
assert!(cb.max().is_some_and(|m| m <= max), "ISP {isp}: max widened");
}
if let Some(min) = side.min() {
assert!(cb.min().is_some_and(|m| m >= min), "ISP {isp}: min widened");
}
}
}
assert_eq!(
c.bounds(70).unwrap(),
Bounds::new(Some(w(-2_000)), Some(w(4_200))).unwrap()
);
}
}
#[test]
fn sr_001_partial_overlap_constrains() {
let cap = Limit::consumption_cap(win(17, 5, 17, 20), w(1_000), dso());
let env = Envelope::unbounded(day()).apply(&cap).unwrap();
assert_eq!(env.bounds(69).unwrap().max(), Some(w(1_000)), "17:00 ISP");
assert_eq!(env.bounds(70).unwrap().max(), Some(w(1_000)), "17:15 ISP");
}
#[test]
fn sr_002_empty_range_is_never_resolved() {
let max = Limit::consumption_cap(win(17, 15, 17, 30), w(1_000), dso());
let min = Limit::new(win(17, 15, 17, 30), Bounds::at_least(w(2_000)), fuse());
for (first, second) in [(&max, &min), (&min, &max)] {
let err = Envelope::unbounded(day())
.apply(first)
.unwrap()
.apply(second)
.unwrap_err();
let Error::EmptyRange { isp, min, max } = err else {
panic!("expected EmptyRange, got {err}")
};
assert_eq!((isp.isp(), min, max), (70, w(2_000), w(1_000)));
}
assert!(Bounds::new(Some(w(2_000)), Some(w(1_000))).is_err());
}
#[test]
fn sr_003_checked_power() {
assert!(matches!(
w(i64::MAX).checked_add(w(1)),
Err(Error::Overflow { .. })
));
assert!(matches!(
w(i64::MIN).checked_neg(),
Err(Error::Overflow { .. })
));
assert!(matches!(
w(i64::MIN).checked_sub(w(1)),
Err(Error::Overflow { .. })
));
let f = Power::feed_in(500).unwrap();
assert_eq!(f.watts(), -500);
assert_eq!(f.direction(), flexibility::Direction::FeedIn);
assert!(Power::consumption(u64::MAX).is_err());
}
#[test]
fn sr_004_grids_must_match() {
let today = Envelope::unbounded(day());
let tomorrow = day_of(date(2026, 12, 2));
let plan = Schedule::new(Series::filled(tomorrow.clone(), w(0)), dso());
assert!(matches!(
plan.check(&today),
Err(Error::GridMismatch { .. })
));
assert!(matches!(
today.combine(&Envelope::unbounded(tomorrow)),
Err(Error::GridMismatch { .. })
));
let hourly = Grid::day(
date(2026, 12, 1),
&common::berlin(),
IspDuration::from_minutes(60).unwrap(),
)
.unwrap();
assert!(today.combine(&Envelope::unbounded(hourly)).is_err());
assert_eq!(day_of(date(2026, 3, 29)).count(), 92);
assert_eq!(day_of(date(2026, 10, 25)).count(), 100);
}
#[test]
fn sr_005_grid_cap() {
let isp = IspDuration::from_minutes(1).unwrap();
assert_eq!(
Grid::new(at(0, 0), isp, MAX_ISPS + 1, TimeZone::UTC).unwrap_err(),
Error::GridSize {
count: u64::from(MAX_ISPS) + 1
}
);
assert!(Grid::new(at(0, 0), isp, u32::MAX, TimeZone::UTC).is_err());
let year = Grid::new(at(0, 0), isp, MAX_ISPS, TimeZone::UTC).unwrap();
assert_eq!(
Envelope::unbounded(year).bounds(MAX_ISPS),
Some(Bounds::UNBOUNDED)
);
}
#[test]
fn sr_006_edges_do_not_panic() {
let far = flexibility::jiff::Timestamp::MAX;
let near = flexibility::jiff::Timestamp::MIN;
assert!(Grid::new(far, IspDuration::FIFTEEN_MINUTES, 1, TimeZone::UTC).is_err());
assert!(Grid::new(near, IspDuration::FIFTEEN_MINUTES, 1, TimeZone::UTC).is_ok());
assert!(
Grid::day(
date(9999, 12, 31),
&common::berlin(),
IspDuration::FIFTEEN_MINUTES
)
.is_err()
);
let grid = day();
assert_eq!(grid.isps(Window::new(near, far).unwrap()), Some(1..=96));
assert_eq!(grid.isp_at(far), None);
assert_eq!(grid.isp_at(near), None);
assert_eq!(grid.interval(u32::MAX), None);
let env = Envelope::unbounded(grid);
assert_eq!(env.bounds(0), None);
assert_eq!(env.max_source(u32::MAX), None);
let lim = Limit::new(
Window::new(near, far).unwrap(),
Bounds::new(Some(w(i64::MIN)), Some(w(i64::MAX))).unwrap(),
dso(),
);
assert!(env.apply(&lim).is_ok());
}
#[test]
fn sr_007_provenance_per_isp() {
let fuse_cap = Limit::consumption_cap(win(0, 0, 23, 0), w(11_000), fuse());
let dso_cap = Limit::consumption_cap(win(17, 0, 19, 0), w(4_200), dso());
let a = Envelope::unbounded(day()).apply(&fuse_cap).unwrap();
let b = Envelope::unbounded(day()).apply(&dso_cap).unwrap();
let c = a.combine(&b).unwrap().combine(&b).unwrap();
assert_eq!(c.provenances(), &[fuse(), dso()], "each provenance once");
assert_eq!(
c.max_source(70),
Some(&dso()),
"the stricter limit names itself"
);
assert_eq!(c.max_source(10), Some(&fuse()));
}
use flexibility::jiff::civil::time;
use flexibility::{Deviation, Energy, Guarantee, Provenance, kw};
#[test]
fn sr_002_001_gaps_and_folds_are_refused() {
for (d, t, word) in [
(date(2026, 3, 29), time(2, 30, 0, 0), "skipped"),
(date(2026, 10, 25), time(2, 30, 0, 0), "ambiguous"),
] {
let grid = day_of(d);
for err in [
grid.local(t).unwrap_err(),
grid.window(t, time(5, 0, 0, 0)).unwrap_err(),
grid.window(time(0, 0, 0, 0), t).unwrap_err(),
] {
assert!(
matches!(&err, Error::LocalTime { time, reason, .. } if *time == t && reason.starts_with(word)),
"{err}"
);
}
}
}
#[test]
fn sr_002_002_power_text_is_exact_or_refused() {
for bad in ["4.0001 kW", "4 kWh", "4,2 kW", "1e3 W", "4.2 kw", ""] {
assert!(
matches!(bad.parse::<Power>(), Err(Error::ParsePower { .. })),
"{bad}"
);
}
for watts in [
0,
1,
-1,
999,
1_000,
4_200,
-3_300,
1_500_000,
i64::MAX,
i64::MIN,
] {
let p = Power::from_watts(watts);
assert_eq!(p.to_string().parse::<Power>().unwrap(), p, "{p}");
let d = Deviation::from_watts(watts);
assert_eq!(d.to_string().parse::<Deviation>().unwrap(), d, "{d}");
}
}
#[test]
fn sr_002_003_guarantees_hold_on_every_path() {
let rule = Provenance::new("bnetza", "ยง 14a minimum", at(0, 0));
let g = Guarantee::consumption(win(0, 0, 23, 45), kw!(4.2), rule.clone()).unwrap();
let guaranteed = Envelope::unbounded(day()).guarantee(&g).unwrap();
let cap = Limit::consumption_cap(win(17, 0, 19, 0), kw!(3), dso());
let capped = Envelope::unbounded(day()).apply(&cap).unwrap();
for err in [
guaranteed.apply(&cap).unwrap_err(),
guaranteed.combine(&capped).unwrap_err(),
capped.combine(&guaranteed).unwrap_err(),
capped.guarantee(&g).unwrap_err(),
] {
let Error::GuaranteeBreached(b) = &err else {
panic!("{err}")
};
assert_eq!(b.isp.isp(), 69);
assert_eq!((&b.limit, &b.guarantee), (&dso(), &rule));
}
}
#[test]
fn sr_002_004_absolute_and_relative_do_not_mix() {
let d = kw!(4.1).deviation_from(kw!(7.4)).unwrap();
assert_eq!(d.to_string(), "-3.3 kW");
assert_eq!(kw!(7.4).checked_add_deviation(d).unwrap(), kw!(4.1));
let env = Envelope::unbounded(day())
.apply(&Limit::consumption_cap(win(17, 0, 19, 0), kw!(4.2), dso()))
.unwrap();
let room = env
.headroom(&Schedule::new(Series::filled(day(), kw!(2)), dso()))
.unwrap();
assert_eq!(room.get(69).unwrap().up, Some(Deviation::from_watts(2_200)));
}
#[test]
fn sr_002_005_explanations_attribute_correctly() {
let agr = Provenance::new("agr.example", "plan-7", at(12, 0));
let env = Envelope::unbounded(day())
.apply(&Limit::consumption_cap(win(0, 0, 23, 0), kw!(11), fuse()))
.unwrap()
.apply(&Limit::consumption_cap(win(17, 0, 19, 0), kw!(4.2), dso()))
.unwrap()
.apply(&Limit::consumption_cap(
win(16, 0, 20, 0),
kw!(7.4),
agr.clone(),
))
.unwrap();
let why = env.explain(69).unwrap();
assert_eq!(why.max_source, Some(dso()));
let shadowed: Vec<_> = why.shadowed.iter().map(|(_, p)| p.clone()).collect();
assert_eq!(shadowed, vec![fuse(), agr]);
}
#[test]
fn sr_002_006_long_text_is_refused_first() {
let long = "9".repeat(1_000_000) + " W";
let err = long.parse::<Power>().unwrap_err();
assert_eq!(
err,
Error::ParsePower {
text: format!("{} bytes", long.len()),
reason: "longer than 64 bytes"
}
);
}
#[test]
fn sr_002_007_energy_and_deviation_are_checked() {
let max = Power::from_watts(i64::MAX);
assert!(
max.energy(IspDuration::from_minutes(1440).unwrap())
.is_err()
);
assert!(Energy::from_wh(i64::MAX).is_err());
assert!(
Energy::from_watt_seconds(i64::MAX)
.checked_add(Energy::from_watt_seconds(1))
.is_err()
);
assert!(
Power::from_watts(i64::MIN)
.deviation_from(Power::from_watts(1))
.is_err()
);
assert!(Deviation::from_watts(i64::MIN).checked_neg().is_err());
let full = Series::filled(day(), max);
assert!(full.energy().is_err());
assert_eq!(day().label(u32::MAX), None);
}
#[test]
fn sr_002_008_no_new_runtime_dependency() {
let manifest = include_str!("../Cargo.toml");
let deps = manifest
.split("[dependencies]")
.nth(1)
.and_then(|rest| rest.split("\n[").next())
.unwrap_or_default();
let names: Vec<&str> = deps
.lines()
.filter(|l| {
!l.trim_start().starts_with('#') && l.contains('=') && !l.contains("optional = true")
})
.filter_map(|l| l.split('=').next().map(str::trim))
.filter(|n| *n != "sha2")
.collect();
assert_eq!(names, vec!["jiff"], "runtime dependencies: {names:?}");
}
use flexibility::baseline::{self, Adjustment, Mbma, XofY};
use flexibility::{Digest, settle};
fn uftp_rows(actuals: &[i64], base: i64, order: i64) -> Vec<(i64, i64)> {
let g = Grid::new(
flexibility::jiff::Timestamp::UNIX_EPOCH,
IspDuration::FIFTEEN_MINUTES,
u32::try_from(actuals.len()).unwrap(),
TimeZone::UTC,
)
.unwrap();
let all = Window::new(g.start(), g.end()).unwrap();
let declared = Schedule::new(Series::filled(g.clone(), w(base)), dso());
let b = baseline::dprognosis(&declared, all).unwrap();
let actual = Series::new(g.clone(), actuals.iter().map(|&a| w(a)).collect()).unwrap();
let ordered = Series::filled(g, Deviation::from_watts(order));
settle(
&b,
&actual,
&ordered,
flexibility::MeasurementPoint::ConnectionPoint,
)
.unwrap()
.lines()
.iter()
.map(|l| (l.delivered.watts(), l.deficiency.watts()))
.collect()
}
#[test]
fn sr_003_001_settlement_follows_uftp() {
let m = 1_000_000;
let rows = uftp_rows(&[7 * m, 8 * m, 9 * m, 10 * m, 11 * m], 10 * m, -2 * m);
assert_eq!(
rows,
[(-2 * m, 0), (-2 * m, 0), (-m, m), (0, 2 * m), (0, 3 * m)]
);
let mirrored = uftp_rows(&[-7 * m, -8 * m, -9 * m, -10 * m, -11 * m], -10 * m, 2 * m);
let flipped: Vec<_> = rows.iter().map(|&(d, f)| (-d, f)).collect();
assert_eq!(mirrored, flipped);
}
#[test]
fn sr_003_002_every_method_has_a_snapshot() {
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/snapshots");
for method in flexibility::MethodId::ALL {
assert!(dir.join(format!("{method}.json")).is_file(), "{method}");
}
}
#[test]
fn sr_003_003_canonical_text_is_injective_and_reproducible() {
let tricky = Provenance::new("a\"b\\c\nd\u{1}รฉ", "r\te", at(0, 0));
let plan = Schedule::new(Series::filled(day(), w(1)), tricky);
let b = baseline::schedule(&plan, win(17, 0, 19, 0)).unwrap();
let text = b.canonical();
assert!(text.contains(r#""issuer":"a\"b\\c\nd\u0001รฉ""#), "{text}");
assert!(text.contains(r#""reference":"r\te""#), "{text}");
let other = Schedule::new(Series::filled(day(), w(2)), dso());
assert_ne!(
baseline::schedule(&other, win(17, 0, 19, 0))
.unwrap()
.digest(),
b.digest()
);
assert_eq!(
Digest::of(b"abc").to_string(),
"sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
);
let file = std::path::Path::new(env!("CARGO_TARGET_TMPDIR")).join("baseline.json");
std::fs::write(&file, &text).unwrap();
let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("scripts/digest.sh");
let out = std::process::Command::new("bash")
.arg(script)
.arg(&file)
.output()
.unwrap();
assert!(
out.status.success(),
"{}",
String::from_utf8_lossy(&out.stderr)
);
assert_eq!(
String::from_utf8(out.stdout).unwrap().trim(),
b.digest().to_string()
);
}
#[test]
fn sr_003_004_methods_resist_gaming() {
let mut values = vec![w(5_000); 96];
values[67] = w(50_000); let measured = Series::new(day(), values).unwrap();
let b = baseline::mbma(&measured, win(17, 0, 19, 0), Mbma { n: 4, gap: 1 }).unwrap();
assert_eq!(b.series().values()[0], w(5_000));
let same = |d| Series::filled(day_of(date(2026, 11, d)), w(5_000));
let p = XofY {
x: 1,
y: 2,
adjustment: Adjustment::None,
};
for order in [[same(20), same(21)], [same(21), same(20)]] {
let b = baseline::xofy(&day(), win(17, 0, 19, 0), &order, None, p).unwrap();
let baseline::Derivation::XofY { days, .. } = b.derivation() else {
panic!()
};
assert_eq!(days, &[date(2026, 11, 21)]);
}
let today = Series::filled(day(), w(6_000));
let capped = XofY {
x: 2,
y: 2,
adjustment: Adjustment::Additive {
window: 2,
gap: 1,
cap: Some(w(500)),
},
};
let b = baseline::xofy(
&day(),
win(17, 0, 19, 0),
&[same(20), same(21)],
Some(&today),
capped,
)
.unwrap();
assert_eq!(b.series().values()[0], w(5_500));
}
#[test]
fn sr_003_005_insufficient_history_is_refused() {
let days: Vec<_> = (21..=29)
.map(|d| Series::filled(day_of(date(2026, 11, d)), w(1)))
.collect();
let err = baseline::xofy(
&day(),
win(17, 0, 19, 0),
&days,
None,
XofY {
x: 5,
y: 10,
adjustment: Adjustment::None,
},
)
.unwrap_err();
assert!(
err.to_string()
.contains("needs y = 10 comparable days, got 9"),
"{err}"
);
let measured = Series::filled(day(), w(1));
let err = baseline::mbma(&measured, win(0, 15, 1, 0), Mbma { n: 4, gap: 1 }).unwrap_err();
assert!(matches!(err, Error::Method { .. }), "{err}");
let zero: Vec<_> = (20..=21)
.map(|d| Series::filled(day_of(date(2026, 11, d)), w(0)))
.collect();
let ratio = XofY {
x: 2,
y: 2,
adjustment: Adjustment::Ratio {
window: 2,
gap: 1,
cap_percent: 20,
},
};
let err = baseline::xofy(&day(), win(17, 0, 19, 0), &zero, Some(&measured), ratio).unwrap_err();
assert!(err.to_string().contains("no positive baseline"), "{err}");
}
#[test]
fn sr_003_006_y_is_bounded() {
let err = baseline::xofy(
&day(),
win(17, 0, 19, 0),
&[],
None,
XofY {
x: 1,
y: 367,
adjustment: Adjustment::None,
},
)
.unwrap_err();
assert!(err.to_string().contains("y = 367 is above 366"), "{err}");
}
#[test]
fn sr_003_007_edges_are_errors() {
let g = Grid::new(
flexibility::jiff::Timestamp::UNIX_EPOCH,
IspDuration::FIFTEEN_MINUTES,
2,
TimeZone::UTC,
)
.unwrap();
let all = Window::new(g.start(), g.end()).unwrap();
assert!(matches!(
baseline::dprognosis(
&Schedule::new(Series::filled(g.clone(), w(i64::MAX)), dso()),
all,
),
Err(Error::Unrepresentable { .. })
));
let edge = i64::try_from(flexibility::MAX_EXACT).unwrap();
let b = baseline::dprognosis(
&Schedule::new(Series::filled(g.clone(), w(edge)), dso()),
all,
)
.unwrap();
let actual = Series::filled(g.clone(), w(-edge));
let ordered = Series::filled(g.clone(), Deviation::from_watts(-edge));
assert!(
settle(
&b,
&actual,
&ordered,
flexibility::MeasurementPoint::ConnectionPoint
)
.is_err()
);
let huge = Series::filled(g, w(i64::MAX));
let tiny = Series::new(huge.grid().clone(), vec![w(i64::MIN), w(i64::MIN)]).unwrap();
let _ = flexibility::accuracy::score([(&huge, &tiny)]);
}
#[test]
fn sr_003_008_only_sha2_is_new() {
let manifest = include_str!("../Cargo.toml");
let deps = manifest
.split("[dependencies]")
.nth(1)
.and_then(|r| r.split("\n[").next())
.unwrap_or_default();
let names: Vec<&str> = deps
.lines()
.filter(|l| {
!l.trim_start().starts_with('#') && l.contains('=') && !l.contains("optional = true")
})
.filter_map(|l| l.split('=').next().map(str::trim))
.collect();
assert_eq!(names, vec!["jiff", "sha2"]);
}
#[cfg(feature = "uftp")]
mod uftp_settlement {
use flexibility::uftp::{self, FlexSign, Kind, wire};
const MW: i64 = 1_000_000;
fn element(
start: u32,
duration: u32,
base: i64,
ordered: i64,
actual: i64,
delivered: i64,
deficiency: i64,
) -> wire::SettlementIsp {
wire::SettlementIsp {
span: wire::IspSpan::new(start, duration).unwrap(),
baseline_power: base,
ordered_flex_power: ordered,
actual_power: actual,
delivered_flex_power: delivered,
power_deficiency: deficiency,
}
}
fn message(isps: Vec<wire::SettlementIsp>) -> wire::FlexOrderSettlement {
wire::FlexOrderSettlement {
order_reference: None,
period: flexibility::jiff::civil::date(2026, 12, 1),
contract_id: None,
d_prognosis_message_id: None,
baseline_reference: None,
congestion_point: "ean.871685900012345678".parse().unwrap(),
price: wire::Amount::ZERO,
penalty: wire::Amount::ZERO,
net_settlement: wire::Amount::ZERO,
isps,
}
}
#[test]
fn sr_004_001_signs_are_explicit() {
let down = message(vec![element(1, 1, 10 * MW, -2 * MW, 8 * MW, 2 * MW, 0)]);
assert_eq!(uftp::check(&down, FlexSign::Magnitude).unwrap(), []);
let as_signed = uftp::check(&down, FlexSign::AsOrdered).unwrap();
assert!(
matches!(as_signed[0].kind, Kind::Field { field: "DeliveredFlexPower", sent, expected } if sent == 2 * MW && expected == -2 * MW)
);
let up = message(vec![element(1, 1, 10 * MW, 2 * MW, 12 * MW, 2 * MW, 0)]);
assert_eq!(uftp::check(&up, FlexSign::Magnitude).unwrap(), []);
assert_eq!(uftp::check(&up, FlexSign::AsOrdered).unwrap(), []);
}
#[test]
fn sr_004_002_nothing_passes_silently() {
let wrong = message(vec![element(10, 3, 10 * MW, -2 * MW, 9 * MW, MW, 0)]);
assert_eq!(uftp::check(&wrong, FlexSign::Magnitude).unwrap().len(), 3);
let twice = message(vec![
element(70, 1, 0, 0, 0, 0, 0),
element(70, 1, 0, 0, 0, 0, 0),
]);
let found = uftp::check(&twice, FlexSign::Magnitude).unwrap();
assert_eq!(found.len(), 1);
assert_eq!((found[0].isp, found[0].kind), (70, Kind::Duplicate));
}
#[test]
fn sr_004_003_expansion_is_bounded() {
let huge = message(vec![element(1, u32::MAX, 0, 0, 0, 0, 0)]);
assert!(matches!(
uftp::check(&huge, FlexSign::Magnitude),
Err(flexibility::Error::GridSize { .. })
));
assert!(
uftp::check(
&message(vec![element(1, flexibility::MAX_ISPS, 0, 0, 0, 0, 0)]),
FlexSign::AsOrdered
)
.is_ok()
);
}
}
#[test]
fn sr_004_004_uftp_is_optional() {
let manifest = include_str!("../Cargo.toml");
let line = manifest
.lines()
.find(|l| l.starts_with("uftp = {"))
.unwrap();
assert!(line.contains("optional = true"), "{line}");
assert!(manifest.contains("uftp = [\"dep:uftp\"]"));
let features = manifest
.split("[features]")
.nth(1)
.and_then(|r| r.split("\n[").next())
.unwrap();
assert!(
!features.contains("default"),
"no default features: {features}"
);
}
#[test]
fn sr_005_002_every_misfit_is_reported() {
use flexibility::{Band, Deviation, DeviationEnvelope, Disposition};
let d = Deviation::from_watts;
let g = day().slice(69..=70).unwrap();
let need = Band::new(d(-30_000), d(-10_000), Disposition::Requested).unwrap();
let env = DeviationEnvelope::new(
Series::new(g.clone(), vec![Some(need), None]).unwrap(),
dso(),
);
let found = env
.check(&Series::new(g, vec![d(-5_000), d(1_000)]).unwrap())
.unwrap();
assert_eq!(found.len(), 2);
assert_eq!(found[0].band, Some(need));
assert_eq!(found[1].band, None, "not requested");
assert!(matches!(
Band::new(d(1_000), d(-1_000), Disposition::Requested),
Err(Error::InvertedBand { .. })
));
}
#[cfg(feature = "uftp")]
mod relative_shapes {
use flexibility::baseline;
use flexibility::jiff::Timestamp;
use flexibility::uftp::{self, FlexSign, wire};
use flexibility::{Error, Power, Provenance, Rounding, Schedule, Series, Window};
use wire::rust_decimal::Decimal;
fn header() -> wire::FlexHeader {
let now: Timestamp = "2026-11-30T12:00:00Z".parse().unwrap();
let id = wire::MessageUuid::from_bytes([5; 16]);
wire::FlexHeader::new(
wire::Metadata::new(
"dso.example".parse().unwrap(),
"agr.example".parse().unwrap(),
now,
id,
),
"Europe/Amsterdam".parse().unwrap(),
"2026-12-01".parse().unwrap(),
"ean.871685900012636543".parse().unwrap(),
)
}
fn order(power: i64, hundredths: i64) -> wire::FlexOrder {
wire::FlexOrder {
header: header(),
isps: vec![wire::PowerIsp {
span: wire::IspSpan::single(69).unwrap(),
power,
}],
unsolicited: Some(true),
flex_offer_message_id: None,
service_type: None,
contract_id: None,
d_prognosis_message_id: None,
baseline_reference: None,
price: "1.00".parse().unwrap(),
currency: wire::Currency::EUR,
order_reference: "ORD-1".into(),
option_reference: None,
activation_factor: wire::ActivationFactor::new(Decimal::new(hundredths, 2)).unwrap(),
}
}
fn settled(o: &wire::FlexOrder, base: i64, actual: i64) -> flexibility::Settlement {
let ordered = uftp::ordered(o, Rounding::HalfAwayFromZero).unwrap();
let g = ordered.grid().clone();
let who = Provenance::new("agr.example", "d-prognosis", Timestamp::UNIX_EPOCH);
let b = baseline::dprognosis(
&Schedule::new(Series::filled(g.clone(), Power::from_watts(base)), who),
Window::new(g.start(), g.end()).unwrap(),
)
.unwrap();
flexibility::settle(
&b,
&Series::filled(g, Power::from_watts(actual)),
&ordered,
flexibility::MeasurementPoint::ConnectionPoint,
)
.unwrap()
}
#[test]
fn sr_005_001_delivered_and_deficiency_share_the_reading() {
let ours = settled(&order(-300_000, 100), 400_000, 120_000);
let e = uftp::isps(&ours, FlexSign::AsOrdered).unwrap()[0];
assert_eq!(
(e.delivered_flex_power, e.power_deficiency),
(-280_000, -20_000)
);
let e = uftp::isps(&ours, FlexSign::Magnitude).unwrap()[0];
assert_eq!(
(e.delivered_flex_power, e.power_deficiency),
(280_000, 20_000)
);
let up = settled(&order(2_000_000, 100), 0, 2_000_000);
for sign in [FlexSign::AsOrdered, FlexSign::Magnitude] {
let e = uftp::isps(&up, sign).unwrap()[0];
assert_eq!((e.delivered_flex_power, e.power_deficiency), (2_000_000, 0));
}
}
#[test]
fn sr_005_003_the_factor_is_applied_once_exactly() {
assert!(matches!(
uftp::ordered(&order(-333, 50), Rounding::Exact),
Err(Error::Inexact { .. })
));
let o = uftp::ordered(&order(-333, 50), Rounding::HalfAwayFromZero).unwrap();
assert_eq!(o.values()[0].watts(), -167);
let ord = order(-300_000, 37);
let item =
uftp::settlement(&ord, &settled(&ord, 400_000, 300_000), FlexSign::AsOrdered).unwrap();
assert_eq!(item.isps[0].ordered_flex_power, -111_000);
let s = wire::FlexSettlement::new(
ord.header.meta.clone(),
ord.header.period,
ord.header.period,
wire::Currency::EUR,
vec![item],
);
assert_eq!(
s.check_against([&ord]).unwrap()[0].disposition,
wire::AcceptedDisputed::Accepted
);
}
#[test]
fn sr_005_004_the_item_settles_the_order_it_names() {
let mut o = order(-300_000, 100);
let ours = settled(&o, 400_000, 120_000);
o.baseline_reference = Some("xofy@1".into());
assert!(matches!(
uftp::settlement(&o, &ours, FlexSign::AsOrdered),
Err(Error::Mismatch {
field: "BaselineReference",
..
})
));
o.baseline_reference = None;
o.header.period = "2026-12-02".parse().unwrap();
assert!(matches!(
uftp::settlement(&o, &ours, FlexSign::AsOrdered),
Err(Error::Mismatch {
field: "Period",
..
})
));
}
#[test]
fn sr_005_005_conversion_is_bounded() {
let huge = [wire::PowerIsp {
span: wire::IspSpan::new(1, u32::MAX).unwrap(),
power: 1,
}];
assert!(matches!(
uftp::profile(&header(), &huge),
Err(Error::GridSize { .. })
));
let mut req =
wire::FlexRequest::new(header(), "2026-11-30T18:00:00Z".parse().unwrap(), vec![]);
req.isps = vec![
wire::FlexRequestIsp::requested(wire::IspSpan::single(70).unwrap(), -1, 0),
wire::FlexRequestIsp::available(wire::IspSpan::new(69, 2).unwrap(), -1, 1),
];
assert!(matches!(
uftp::request(&req),
Err(Error::Unrepresentable { .. })
));
}
}
#[test]
fn sr_005_006_uftp_is_pinned_and_tested_on_the_msrv() {
let manifest = include_str!("../Cargo.toml");
let line = manifest
.lines()
.find(|l| l.starts_with("uftp = {"))
.unwrap();
assert!(
line.contains("version = \"0.3\"") && line.contains("optional = true"),
"{line}"
);
let ci = include_str!("../.github/workflows/ci.yml");
let rest = ci.split("\n msrv:").nth(1).unwrap();
let end = rest
.match_indices("\n ")
.find(|(i, _)| rest[i + 3..].starts_with(|c: char| c.is_ascii_alphabetic()))
.map_or(rest.len(), |(i, _)| i);
let job = &rest[..end];
assert!(job.contains("cargo test --locked --all-features"), "{job}");
let just = include_str!("../justfile");
assert!(just.contains("RUSTUP_TOOLCHAIN={{ msrv }} cargo test --all-features"));
}
#[cfg(feature = "eebus")]
mod eebus_limits {
use super::*;
use flexibility::eebus::wire::model::ScaledNumber;
use flexibility::eebus::{self, Direction, LimitWrite};
use std::time::Duration;
#[test]
fn sr_006_001_lpc_and_lpp_keep_their_sign() {
let lpp = LimitWrite::active(3_000);
let cap = eebus::limit(Direction::Production, &lpp, at(12, 0), at(13, 0), dso())
.unwrap()
.unwrap();
assert_eq!(
(cap.bounds().min(), cap.bounds().max()),
(Some(w(-3_000)), None)
);
let (direction, write) = eebus::write(&cap, at(12, 0)).unwrap();
assert_eq!(
(direction, write.value.to_i64()),
(Direction::Production, Some(3_000))
);
let lpc = LimitWrite::active(3_000);
let cap = eebus::limit(Direction::Consumption, &lpc, at(12, 0), at(13, 0), dso())
.unwrap()
.unwrap();
assert_eq!(
(cap.bounds().min(), cap.bounds().max()),
(None, Some(w(3_000)))
);
}
#[test]
fn sr_006_002_nothing_is_rounded_or_stretched() {
let read = |write: LimitWrite| {
eebus::limit(Direction::Consumption, &write, at(17, 0), at(23, 0), dso())
};
let half = read(LimitWrite::active(ScaledNumber::new(42_005, -1))).unwrap_err();
assert!(half.to_string().contains("4200.5"), "{half}");
assert!(read(LimitWrite::active(-1)).is_err());
assert!(matches!(
read(LimitWrite::active_for(1, Duration::MAX)),
Err(Error::Unrepresentable {
field: "duration",
..
})
));
let band = Limit::new(
Window::new(at(17, 0), at(19, 0)).unwrap(),
Bounds::new(Some(w(-1)), Some(w(1))).unwrap(),
dso(),
);
assert!(matches!(
eebus::write(&band, at(17, 0)),
Err(Error::Unrepresentable {
protocol: "EEBUS",
..
})
));
}
}
#[cfg(feature = "metering")]
mod metering_data {
use super::*;
use flexibility::Rounding;
use flexibility::metering::{self, wire};
use wire::grid::para14a::{
Anlage, Para14aConfig, SteuVeFallgruppe, mindestleistung_direktansteuerung,
steuerbare_verbrauchseinrichtungen,
};
use wire::prelude::Decimal;
use wire::{DayBoundary, MeterInterval, ObisCode, QualityFlag, Resolution};
fn kwh(text: &str) -> Decimal {
text.parse().unwrap()
}
fn lastgang(grid: &Grid, channel: ObisCode, values: &[&str], q: QualityFlag) -> wire::Series {
let intervals = grid
.numbers()
.zip(values)
.map(|(isp, v)| {
let iv = grid.interval(isp).unwrap();
MeterInterval::new(iv.from(), iv.until(), kwh(v), q)
.unwrap()
.with_obis(channel)
})
.collect();
wire::Series::new(Resolution::QUARTER_HOUR, DayBoundary::Strom, intervals).unwrap()
}
#[test]
fn sr_006_001_export_is_negative() {
let g = day().slice(69..=69).unwrap();
let out = lastgang(
&g,
ObisCode::STROM_EINSPEISUNG_LASTGANG,
&["0.25"],
QualityFlag::Measured,
);
let p = metering::power(&[&out], &g, Rounding::Exact).unwrap();
assert_eq!(p.values(), [w(-1_000)]);
}
#[test]
fn sr_006_003_the_minimum_is_never_understated() {
let steuve = steuerbare_verbrauchseinrichtungen(&[Anlage::new(
SteuVeFallgruppe::Waermepumpe,
kwh("20.001"),
)])
.unwrap();
let m = mindestleistung_direktansteuerung(&steuve[0], &Para14aConfig::VERMUTUNG);
let g = day();
let all = Window::new(g.start(), g.end()).unwrap();
assert_eq!(
metering::guarantee(m, all, dso()).unwrap().power(),
w(8_001)
);
}
#[test]
fn sr_006_004_no_quarter_is_invented() {
let g = day().slice(69..=70).unwrap();
let one = lastgang(
&g.slice(69..=69).unwrap(),
ObisCode::STROM_BEZUG_LASTGANG,
&["1"],
QualityFlag::Measured,
);
let err = metering::power(&[&one], &g, Rounding::Exact).unwrap_err();
assert!(
err.to_string().contains("missing electricity quarter"),
"{err}"
);
let faulty = lastgang(
&g,
ObisCode::STROM_BEZUG_LASTGANG,
&["1", "1"],
QualityFlag::Faulty,
);
assert!(metering::power(&[&faulty], &g, Rounding::Exact).is_err());
let register = lastgang(
&g,
ObisCode::STROM_BEZUG_TOTAL,
&["1", "1"],
QualityFlag::Measured,
);
assert!(matches!(
metering::power(&[®ister], &g, Rounding::Exact),
Err(Error::Unrepresentable {
field: "channel",
..
})
));
}
#[test]
fn sr_006_005_net_then_round() {
let g = day().slice(69..=69).unwrap();
let import = lastgang(
&g,
ObisCode::STROM_BEZUG_LASTGANG,
&["0.00035"],
QualityFlag::Measured,
);
let export = lastgang(
&g,
ObisCode::STROM_EINSPEISUNG_LASTGANG,
&["0.00015"],
QualityFlag::Measured,
);
let p = metering::power(&[&import, &export], &g, Rounding::HalfAwayFromZero).unwrap();
assert_eq!(p.values(), [w(1)], "0.8 W net, not 1 W - 1 W");
}
}
#[test]
fn sr_006_006_eebus_and_metering_are_optional() {
let manifest = include_str!("../Cargo.toml");
for name in ["eebus", "metering"] {
let line = manifest
.lines()
.find(|l| l.starts_with(&format!("{name} = {{")))
.unwrap();
assert!(
line.contains("optional = true") && line.contains("default-features = false"),
"{line}"
);
assert!(manifest.contains(&format!("{name} = [\"dep:{name}\"]")));
}
}
mod storage_and_pools {
use super::*;
use flexibility::pool::{self, Aggregate};
use flexibility::{Energy, EnergyEnvelope, Level, LevelBroken, Provenance, kw, kwh};
fn who(r: &str) -> Provenance {
Provenance::new("emob.example", r, at(0, 0))
}
fn boxed(grid: &Grid, min: Power, max: Power) -> EnergyEnvelope {
let all = Window::new(grid.start(), grid.end()).unwrap();
EnergyEnvelope::new(
Envelope::unbounded(grid.clone())
.apply(&Limit::new(
all,
Bounds::new(Some(min), Some(max)).unwrap(),
who("box"),
))
.unwrap(),
kwh!(0),
)
}
fn plan(grid: &Grid, p: &[Power]) -> Schedule {
Schedule::new(Series::new(grid.clone(), p.to_vec()).unwrap(), who("plan"))
}
#[test]
fn sr_007_001_every_boundary_is_checked() {
let night = day().slice(1..=28).unwrap();
let ev = boxed(&night, kw!(0), kw!(11))
.level_at(night.end(), Level::at_least(kwh!(30)), who("departure"))
.unwrap();
let r = ev.check(&plan(&night, &[kw!(4); 28])).unwrap();
assert_eq!((r.level.len(), r.level[0].level), (1, kwh!(28)));
let g = day().slice(69..=76).unwrap();
let battery = EnergyEnvelope::new(boxed(&g, kw!(-5), kw!(5)).power().clone(), kwh!(5))
.level_always(Level::between(kwh!(1), kwh!(9)).unwrap(), who("soc"))
.unwrap();
let r = battery.check(&plan(&g, &[kw!(-4); 8])).unwrap();
assert_eq!(r.level.len(), 4);
assert!(
r.level
.iter()
.all(|v| matches!(v.broken, LevelBroken::Below(_)))
);
}
#[test]
fn sr_007_002_boundaries_are_not_snapped() {
let g = day().slice(1..=28).unwrap();
assert!(matches!(
boxed(&g, kw!(0), kw!(11)).level_at(at(7, 5), Level::at_least(kwh!(1)), who("x")),
Err(Error::NotABoundary { .. })
));
assert!(matches!(
Level::between(kwh!(2), kwh!(1)),
Err(Error::InvertedLevel { .. })
));
}
#[test]
fn sr_007_003_levels_do_not_wrap() {
let g = day().slice(69..=69).unwrap();
let full = EnergyEnvelope::new(
Envelope::unbounded(g.clone()),
Energy::from_watt_seconds(i64::MAX - 1),
);
assert!(matches!(
full.check(&plan(&g, &[kw!(1)])),
Err(Error::Overflow { .. })
));
let huge = EnergyEnvelope::new(
Envelope::unbounded(g.clone()),
Energy::from_watt_seconds(i64::MAX),
);
assert!(matches!(
pool::aggregate(&[huge.clone(), huge], who("pool")),
Err(Error::Overflow { .. })
));
}
#[test]
fn sr_007_004_exactness_is_in_the_type() {
let g = day().slice(69..=70).unwrap();
let a = boxed(&g, kw!(0), kw!(10));
assert!(matches!(
pool::aggregate(&[a.clone(), a.clone()], who("pool")),
Ok(Aggregate::Exact(_))
));
let car = a
.level_at(g.end(), Level::at_least(kwh!(5)), who("departure"))
.unwrap();
assert!(matches!(
pool::aggregate(&[car, a], who("pool")),
Ok(Aggregate::Outer(_))
));
}
#[test]
fn sr_007_005_a_split_is_checked_completely() {
let g = day().slice(69..=70).unwrap();
let a = boxed(&g, kw!(0), kw!(10));
let car = a
.level_at(g.end(), Level::at_least(kwh!(5)), who("departure"))
.unwrap();
let pool_plan = plan(&g, &[kw!(10), kw!(10)]);
let r = pool::check_split(
&pool_plan,
&[
(&a, &plan(&g, &[kw!(5), w(4_999)])),
(&car, &plan(&g, &[kw!(5), kw!(5)])),
],
)
.unwrap();
assert_eq!(r.sums.len(), 1);
assert_eq!(r.sums[0].label.isp(), 70);
assert_eq!(r.devices.len(), 1);
assert_eq!(r.devices[0].0, 1);
assert!(!r.fits());
}
}
mod receipt_interchange {
use super::*;
use flexibility::{Deviation, Settlement, baseline, settle};
fn text() -> String {
let g = day().slice(69..=70).unwrap();
let all = Window::new(g.start(), g.end()).unwrap();
let base = baseline::dprognosis(
&Schedule::new(Series::filled(g.clone(), w(10_000_000)), dso()),
all,
)
.unwrap();
let actual = Series::new(g.clone(), vec![w(9_000_000), w(8_000_000)]).unwrap();
settle(
&base,
&actual,
&Series::filled(g, Deviation::from_watts(-2_000_000)),
flexibility::MeasurementPoint::ConnectionPoint,
)
.unwrap()
.canonical()
}
fn read(t: &str) -> Result<Settlement, Error> {
Settlement::from_canonical(t, common::berlin())
}
#[test]
fn sr_008_001_only_canonical_bytes_are_read() {
let t = text();
assert!(read(&t).is_ok());
let spaced = t.replacen(':', ": ", 1);
let duplicated = t.replacen(
"\"method\":\"dprognosis@1\"",
"\"method\":\"dprognosis@1\",\"method\":\"dprognosis@1\"",
1,
);
let extra = t.replacen("{\"grid\"", "{\"a\":1,\"grid\"", 1);
let escaped = t.replacen("settlement", "\\u0073ettlement", 1);
for bad in [spaced, duplicated, extra, escaped] {
assert!(matches!(read(&bad), Err(Error::Receipt { .. })), "{bad}");
}
}
#[test]
fn sr_008_002_what_it_claims_is_checked() {
let t = text();
let path = |bad: String| match read(&bad) {
Err(Error::Receipt { path, .. }) => path,
other => panic!("{other:?}"),
};
assert_eq!(
path(t.replace("flexibility.settlement@1", "flexibility.settlement@2")),
"profile"
);
let bad = t.replacen("\"deficiency\":1000000", "\"deficiency\":0", 1);
let err = read(&bad).unwrap_err();
assert_eq!(
err.to_string(),
"receipt at `lines[0].deficiency`: sent 0, the rule gives 1000000"
);
let delivered: i64 = -(1_000_000 * 900 + 2_000_000 * 900);
assert_eq!(
path(t.replace(
&format!("\"delivered_ws\":{delivered}"),
"\"delivered_ws\":0"
)),
"totals.delivered_ws"
);
}
#[test]
fn sr_008_003_the_reader_is_bounded() {
assert!(read(&"[".repeat(100_000)).is_err());
assert!(read(&"{".repeat(50_000)).is_err());
assert!(read(&format!("[{}]", "1".repeat(1_000))).is_err());
let huge = " ".repeat(flexibility::MAX_RECEIPT_BYTES + 1);
assert!(read(&huge).unwrap_err().to_string().contains("more than"));
for junk in [
"",
"\"",
"{\"",
"[1,",
"-",
"--1",
"01",
"\"\\u12\"",
"\u{0}",
] {
assert!(read(junk).is_err(), "{junk:?}");
}
}
#[test]
fn sr_008_004_refusals_are_safe_to_log() {
let hostile = text().replace("dprognosis@1", &format!("x\ny\r{}", "z".repeat(500)));
let msg = read(&hostile).unwrap_err().to_string();
assert!(!msg.contains('\n') && !msg.contains('\r'), "{msg}");
assert!(msg.chars().count() < 160, "{msg}");
}
}
mod measurement_and_rebound {
use super::*;
use flexibility::baseline::{self, Mbma};
use flexibility::{Deviation, Difference, MeasurementPoint, Settlement, settle};
const MBMA: Mbma = Mbma { n: 4, gap: 1 };
fn measured(during: i64, after: i64) -> Series<Power> {
let g = day();
Series::new(
g.clone(),
g.numbers()
.map(|isp| match isp {
69..=76 => w(during),
77..=80 => w(after),
_ => w(7_000),
})
.collect(),
)
.unwrap()
}
fn settled(m: &Series<Power>, order: i64, at: MeasurementPoint) -> Settlement {
let ev = win(17, 0, 19, 0);
let actual = m.over(ev).unwrap();
let ordered = Series::filled(actual.grid().clone(), Deviation::from_watts(order));
settle(&baseline::mbma(m, ev, MBMA).unwrap(), &actual, &ordered, at).unwrap()
}
fn rebound(m: &Series<Power>, s: &Settlement) -> Result<flexibility::Rebound, Error> {
s.rebound(
&baseline::mbma(m, win(17, 0, 20, 0), MBMA).unwrap(),
&m.over(win(19, 0, 20, 0)).unwrap(),
s.measured_at().clone(),
)
}
#[test]
fn sr_009_001_the_meter_is_in_the_receipt() {
let m = measured(4_500, 7_000);
let fiscal = settled(&m, -3_000, MeasurementPoint::ConnectionPoint);
let sub = settled(&m, -3_000, MeasurementPoint::device("hp-1").unwrap());
assert_ne!(fiscal.digest(), sub.digest());
assert!(matches!(
fiscal.diff(&sub),
Some(Difference::MeasurementPoint { .. })
));
let back = Settlement::from_canonical(&sub.canonical(), common::berlin()).unwrap();
assert_eq!(back.measured_at(), sub.measured_at());
}
#[test]
fn sr_009_002_device_ids_are_bounded() {
for bad in [String::new(), "x".repeat(65), "a\nb".into()] {
let err = MeasurementPoint::device(&bad).unwrap_err();
assert!(matches!(err, Error::DeviceId { .. }));
assert!(!err.to_string().contains('\n'));
}
}
#[test]
fn sr_009_003_rebound_has_the_right_sign() {
let back = measured(4_500, 9_000);
let r = rebound(
&back,
&settled(&back, -3_000, MeasurementPoint::ConnectionPoint),
)
.unwrap();
assert!(r.lines().iter().all(|l| l.rebound == w(2_000)));
let still = measured(4_500, 5_000);
let r = rebound(
&still,
&settled(&still, -3_000, MeasurementPoint::ConnectionPoint),
)
.unwrap();
assert!(r.lines().iter().all(|l| l.rebound == w(0)));
let up = measured(10_000, 6_000);
let r = rebound(&up, &settled(&up, 3_000, MeasurementPoint::ConnectionPoint)).unwrap();
assert!(r.lines().iter().all(|l| l.rebound == w(1_000)));
let none = settled(&back, 0, MeasurementPoint::ConnectionPoint);
assert!(matches!(rebound(&back, &none), Err(Error::Method { .. })));
}
#[test]
fn sr_009_004_rebound_is_anchored() {
let m = measured(4_500, 9_000);
let s = settled(&m, -3_000, MeasurementPoint::ConnectionPoint);
let ext = baseline::mbma(&m, win(17, 0, 20, 0), MBMA).unwrap();
assert!(
s.rebound(
&ext,
&m.over(win(19, 15, 20, 0)).unwrap(),
MeasurementPoint::ConnectionPoint
)
.is_err()
);
assert!(
s.rebound(
&ext,
&m.over(win(19, 0, 20, 0)).unwrap(),
MeasurementPoint::device("x").unwrap()
)
.is_err()
);
let declared = baseline::dprognosis(
&Schedule::new(Series::filled(day(), w(7_000)), dso()),
win(17, 0, 20, 0),
)
.unwrap();
assert!(
s.rebound(
&declared,
&m.over(win(19, 0, 20, 0)).unwrap(),
MeasurementPoint::ConnectionPoint
)
.is_err()
);
let mut m2 = m.values().to_vec();
m2[70] = w(4_400);
let m2 = Series::new(day(), m2).unwrap();
let s2 = settled(&m2, -3_000, MeasurementPoint::ConnectionPoint);
let a = rebound(&m, &s).unwrap();
let b = rebound(&m2, &s2).unwrap();
assert_eq!(a.total(), b.total());
assert_ne!(a.digest(), b.digest());
}
}
#[cfg(feature = "s2")]
mod s2_conversion {
use super::*;
use flexibility::s2::{self, wire};
use flexibility::{Envelope, Limit, Rounding};
use wire::types::pebc::{Instruction, PowerEnvelope, PowerEnvelopeElement};
use wire::types::ppbc::{PowerSequence, PowerSequenceElement};
use wire::types::{CommodityQuantity, Duration, Id, PowerForecastValue};
const L1: CommodityQuantity = CommodityQuantity::ElectricPowerL1;
fn instruction(elements: Vec<PowerEnvelopeElement>) -> Instruction {
Instruction {
message_id: Id::new_const("m-1"),
id: Id::new_const("i-1"),
execution_time: at(17, 0).into(),
abnormal_condition: false,
power_constraints_id: Id::new_const("pc-1"),
power_envelopes: vec![PowerEnvelope {
id: Id::new_const("pe-1"),
commodity_quantity: L1,
power_envelope_elements: elements,
}],
}
}
fn element(lower: f64, upper: f64) -> PowerEnvelopeElement {
PowerEnvelopeElement::new(Duration::from_secs(900), lower, upper)
}
#[test]
fn sr_010_001_signs_pass_through() {
let pv = s2::limits(&instruction(vec![element(-2_000.0, 0.0)]), L1, &dso()).unwrap();
assert_eq!(pv[0].bounds().min(), Some(w(-2_000)));
assert_eq!(pv[0].bounds().max(), Some(w(0)));
let heat = s2::limits(&instruction(vec![element(0.0, 3_000.0)]), L1, &dso()).unwrap();
assert_eq!(heat[0].bounds().max(), Some(w(3_000)));
}
#[test]
fn sr_010_002_numbers_are_exact() {
for bad in [-2_000.5, f64::INFINITY, f64::NAN, 1e30] {
assert!(
matches!(
s2::limits(&instruction(vec![element(bad, 0.0)]), L1, &dso()),
Err(Error::Unrepresentable { protocol: "S2", .. })
),
"{bad}"
);
}
let seq = PowerSequence {
id: Id::new_const("seq-1"),
elements: vec![PowerSequenceElement {
duration: Duration::from_secs(900),
power_values: vec![PowerForecastValue::expected(2_000.3, L1)],
}],
is_interruptible: false,
max_pause_before: None,
abnormal_condition_only: false,
};
assert!(s2::schedule(&seq, L1, at(17, 0), &day(), Rounding::Exact, dso()).is_err());
let plan = s2::schedule(
&seq,
L1,
at(17, 0),
&day(),
Rounding::HalfAwayFromZero,
dso(),
)
.unwrap();
assert_eq!(plan.series().values(), [w(2_000)]);
}
#[test]
fn sr_010_003_nothing_is_placed_or_dropped_silently() {
let limits = s2::limits(
&instruction(vec![element(-1.0, 0.0), element(-2.0, 0.0)]),
L1,
&dso(),
)
.unwrap();
assert_eq!(
limits[1].window(),
Window::new(at(17, 15), at(17, 30)).unwrap()
);
let half = Limit::consumption_cap(win(17, 0, 18, 0), w(5_000), dso());
let open = Envelope::unbounded(day()).apply(&half).unwrap();
assert!(s2::power_envelope(&open, Id::new_const("pe"), L1).is_err());
}
#[test]
fn sr_010_004_s2_kit_is_pinned_and_light() {
let manifest = include_str!("../Cargo.toml");
let line = manifest
.lines()
.find(|l| l.starts_with("s2-kit = {"))
.unwrap();
assert!(
line.contains("version = \"0.7\"")
&& line.contains("default-features = false")
&& line.contains("optional = true"),
"{line}"
);
}
}
#[cfg(feature = "openadr")]
mod openadr_conversion {
use super::*;
use flexibility::Rounding;
use flexibility::jiff::Timestamp;
use flexibility::openadr::{self, wire};
use wire::model::{Event, Report};
fn t(s: &str) -> Timestamp {
s.parse().unwrap()
}
fn event(descriptor: &str, period: &str, values: &str) -> Event {
serde_json::from_str(&format!(
r#"{{"id": "e1", "programID": "p1",
"createdDateTime": "2026-03-13T12:00:00Z", "modificationDateTime": "2026-03-13T12:00:00Z",
"payloadDescriptors": [{descriptor}], "intervalPeriod": {period},
"intervals": [{{"id": 0, "payloads": [{{"type": "IMPORT_CAPACITY_LIMIT", "values": [{values}]}}]}}]}}"#
))
.unwrap()
}
const KW: &str = r#"{"payloadType": "IMPORT_CAPACITY_LIMIT", "units": "KW"}"#;
const HOUR: &str = r#"{"start": "2026-03-14T00:00:00Z", "duration": "PT1H"}"#;
fn day() -> Window {
Window::new(t("2026-03-14T00:00:00Z"), t("2026-03-15T00:00:00Z")).unwrap()
}
fn limits(e: &Event) -> Result<Vec<flexibility::Limit>, Error> {
openadr::limits(&e.content, None, day(), t("2026-03-14T00:00:00Z"), &dso())
}
#[test]
fn sr_011_001_units_are_never_guessed() {
assert!(limits(&event(KW, HOUR, "5")).is_ok());
let none = r#"{"payloadType": "IMPORT_CAPACITY_LIMIT"}"#;
assert!(matches!(
limits(&event(none, HOUR, "5")),
Err(Error::Unrepresentable { field: "units", .. })
));
}
#[test]
fn sr_011_002_limits_are_exact_magnitudes() {
assert_eq!(
limits(&event(KW, HOUR, "7.56")).unwrap()[0].bounds().max(),
Some(w(7_560))
);
assert_eq!(limits(&event(KW, HOUR, "1, 2")).unwrap().len(), 2);
for bad in ["7.5605", "-1", "\"x\""] {
assert!(limits(&event(KW, HOUR, bad)).is_err(), "{bad}");
}
}
#[test]
fn sr_011_003_time_is_read_strictly() {
let random =
r#"{"start": "2026-03-14T00:00:00Z", "duration": "PT1H", "randomizeStart": "PT10M"}"#;
assert_eq!(
limits(&event(KW, random, "5")).unwrap()[0].window().until(),
t("2026-03-14T01:10:00Z")
);
let forever = r#"{"start": "2026-03-14T06:00:00Z", "duration": "P9999Y"}"#;
assert_eq!(
limits(&event(KW, forever, "5")).unwrap()[0]
.window()
.until(),
day().until()
);
}
#[test]
fn sr_011_004_usage_is_complete_or_refused() {
let report: Report = serde_json::from_str(
r#"{"id": "r1", "eventID": "e1", "clientName": "ven-1",
"createdDateTime": "2026-03-14T02:00:00Z", "modificationDateTime": "2026-03-14T02:00:00Z",
"payloadDescriptors": [{"payloadType": "USAGE", "units": "KWH"}],
"resources": [{"resourceName": "m", "intervalPeriod": {"start": "2026-03-14T00:00:00Z", "duration": "PT15M"},
"intervals": [{"id": 0, "payloads": [{"type": "USAGE", "values": [1]}]}]}]}"#,
)
.unwrap();
let one = Grid::new(
t("2026-03-14T00:00:00Z"),
IspDuration::FIFTEEN_MINUTES,
1,
TimeZone::UTC,
)
.unwrap();
assert_eq!(
openadr::usage(&report.content, "m", None, &one, Rounding::Exact)
.unwrap()
.values(),
[w(4_000)]
);
let two = Grid::new(
t("2026-03-14T00:00:00Z"),
IspDuration::FIFTEEN_MINUTES,
2,
TimeZone::UTC,
)
.unwrap();
assert!(openadr::usage(&report.content, "m", None, &two, Rounding::Exact).is_err());
}
#[test]
fn sr_011_005_expansion_is_bounded_and_the_crate_pinned() {
let event: Event = serde_json::from_str(&format!(
r#"{{"id": "e1", "programID": "p1", "duration": "P9999Y",
"createdDateTime": "2026-03-13T12:00:00Z", "modificationDateTime": "2026-03-13T12:00:00Z",
"payloadDescriptors": [{KW}],
"intervalPeriod": {{"start": "2026-03-14T00:00:00Z", "duration": "PT1S"}},
"intervals": [{{"id": 0, "payloads": [{{"type": "IMPORT_CAPACITY_LIMIT", "values": [5]}}]}}]}}"#
))
.unwrap();
assert!(matches!(
limits(&event),
Err(Error::Unrepresentable {
field: "intervals",
..
})
));
let manifest = include_str!("../Cargo.toml");
let line = manifest
.lines()
.find(|l| l.starts_with("openadr = {"))
.unwrap();
assert!(
line.contains("version = \"0.10\"") && line.contains("default-features = false"),
"{line}"
);
}
}
mod stack_digest {
use super::*;
use flexibility::{MAX_EXACT, MeasurementPoint, Settlement, canonical_series};
fn settlement() -> flexibility::Settlement {
let base = baseline::dprognosis(
&Schedule::new(Series::filled(day(), w(7_000)), dso()),
win(17, 0, 18, 0),
)
.unwrap();
let actual = Series::filled(base.series().grid().clone(), w(4_500));
let ordered = Series::filled(base.series().grid().clone(), Deviation::from_watts(-3_000));
settle(&base, &actual, &ordered, MeasurementPoint::ConnectionPoint).unwrap()
}
#[test]
fn sr_012_001_integers_are_exact_for_any_rfc_8785_library() {
let edge = i64::try_from(MAX_EXACT).unwrap();
let g = Grid::new(
flexibility::jiff::Timestamp::UNIX_EPOCH,
IspDuration::FIFTEEN_MINUTES,
1,
TimeZone::UTC,
)
.unwrap();
assert!(canonical_series(&Series::filled(g.clone(), w(edge))).is_ok());
assert!(matches!(
canonical_series(&Series::filled(g, w(edge + 1))),
Err(Error::Unrepresentable {
protocol: "canon@1",
..
})
));
let text = settlement().canonical();
let beyond = text.replacen("\"actual\":4500", "\"actual\":9007199254740993", 1);
assert!(matches!(
Settlement::from_canonical(&beyond, common::berlin()),
Err(Error::Receipt { .. })
));
}
#[test]
fn sr_012_002_documents_name_their_profile() {
let s = settlement();
assert!(
s.canonical()
.contains(r#""profile":"flexibility.settlement@1""#)
);
let base = baseline::dprognosis(
&Schedule::new(Series::filled(day(), w(7_000)), dso()),
win(17, 0, 18, 0),
)
.unwrap();
assert!(
base.canonical()
.contains(r#""profile":"flexibility.baseline@1""#)
);
let err = Settlement::from_canonical(&base.canonical(), common::berlin()).unwrap_err();
assert!(
matches!(err, Error::Receipt { ref path, .. } if path == "profile"),
"{err}"
);
}
#[test]
fn sr_012_003_digests_carry_their_algorithm() {
let d = settlement().digest();
let text = d.to_string();
assert!(text.starts_with("sha256:") && text.len() == 71, "{text}");
assert_eq!(text.parse::<Digest>().unwrap(), d);
assert!(text["sha256:".len()..].parse::<Digest>().is_err());
assert!(text.replace("sha256", "sha512").parse::<Digest>().is_err());
assert!(settlement().canonical().contains("\"baseline\":\"sha256:"));
}
#[test]
fn sr_012_004_a_second_encoder_agrees_byte_for_byte() {
let s = settlement();
let base = baseline::dprognosis(
&Schedule::new(Series::filled(day(), w(7_000)), dso()),
win(17, 0, 18, 0),
)
.unwrap();
let weird = Provenance::new("a\"b\\c\nd\u{1}รฉ", "r\te", at(0, 0));
let odd = baseline::schedule(
&Schedule::new(Series::filled(day(), w(-1)), weird),
win(17, 0, 18, 0),
)
.unwrap();
let series = canonical_series(base.series()).unwrap();
for text in [s.canonical(), base.canonical(), odd.canonical(), series] {
let parsed: serde_json::Value = serde_json::from_str(&text).unwrap();
assert_eq!(serde_json::to_string(&parsed).unwrap(), text);
}
}
}
#[cfg(feature = "csip")]
mod csip_conversion {
use super::*;
use flexibility::csip::{self, wire};
use wire::csip_aus::{ActivePower, Mode, SiteMode};
use wire::schedule::{Event, Offset, Window as Interval};
const NMI: &str = "NMI-1";
fn noon() -> i64 {
at(12, 0).as_second()
}
fn event(
id: u128,
mode: Mode,
kw: i16,
primacy: u8,
created: i64,
) -> Event<SiteMode<'static>, ActivePower> {
Event {
id,
mode: SiteMode {
connection_point: NMI,
mode,
},
value: ActivePower {
value: kw,
multiplier: 3,
},
primacy,
created,
received: created,
window: Interval::new(noon(), 3_600, Offset::default(), Offset::default()).unwrap(),
termination: None,
}
}
fn grid() -> Grid {
Grid::new(at(12, 0), IspDuration::FIFTEEN_MINUTES, 4, TimeZone::UTC).unwrap()
}
#[test]
fn sr_013_001_signs_follow_the_connection_point() {
let e = csip::envelope(
&[
event(1, Mode::Import, 7, 1, noon() - 60),
event(2, Mode::Export, 3, 1, noon() - 60),
],
NMI,
&[],
&grid(),
&dso(),
)
.unwrap();
assert_eq!(e.bounds(1).unwrap().max(), Some(w(7_000)));
assert_eq!(e.bounds(1).unwrap().min(), Some(w(-3_000)));
}
#[test]
fn sr_013_002_supersession_is_the_protocols() {
let e = csip::envelope(
&[
event(1, Mode::Export, 1, 1, noon() - 120),
event(2, Mode::Export, 4, 1, noon() - 60),
],
NMI,
&[],
&grid(),
&dso(),
)
.unwrap();
assert_eq!(e.bounds(1).unwrap().min(), Some(w(-4_000)));
let tie = csip::envelope(
&[
event(1, Mode::Export, 1, 1, noon() - 60),
event(2, Mode::Export, 4, 1, noon() - 60),
],
NMI,
&[],
&grid(),
&dso(),
);
assert!(tie.is_err());
}
#[test]
fn sr_013_003_the_strictest_instant_of_an_isp_holds() {
let mut late = event(1, Mode::Import, 1, 1, noon() - 60);
late.window =
Interval::new(noon() + 600, 60, Offset::default(), Offset::default()).unwrap();
let defaults = [(
Mode::Import,
ActivePower {
value: 9,
multiplier: 3,
},
)];
let e = csip::envelope(&[late], NMI, &defaults, &grid(), &dso()).unwrap();
assert_eq!(e.bounds(1).unwrap().max(), Some(w(1_000)));
assert_eq!(e.bounds(2).unwrap().max(), Some(w(9_000)));
}
#[test]
fn sr_013_004_values_and_work_are_bounded() {
let mut frac = event(1, Mode::Import, 1, 1, noon() - 60);
frac.value = ActivePower {
value: 15,
multiplier: -1,
};
assert!(csip::envelope(&[frac], NMI, &[], &grid(), &dso()).is_err());
let many: Vec<_> = (0..=csip::MAX_CONTROLS)
.map(|i| {
event(
u128::try_from(i).unwrap(),
Mode::Import,
1,
1,
noon() - 60 - i64::try_from(i).unwrap(),
)
})
.collect();
assert!(csip::envelope(&many, NMI, &[], &grid(), &dso()).is_err());
let line = include_str!("../Cargo.toml")
.lines()
.find(|l| l.starts_with("ieee2030-5 = {"))
.unwrap();
assert!(
line.contains("version = \"0.2\"") && line.contains("default-features = false"),
"{line}"
);
}
}
mod limits_and_fixes {
use super::*;
use flexibility::baseline::{Adjustment, XofY};
use flexibility::{EnergyEnvelope, Level, kwh};
#[test]
fn sr_014_001_history_lines_up_by_local_time() {
let target = day_of(date(2026, 10, 26)).slice(69..=76).unwrap();
let event = Window::new(target.start(), target.end()).unwrap();
let params = XofY {
x: 1,
y: 2,
adjustment: Adjustment::None,
};
let by_number = [
Series::filled(
day_of(date(2026, 10, 25)).slice(69..=76).unwrap(),
w(10_000),
),
Series::filled(day_of(date(2026, 10, 24)).slice(69..=76).unwrap(), w(5_000)),
];
assert!(baseline::xofy(&target, event, &by_number, None, params).is_err());
}
#[test]
fn sr_014_002_rebound_needs_the_order_covered() {
let m = Series::filled(day(), w(7_000));
let b = baseline::mbma(&m, win(17, 0, 18, 0), baseline::Mbma { n: 4, gap: 1 }).unwrap();
let actual = m.over(win(17, 0, 18, 0)).unwrap();
let ordered = Series::filled(actual.grid().clone(), Deviation::from_watts(-1_000));
let s = settle(
&b,
&actual,
&ordered,
flexibility::MeasurementPoint::ConnectionPoint,
)
.unwrap();
let alone = baseline::mbma(&m, win(18, 0, 19, 0), baseline::Mbma { n: 4, gap: 1 }).unwrap();
assert!(
s.rebound(
&alone,
&m.over(win(18, 0, 19, 0)).unwrap(),
flexibility::MeasurementPoint::ConnectionPoint
)
.is_err()
);
}
#[test]
fn sr_014_003_the_initial_level_is_checked() {
let e = EnergyEnvelope::new(Envelope::unbounded(day().slice(1..=4).unwrap()), kwh!(20));
assert!(matches!(
e.level_always(Level::at_most(kwh!(9)), fuse()),
Err(Error::InitialLevel { .. })
));
}
#[test]
fn sr_014_004_named_limits_and_text_are_exact() {
let window = win(17, 0, 18, 0);
assert_eq!(
Limit::consumption_floor(window, w(2_000), dso())
.bounds()
.min(),
Some(w(2_000))
);
assert_eq!(
Limit::feed_in_floor(window, w(2_000), dso())
.unwrap()
.bounds()
.max(),
Some(w(-2_000))
);
assert!(Limit::feed_in_floor(window, w(-1), dso()).is_err());
assert!(Limit::band(window, w(2), w(1), dso()).is_err());
assert_eq!("5.0 W".parse::<flexibility::Power>().unwrap(), w(5));
assert!("5.5 W".parse::<flexibility::Power>().is_err());
}
}
#[cfg(feature = "iec104")]
mod iec104_conversion {
use super::*;
use flexibility::Rounding;
use flexibility::iec104::{self, Direction, Point, Scale, wire};
use wire::types::{Normalized, SetpointFloat, SetpointNormalized, SetpointScaled};
const PARK: Point = Point {
direction: Direction::FeedIn,
scale: Scale::Normalized {
full_scale: flexibility::mw!(10),
},
};
const SITE: Point = Point {
direction: Direction::Consumption,
scale: Scale::Scaled {
step: flexibility::kw!(1),
},
};
#[test]
fn sr_015_001_the_point_list_decides() {
let park = iec104::limit(
SetpointNormalized::new(Normalized(16_384)),
PARK,
win(17, 0, 18, 0),
Rounding::Exact,
dso(),
)
.unwrap();
assert_eq!(park.bounds().min(), Some(w(-5_000_000)));
assert!(
iec104::limit(
SetpointFloat::new(5.0),
SITE,
win(17, 0, 18, 0),
Rounding::Exact,
dso()
)
.is_err()
);
}
#[test]
fn sr_015_002_only_an_execute_sets_a_value() {
assert!(
iec104::limit(
SetpointScaled::new(10).select(),
SITE,
win(17, 0, 18, 0),
Rounding::Exact,
dso()
)
.is_err()
);
}
#[test]
fn sr_015_003_rounding_is_named_and_strict() {
let thirty = SetpointNormalized::new(Normalized(9_830));
assert!(iec104::limit(thirty, PARK, win(17, 0, 18, 0), Rounding::Exact, dso()).is_err());
let s = iec104::setpoint(w(3_000_000), PARK, Rounding::TowardZero).unwrap();
let back = iec104::limit(s, PARK, win(17, 0, 18, 0), Rounding::TowardZero, dso()).unwrap();
assert!(back.bounds().min().unwrap() >= w(-3_000_000));
}
#[test]
fn sr_015_004_floats_are_exact_and_the_crate_light() {
let kw_point = Point {
direction: Direction::Consumption,
scale: Scale::Float {
unit: flexibility::kw!(1),
},
};
assert_eq!(
iec104::limit(
SetpointFloat::new(4.2),
kw_point,
win(17, 0, 18, 0),
Rounding::Exact,
dso()
)
.unwrap()
.bounds()
.max(),
Some(w(4_200))
);
assert!(
iec104::limit(
SetpointFloat::new(f32::INFINITY),
kw_point,
win(17, 0, 18, 0),
Rounding::Exact,
dso()
)
.is_err()
);
let line = include_str!("../Cargo.toml")
.lines()
.find(|l| l.starts_with("iec60870 = {"))
.unwrap();
assert!(
line.contains("version = \"0.2\"") && line.contains("default-features = false"),
"{line}"
);
}
}
#[cfg(feature = "cls")]
mod cls_conversion {
use super::*;
use flexibility::cls::{self, wire};
fn control(json: &str) -> wire::wire::Control {
serde_json::from_str(json).unwrap()
}
#[test]
fn sr_016_001_signs_follow_the_direction() {
let c = control(
r#"{"limits": {"power": {"active": {"production": {"value": 3000, "active": true}}}}}"#,
);
assert_eq!(
cls::limits(&c, at(17, 0), at(23, 0), &dso()).unwrap()[0]
.bounds()
.min(),
Some(w(-3_000))
);
}
#[test]
fn sr_016_002_protocol_rules_hold() {
for bad in [
r#"{"limits": {"power": {"active": {"consumption": {"value": 0, "active": true}}}}}"#,
r#"{"limits": {"power": {"active": {"consumption": {"value": 1, "active": true, "duration": 0}}}}}"#,
r#"{"limits": {"power": {"active": {"consumption": {"value": -5, "active": true}}}}}"#,
] {
assert!(
cls::limits(&control(bad), at(17, 0), at(23, 0), &dso()).is_err(),
"{bad}"
);
}
}
#[test]
fn sr_016_003_the_guarantee_holds() {
let c = control(
r#"{"limits": {"power": {"active": {"consumption": {"value": 3000, "active": true}}}}}"#,
);
let all = Window::new(day().start(), day().end()).unwrap();
let env = Envelope::unbounded(day())
.guarantee(&flexibility::Guarantee::consumption(all, w(4_200), fuse()).unwrap())
.unwrap();
assert!(
env.apply(&cls::limits(&c, at(17, 0), at(23, 0), &dso()).unwrap()[0])
.is_err()
);
}
#[test]
fn sr_016_004_the_crate_is_pinned() {
let line = include_str!("../Cargo.toml")
.lines()
.find(|l| l.starts_with("cls-eedi = {"))
.unwrap();
assert!(
line.contains("version = \"0.2\"") && line.contains("optional = true"),
"{line}"
);
}
}