emob_session/split.rs
1//! Splitting a session across quarter hours, exactly.
2//!
3//! # Why this exists
4//!
5//! A charging session that runs from 10:07 to 11:23 has to be settled against
6//! six quarter hours. Under German pass-through charging (NZR-EMob / Modell 2)
7//! the operator assigns each quarter hour's energy to the balance group of the
8//! supplier the driver chose, quarter hour by quarter hour `[A6 §IV.1]`, and
9//! `mako-emob` will not accept a set of numbers that does not add up.
10//!
11//! So this module has one hard requirement and one honest one.
12//!
13//! # Conservation is by construction, not by reconciliation
14//!
15//! The naive approach computes each slot's energy independently and then
16//! discovers the sum is a few milliwatt-hours off the session total, because
17//! rounding happened six times. The usual fix is to shove the difference into
18//! the last slot, which silently misattributes energy to whoever held 11:15.
19//!
20//! Instead, this computes the **cumulative** energy at each quarter-hour
21//! *boundary* once, and takes differences:
22//!
23//! ```text
24//! slot[i] = cumulative(boundary[i+1]) − cumulative(boundary[i])
25//! ```
26//!
27//! The sum telescopes: every interior boundary appears once positive and once
28//! negative and cancels exactly, whatever it was rounded to. What is left is
29//! `cumulative(end) − cumulative(start)`, which is the session total, to the
30//! last digit, always. [`SessionSplit::conserves`] proves it, and a property
31//! test runs it over hundreds of generated sessions.
32//!
33//! # The grid is not the only thing that cuts a session
34//!
35//! A quarter hour is where the *energy* settles. It is not where the *price*
36//! changes: `[AFIR Art. 5(4)]` lets a fast charger add an occupancy fee per
37//! minute for the time a vehicle is connected and **not** charging, and a
38//! vehicle stops charging when it stops charging, not at `:15:00`. A slot that
39//! ran from 10:15 to 10:30 with the charge finishing at 10:20 is ten minutes of
40//! occupancy and five minutes of charging, and one flag cannot say so.
41//!
42//! So [`into_periods`] takes extra cut instants beside the grid — the session's
43//! own state changes, for the caller that has them — and every one of them is
44//! just another boundary in the same telescoping sum. Conservation is
45//! unaffected: interior boundaries cancel whatever they were rounded to,
46//! wherever they fall. [`Session::split`] passes the session's history, so a
47//! CDR built from it prices each minute at the rate that minute earned.
48//!
49//! [`Session::split`]: crate::Session::split
50//!
51//! # Where the numbers come from is recorded
52//!
53//! A boundary that a `Sample.Clock` reading landed on exactly is
54//! [`Provenance::Measured`]. A boundary between two readings is
55//! [`Provenance::Interpolated`] — and that assumes constant power across the
56//! gap, which a tapering charge curve does not deliver. The error lands on
57//! whichever supplier held the boundary, so the assumption travels with the
58//! number rather than being forgotten.
59//!
60//! # …and constant power means constant power *while charging*
61//!
62//! A straight line between two readings is the honest guess across a gap the
63//! session says nothing about. It is a wrong guess across a gap the session
64//! says something about: a transaction that opens `EVConnected`, starts
65//! charging thirty seconds later and sends its next meter value at the quarter
66//! hour — the ordinary OCPP 2.0.1 shape — has a register that did not move for
67//! those thirty seconds, and a line drawn from the opening reading attributes
68//! thirty seconds' worth of energy to an interval the operator's own state
69//! machine calls suspended. The CDR builder then refuses the record for a
70//! contradiction the arithmetic invented.
71//!
72//! So [`into_periods`] takes the session's **idle intervals** beside its cuts,
73//! and interpolates over *charging time only*: the register is held flat across
74//! an idle interval and the gap's energy is spread over the seconds that remain.
75//! Where a gap has no charging time at all and the register moved anyway, the
76//! line is drawn across the whole gap and the contradiction is left standing for
77//! the builder to report — it is now a real one.
78//!
79//! # Quarter hours and daylight saving
80//!
81//! A quarter hour here is an instant plus fifteen minutes of real time. Every
82//! civil UTC offset in the world is a whole number of quarter hours, so a UTC
83//! quarter-hour boundary is a local quarter-hour boundary everywhere — and the
84//! 92- and 100-slot days of a clock change are simply days with fewer or more
85//! instants in them. Nothing here counts to 96, and there is no DST branch.
86
87use emob_core::{Direction, Energy, QuarterHour, apportion};
88use rust_decimal::Decimal;
89
90use crate::meter::{MeterSeries, ReadingContext};
91
92/// Where a number came from.
93#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
94#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
95#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
96pub enum Provenance {
97 /// A meter reading landed on this instant. The station measured it.
98 Measured,
99 /// The register was **held** at a measured reading's value across an
100 /// interval the session says nothing flowed in.
101 ///
102 /// The value is exact, on the session's own account: between the reading
103 /// and this instant the vehicle was connected and not charging, so the
104 /// register cannot have moved. What it rests on is the operator's state
105 /// machine rather than a second reading — which is why it is a third answer
106 /// rather than [`Self::Measured`], and why a settlement may still treat the
107 /// number as authoritative where it may not treat an interpolated one so.
108 Held,
109 /// Derived by assuming constant power between two readings.
110 ///
111 /// Which a tapering charge curve does not deliver: a car at 80 % state of
112 /// charge draws far less at the end of a gap than at its start, so a
113 /// straight line over-allocates to the later side. The error is bounded by
114 /// the gap, which is why `AlignedDataInterval = 900` matters.
115 Interpolated,
116}
117
118impl Provenance {
119 /// The weaker of two provenances — what a slot inherits from its two
120 /// boundaries.
121 #[must_use]
122 pub const fn weaker(self, other: Self) -> Self {
123 match (self, other) {
124 (Self::Measured, Self::Measured) => Self::Measured,
125 (Self::Interpolated, _) | (_, Self::Interpolated) => Self::Interpolated,
126 _ => Self::Held,
127 }
128 }
129
130 /// Whether the number this provenance describes is exact — measured, or
131 /// held at a measurement — rather than assumed.
132 #[must_use]
133 pub const fn is_exact(self) -> bool {
134 !matches!(self, Self::Interpolated)
135 }
136
137 /// The provenance of a boundary whose value was carried unchanged from a
138 /// reading: a held measurement, or an interpolation that was already one.
139 const fn held_from(reading: Self) -> Self {
140 match reading {
141 Self::Measured | Self::Held => Self::Held,
142 Self::Interpolated => Self::Interpolated,
143 }
144 }
145}
146
147/// One slice of a session, inside one quarter hour.
148///
149/// The settlement slot and the measured window are separate fields, and that is
150/// the whole point of the type. A session whose readings run 10:07 to 10:23 has
151/// its first slot reported under the quarter hour beginning **10:00** — that is
152/// the settlement period the energy belongs to `[A6 §IV.1]` — while the energy
153/// itself was measured over **10:07 to 10:15**. Both statements are true and
154/// they are different instants, and a consumer that reconstructs one from the
155/// other has to guess.
156///
157/// One quarter hour may hold **more than one slot**, whenever a cut passed to
158/// [`into_periods`] falls inside it — a session that stops charging at 10:20
159/// yields a charging slice and an occupancy slice, both under the quarter hour
160/// beginning 10:15. [`SessionSplit::market_series`] sums them back together for
161/// the market side, which settles per period and not per slice.
162#[derive(Debug, Clone, PartialEq, Eq)]
163#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
164pub struct Slot {
165 /// Which quarter hour this energy settles in.
166 pub quarter_hour: QuarterHour,
167 /// The first instant the meter series covers inside that quarter hour.
168 ///
169 /// Equal to [`QuarterHour::start`] for every slot but the first, and to the
170 /// first reading's instant for that one.
171 #[cfg_attr(feature = "serde", serde(with = "time::serde::rfc3339"))]
172 pub from: time::OffsetDateTime,
173 /// The last instant it covers — [`QuarterHour::end`] except in the final
174 /// slot, which stops at the last reading.
175 #[cfg_attr(feature = "serde", serde(with = "time::serde::rfc3339"))]
176 pub to: time::OffsetDateTime,
177 /// How much energy the session moved inside it.
178 pub energy: Energy,
179 /// Which way.
180 pub direction: Direction,
181 /// How the number was arrived at.
182 pub provenance: Provenance,
183}
184
185impl Slot {
186 /// How long the measured window lasted.
187 #[must_use]
188 pub fn duration(&self) -> time::Duration {
189 self.to - self.from
190 }
191
192 /// Whether the slot's readings cover its whole quarter hour.
193 ///
194 /// False for the first and last slot of a session that began or ended
195 /// mid-quarter — which is most of them — and for every slice of a quarter
196 /// hour a cut divided.
197 #[must_use]
198 pub fn covers_the_whole_quarter_hour(&self) -> bool {
199 self.from == self.quarter_hour.start() && self.to == self.quarter_hour.end()
200 }
201}
202
203/// A session, split across the quarter hours it touched.
204#[derive(Debug, Clone, PartialEq, Eq)]
205#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
206pub struct SessionSplit {
207 /// The slots, in time order, with no gaps.
208 pub slots: Vec<Slot>,
209 /// The session total the split was taken from.
210 pub total: Energy,
211 /// The direction of every slot.
212 pub direction: Direction,
213}
214
215impl SessionSplit {
216 /// Whether the slots add up to the total, exactly.
217 ///
218 /// Always true by construction; asserted anyway, because a conservation
219 /// property that is never checked is a conservation property that quietly
220 /// stops holding.
221 #[must_use]
222 pub fn conserves(&self) -> bool {
223 self.slots.iter().map(|s| s.energy).sum::<Energy>() == self.total
224 }
225
226 /// The slots whose energy was interpolated rather than measured.
227 pub fn interpolated(&self) -> impl Iterator<Item = &Slot> {
228 self.slots
229 .iter()
230 .filter(|s| s.provenance == Provenance::Interpolated)
231 }
232
233 /// Whether every slot's energy is exact — measured at both its boundaries,
234 /// or held at a measurement across an interval the session says nothing
235 /// flowed in — with nothing interpolated anywhere.
236 ///
237 /// The question a settlement process should ask before treating the split
238 /// as authoritative.
239 #[must_use]
240 pub fn fully_measured(&self) -> bool {
241 self.slots.iter().all(|s| s.provenance.is_exact())
242 }
243
244 /// The series in the form the market side reads it: each period labelled by
245 /// its **end**.
246 ///
247 /// The one conversion that separates this workspace's grid from a German
248 /// load profile. Internally a quarter hour is named by its start, because
249 /// that is the only spelling in which `containing()` is a truncation;
250 /// `[PTB-A 50.7 §3.1.7.2]` labels a Messperiode by its end, and so do
251 /// MSCONS and `mako-emob`. Mixing the two shifts every slot by fifteen
252 /// minutes — an error that sums to zero across the session and is wrong for
253 /// every individual balance group `[A6 §IV.1]`.
254 ///
255 /// So the conversion happens once, here, rather than in each adapter that
256 /// needs it.
257 ///
258 /// Slices of one quarter hour are summed back together. A cut at a state
259 /// change divides a slot for *pricing* — an occupancy fee is a price per
260 /// minute `[AFIR Art. 5(4)]` — and the market side settles a whole
261 /// Messperiode against one balance group, so handing it two entries for one
262 /// timestamp would be a file no `mako-emob` allocation can read.
263 #[must_use]
264 pub fn market_series(&self) -> Vec<(time::OffsetDateTime, Energy)> {
265 let mut series: Vec<(time::OffsetDateTime, Energy)> = Vec::new();
266 for slot in &self.slots {
267 let at = slot.quarter_hour.metering_timestamp();
268 match series.last_mut() {
269 Some((last, energy)) if *last == at => *energy += slot.energy,
270 _ => series.push((at, slot.energy)),
271 }
272 }
273 series
274 }
275}
276
277/// Split a session's meter series across quarter hours.
278///
279/// ```
280/// use emob_session::{MeterReading, MeterSeries, ReadingContext, split};
281/// use emob_core::{Direction, Energy, QuarterHour};
282/// use rust_decimal::Decimal;
283/// use std::str::FromStr;
284/// use time::macros::datetime;
285///
286/// let kwh = |s: &str| Energy::from_kwh(Decimal::from_str(s).unwrap()).unwrap();
287/// let series = MeterSeries::new(Direction::Import, vec![
288/// MeterReading::new(datetime!(2026-01-02 10:00 +1), kwh("100.000"), Direction::Import, ReadingContext::TransactionBegin),
289/// MeterReading::new(datetime!(2026-01-02 10:15 +1), kwh("110.000"), Direction::Import, ReadingContext::SampleClock),
290/// MeterReading::new(datetime!(2026-01-02 10:30 +1), kwh("118.000"), Direction::Import, ReadingContext::TransactionEnd),
291/// ])?;
292///
293/// let split = split::into_quarter_hours(&series)?;
294/// assert_eq!(split.slots.len(), 2);
295/// assert_eq!(split.slots[0].energy.to_string(), "10.000 kWh");
296/// assert_eq!(split.slots[1].energy.to_string(), "8.000 kWh");
297/// assert!(split.conserves());
298/// assert!(split.fully_measured());
299/// # Ok::<(), Box<dyn std::error::Error>>(())
300/// ```
301///
302/// # Errors
303///
304/// [`SplitError`] when the series cannot be split — a zero-length session, or
305/// one so long that splitting it is a corruption rather than a charge.
306pub fn into_quarter_hours(series: &MeterSeries) -> Result<SessionSplit, SplitError> {
307 into_periods(series, &[], &[])
308}
309
310/// An interval `[from, to)` in which the session says no energy flowed.
311///
312/// What [`into_periods`] holds the register flat across. The session's own
313/// history is the source — [`crate::Session::idle_intervals`] derives them —
314/// and a meter series never produces one, because a meter cannot tell a taper
315/// from a suspension.
316pub type Idle = (time::OffsetDateTime, time::OffsetDateTime);
317
318/// Split a session's meter series across quarter hours, cutting also at every
319/// instant in `cuts` and interpolating only across the time outside `idle`.
320///
321/// The grid says where the *energy* settles `[A6 §IV.1]`; `cuts` say where
322/// anything else about the session changed. The caller with the session's own
323/// state machine passes its transition instants, and each resulting slice
324/// carries one answer to "was the vehicle charging here" instead of one answer
325/// for a quarter hour that held two.
326///
327/// `idle` is the same history read the other way: the intervals in which the
328/// session says nothing flowed. A boundary that falls inside one takes the
329/// register value at the interval's start, and a gap between two readings
330/// spreads its energy over the seconds that were **not** idle — because a
331/// straight line across a suspension attributes energy to an interval the
332/// operator's own record says moved none, and the CDR builder then refuses a
333/// contradiction the arithmetic invented. See the module documentation.
334///
335/// Cuts outside the series, and cuts that land on a boundary the grid already
336/// produced, cost one comparison and change nothing; so do idle intervals
337/// outside the series. Conservation is unaffected whatever they are: every
338/// interior boundary still appears once positive and once negative in the
339/// telescoping sum.
340///
341/// ```
342/// use emob_session::{MeterReading, MeterSeries, ReadingContext, split};
343/// use emob_core::{Direction, Energy};
344/// use rust_decimal::Decimal;
345/// use time::macros::datetime;
346///
347/// # let kwh = |s: &str| Energy::from_kwh(<Decimal as std::str::FromStr>::from_str(s).unwrap()).unwrap();
348/// let series = MeterSeries::new(Direction::Import, vec![
349/// MeterReading::new(datetime!(2026-01-02 10:00 +1), kwh("100.000"), Direction::Import, ReadingContext::TransactionBegin),
350/// MeterReading::new(datetime!(2026-01-02 10:30 +1), kwh("110.000"), Direction::Import, ReadingContext::TransactionEnd),
351/// ])?;
352///
353/// // The charge finished at 10:20, in the middle of the second quarter hour,
354/// // and the car sat there until 10:30.
355/// let stopped = datetime!(2026-01-02 10:20 +1);
356/// let split = split::into_periods(&series, &[stopped], &[(stopped, datetime!(2026-01-02 10:30 +1))])?;
357/// assert_eq!(split.slots.len(), 3, "10:00–10:15, 10:15–10:20, 10:20–10:30");
358/// assert!(split.slots[2].energy.is_zero(), "nothing flowed while it sat there");
359/// assert!(split.conserves());
360/// // …and the market side still sees two Messperioden.
361/// assert_eq!(split.market_series().len(), 2);
362/// # Ok::<(), Box<dyn std::error::Error>>(())
363/// ```
364///
365/// # Errors
366///
367/// The same as [`into_quarter_hours`].
368pub fn into_periods(
369 series: &MeterSeries,
370 cuts: &[time::OffsetDateTime],
371 idle: &[Idle],
372) -> Result<SessionSplit, SplitError> {
373 let start = series.first().at;
374 let end = series.last().at;
375
376 if end <= start {
377 return Err(SplitError::NoDuration { at: start });
378 }
379
380 // A corruption guard, not a regulatory bound: a "session" spanning more
381 // than a year is a clock fault or a parsing error, and allocating it would
382 // build 35 000 slots before anybody noticed.
383 let span = end - start;
384 if span > time::Duration::days(366) {
385 return Err(SplitError::ImplausiblyLong {
386 days: span.whole_days(),
387 });
388 }
389
390 // The boundaries: the session start, every quarter-hour boundary strictly
391 // inside it, every cut strictly inside it, and the session end. Note that
392 // the first and last are *not* quarter-hour boundaries in general — a
393 // session starting at 10:07 has its first slot run 10:07 to 10:15, and that
394 // slot is still reported under the quarter hour beginning 10:00, because
395 // that is the settlement period the energy belongs to.
396 let mut boundaries: Vec<time::OffsetDateTime> = vec![start];
397 let mut cursor = QuarterHour::containing(start).next();
398 while cursor.start() < end {
399 boundaries.push(cursor.start());
400 cursor = cursor.next();
401 }
402 boundaries.extend(cuts.iter().copied().filter(|&at| at > start && at < end));
403 boundaries.push(end);
404 // A cut that coincides with a grid boundary is the same boundary, and a
405 // duplicate would produce a slice of no duration and no energy.
406 boundaries.sort_unstable();
407 boundaries.dedup();
408
409 // Each boundary's cumulative register value, computed exactly once. This is
410 // what makes the sum telescope.
411 let idle = normalised_idle(idle, start, end);
412 let cumulative = cumulative_along(series, &boundaries, &idle);
413
414 let mut slots = Vec::with_capacity(boundaries.len().saturating_sub(1));
415 for i in 0..boundaries.len() - 1 {
416 let (from, from_prov) = cumulative[i];
417 let (to, to_prov) = cumulative[i + 1];
418 let energy = Energy::from_kwh(to - from).map_err(|_| SplitError::NonMonotonic {
419 at: boundaries[i + 1],
420 })?;
421 slots.push(Slot {
422 quarter_hour: QuarterHour::containing(boundaries[i]),
423 // The window the readings actually cover, which is the boundary
424 // pair this slot's energy was taken between — never the quarter
425 // hour clamped to the session, because the two differ whenever the
426 // session's own window is wider than its meter series.
427 from: boundaries[i],
428 to: boundaries[i + 1],
429 energy,
430 direction: series.direction(),
431 provenance: from_prov.weaker(to_prov),
432 });
433 }
434
435 let total = series
436 .total()
437 .map_err(|_| SplitError::NonMonotonic { at: end })?;
438
439 let split = SessionSplit {
440 slots,
441 total,
442 direction: series.direction(),
443 };
444
445 // The invariant this whole module exists for. If it ever fails, the bug is
446 // here and not in the caller, so it is worth saying so loudly rather than
447 // returning a number nobody can use.
448 debug_assert!(
449 split.conserves(),
450 "the telescoping sum must equal the total exactly"
451 );
452
453 Ok(split)
454}
455
456/// The register's cumulative value at every boundary, and how each was arrived
457/// at.
458///
459/// `boundaries` is ascending, and so are the readings, so the two are walked
460/// **together** rather than the readings being searched once per boundary. A
461/// month-long session sampled every five minutes has thousands of each, and
462/// the nested form is quadratic in a function that runs before anything is
463/// billed.
464fn cumulative_along(
465 series: &MeterSeries,
466 boundaries: &[time::OffsetDateTime],
467 idle: &[Idle],
468) -> Vec<(Decimal, Provenance)> {
469 let readings = series.readings();
470 let last = &readings[readings.len() - 1];
471 // The index of the last reading at or before the current boundary. It only
472 // ever moves forward, which is what makes the whole walk linear.
473 let mut index = 0usize;
474
475 boundaries
476 .iter()
477 .map(|&at| {
478 // Before the first or after the last reading: the endpoints. Both
479 // are measured — they *are* readings.
480 if at <= readings[0].at {
481 return (readings[0].register.kwh(), Provenance::Measured);
482 }
483 if at >= last.at {
484 return (last.register.kwh(), Provenance::Measured);
485 }
486 while index + 1 < readings.len() && readings[index + 1].at <= at {
487 index += 1;
488 }
489 let before = &readings[index];
490 if at == before.at {
491 return (before.register.kwh(), measured_if_useful(before.context));
492 }
493 let after = &readings[index + 1];
494
495 // Linear interpolation: constant power across the gap — across the
496 // part of it the session was charging in. The register is held
497 // flat over an idle interval, so the gap's energy is spread over
498 // the seconds that remain. A gap with no charging time at all in
499 // which the register nonetheless moved is a contradiction between
500 // the meter and the state machine; the line is then drawn across
501 // the whole gap, and the CDR builder reports the disagreement.
502 let (gap, offset) = {
503 let active_gap = charging_seconds(before.at, after.at, idle);
504 if active_gap > 0 {
505 let active_offset = charging_seconds(before.at, at, idle);
506 // No charging time between a reading and this boundary:
507 // the register cannot have moved, so the value is the
508 // reading's — held, not interpolated — from whichever
509 // side the idle stretch touches.
510 if active_offset == 0 {
511 return (
512 before.register.kwh(),
513 Provenance::held_from(measured_if_useful(before.context)),
514 );
515 }
516 if active_offset == active_gap {
517 return (
518 after.register.kwh(),
519 Provenance::held_from(measured_if_useful(after.context)),
520 );
521 }
522 (active_gap, active_offset)
523 } else {
524 (
525 (after.at - before.at).whole_seconds(),
526 (at - before.at).whole_seconds(),
527 )
528 }
529 };
530 if gap <= 0 {
531 return (before.register.kwh(), Provenance::Interpolated);
532 }
533 let delta = after.register.kwh() - before.register.kwh();
534 // The same arithmetic the rating engine places a tariff threshold
535 // with, through the same function: multiply before dividing, and
536 // quote the result at a scale a *sum* of such values can carry, so
537 // the telescoping identity this module rests on holds as written.
538 (
539 apportion(
540 before.register.kwh(),
541 delta,
542 offset.unsigned_abs(),
543 gap.unsigned_abs(),
544 ),
545 Provenance::Interpolated,
546 )
547 })
548 .collect()
549}
550
551/// The idle intervals clipped to the series, sorted, and merged where they
552/// touch or overlap — so [`charging_seconds`] can subtract them without
553/// counting a second twice.
554fn normalised_idle(
555 idle: &[Idle],
556 start: time::OffsetDateTime,
557 end: time::OffsetDateTime,
558) -> Vec<Idle> {
559 let mut clipped: Vec<Idle> = idle
560 .iter()
561 .map(|&(from, to)| (from.max(start), to.min(end)))
562 .filter(|(from, to)| to > from)
563 .collect();
564 clipped.sort_unstable();
565 let mut merged: Vec<Idle> = Vec::with_capacity(clipped.len());
566 for (from, to) in clipped {
567 match merged.last_mut() {
568 Some((_, last_to)) if from <= *last_to => *last_to = (*last_to).max(to),
569 _ => merged.push((from, to)),
570 }
571 }
572 merged
573}
574
575/// The whole seconds of `[from, to)` that lie outside every idle interval.
576///
577/// `idle` is [`normalised_idle`]'s output: disjoint and ascending, so each
578/// interval's overlap with the window is subtracted exactly once.
579fn charging_seconds(from: time::OffsetDateTime, to: time::OffsetDateTime, idle: &[Idle]) -> i64 {
580 let total = (to - from).whole_seconds();
581 let idle_inside: i64 = idle
582 .iter()
583 .map(|&(a, b)| (b.min(to) - a.max(from)).whole_seconds().max(0))
584 .sum();
585 total - idle_inside
586}
587
588/// A reading that lands on a boundary counts as measuring it only when it was
589/// *meant* to.
590///
591/// A `Sample.Periodic` reading that happens to fall on `:15:00` measured the
592/// register, certainly — but the station chose that instant for its own
593/// reasons, and treating the coincidence as a clock-aligned measurement would
594/// report a settlement as authoritative on a day when the phase drifted.
595/// Transaction boundaries count because the session genuinely begins and ends
596/// there.
597const fn measured_if_useful(context: ReadingContext) -> Provenance {
598 if context.is_clock_aligned() || context.is_transaction_boundary() {
599 Provenance::Measured
600 } else {
601 Provenance::Interpolated
602 }
603}
604
605/// Why a session could not be split.
606#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
607#[non_exhaustive]
608pub enum SplitError {
609 /// The first and last readings are at the same instant.
610 #[error("the session has no duration: every reading is at {at}")]
611 NoDuration {
612 /// The instant.
613 at: time::OffsetDateTime,
614 },
615
616 /// The session spans more than a year.
617 #[error("the session spans {days} days, which is a clock fault rather than a charge")]
618 ImplausiblyLong {
619 /// How many days.
620 days: i64,
621 },
622
623 /// A cumulative value decreased.
624 #[error("the cumulative register decreased at {at}")]
625 NonMonotonic {
626 /// Where.
627 at: time::OffsetDateTime,
628 },
629}
630
631#[cfg(test)]
632mod tests {
633 use super::*;
634 use crate::meter::MeterReading;
635 use std::str::FromStr;
636 use time::macros::datetime;
637
638 fn kwh(s: &str) -> Energy {
639 Energy::from_kwh(Decimal::from_str(s).unwrap()).unwrap()
640 }
641
642 fn at(minute: i64) -> time::OffsetDateTime {
643 datetime!(2026-01-02 10:00 +1) + time::Duration::minutes(minute)
644 }
645
646 fn series(points: &[(i64, &str, ReadingContext)]) -> MeterSeries {
647 MeterSeries::new(
648 Direction::Import,
649 points
650 .iter()
651 .map(|&(m, v, c)| MeterReading::new(at(m), kwh(v), Direction::Import, c))
652 .collect(),
653 )
654 .unwrap()
655 }
656
657 #[test]
658 fn a_session_on_the_boundaries_is_fully_measured() {
659 let s = series(&[
660 (0, "100.000", ReadingContext::TransactionBegin),
661 (15, "110.000", ReadingContext::SampleClock),
662 (30, "118.000", ReadingContext::TransactionEnd),
663 ]);
664 let split = into_quarter_hours(&s).unwrap();
665
666 assert_eq!(split.slots.len(), 2);
667 assert_eq!(split.slots[0].energy.to_string(), "10.000 kWh");
668 assert_eq!(split.slots[1].energy.to_string(), "8.000 kWh");
669 assert!(split.fully_measured());
670 assert!(split.conserves());
671 assert!(
672 split.slots.iter().all(Slot::covers_the_whole_quarter_hour),
673 "a session on the boundaries covers every slot it touches"
674 );
675 }
676
677 #[test]
678 fn an_interpolation_that_does_not_terminate_still_conserves() {
679 // The boundary at 10:15 falls 840/1260 of the way through 10:01 →
680 // 10:22, and `7 × 840 / 1260` is 4.666… — a ratio no decimal states.
681 // The value is the workspace's one apportionment, quoted at the scale
682 // a *sum* of such values can carry: without that floor two of them
683 // spend the whole 96-bit mantissa on their fractions and cannot be
684 // added exactly, which is a conservation check failing in the last
685 // place of the assertion that exists to prove there is none.
686 let s = series(&[
687 (1, "0", ReadingContext::TransactionBegin),
688 (22, "7", ReadingContext::TransactionEnd),
689 ]);
690 let split = into_quarter_hours(&s).unwrap();
691
692 assert_eq!(
693 split.slots[0].energy.kwh(),
694 emob_core::apportion(Decimal::ZERO, Decimal::from(7), 840, 1260)
695 );
696 assert_eq!(split.slots[0].energy.kwh().to_string(), "4.666666666667");
697 assert!(split.conserves(), "and the pieces still telescope exactly");
698 assert!(!split.fully_measured());
699 }
700
701 #[test]
702 fn a_session_starting_mid_slot_reports_under_the_slot_it_belongs_to() {
703 // 10:07 → 10:23 touches the quarter hours beginning 10:00 and 10:15.
704 let s = series(&[
705 (7, "100.0", ReadingContext::TransactionBegin),
706 (23, "108.0", ReadingContext::TransactionEnd),
707 ]);
708 let split = into_quarter_hours(&s).unwrap();
709
710 assert_eq!(split.slots.len(), 2);
711 assert_eq!(split.slots[0].quarter_hour.to_string(), "2026-01-02T10:00");
712 assert_eq!(split.slots[1].quarter_hour.to_string(), "2026-01-02T10:15");
713
714 // The settlement slot and the measured window are different instants,
715 // and the slot carries both rather than leaving a consumer to guess.
716 assert_eq!(split.slots[0].from, at(7), "the readings begin at 10:07");
717 assert_eq!(split.slots[0].to, at(15));
718 assert_eq!(split.slots[0].duration(), time::Duration::minutes(8));
719 assert!(!split.slots[0].covers_the_whole_quarter_hour());
720 assert_eq!(split.slots[1].from, at(15));
721 assert_eq!(split.slots[1].to, at(23));
722
723 assert!(split.conserves());
724 // Nothing measured 10:15, so both slots inherit the interpolation.
725 assert!(!split.fully_measured());
726 assert_eq!(split.interpolated().count(), 2);
727 }
728
729 #[test]
730 fn conservation_survives_a_ratio_that_does_not_divide() {
731 // 10:07 → 10:23 is 16 minutes; the boundary at 10:15 is 8/16 of the
732 // way. Fine. Now make it awkward: 10:01 → 10:22, boundary at 10:15 is
733 // 14/21 = 2/3 of the way, and 7 kWh × 2/3 is a repeating decimal.
734 let s = series(&[
735 (1, "0", ReadingContext::TransactionBegin),
736 (22, "7", ReadingContext::TransactionEnd),
737 ]);
738 let split = into_quarter_hours(&s).unwrap();
739
740 assert_eq!(split.slots.len(), 2);
741 assert!(
742 split.conserves(),
743 "slots {:?} must sum to {}",
744 split.slots.iter().map(|s| s.energy).collect::<Vec<_>>(),
745 split.total
746 );
747 assert_eq!(
748 split.slots.iter().map(|s| s.energy).sum::<Energy>(),
749 kwh("7")
750 );
751 }
752
753 #[test]
754 fn a_long_session_conserves_across_many_slots() {
755 // Six hours, readings only at the ends: 24 slots, every interior
756 // boundary interpolated, and the sum still exact.
757 let s = series(&[
758 (0, "0", ReadingContext::TransactionBegin),
759 (360, "123.456", ReadingContext::TransactionEnd),
760 ]);
761 let split = into_quarter_hours(&s).unwrap();
762
763 assert_eq!(split.slots.len(), 24);
764 assert!(split.conserves());
765 assert_eq!(
766 split.slots.iter().map(|s| s.energy).sum::<Energy>(),
767 kwh("123.456")
768 );
769 }
770
771 #[test]
772 fn conservation_holds_over_many_generated_sessions() {
773 // A property test without a property-testing dependency: a spread of
774 // start offsets, durations and totals, each of which produces a
775 // different set of awkward ratios.
776 let mut checked = 0;
777 for start_min in [0_i64, 1, 4, 7, 13, 14] {
778 for duration in [3_i64, 16, 21, 47, 90, 133] {
779 for total in ["0.001", "7", "13.37", "123.456789"] {
780 let s = series(&[
781 (start_min, "0", ReadingContext::TransactionBegin),
782 (start_min + duration, total, ReadingContext::TransactionEnd),
783 ]);
784 let split = into_quarter_hours(&s).unwrap();
785 assert!(
786 split.conserves(),
787 "start={start_min} duration={duration} total={total}"
788 );
789 assert_eq!(
790 split.slots.iter().map(|x| x.energy).sum::<Energy>(),
791 kwh(total)
792 );
793 checked += 1;
794 }
795 }
796 }
797 assert_eq!(checked, 144);
798 }
799
800 #[test]
801 fn the_market_series_labels_each_period_by_its_end() {
802 // `[PTB-A 50.7 §3.1.7.2]`: "der Zeitstempel 00:15:00 [gehört] zur
803 // ersten Messperiode eines Tages". Handing `mako-emob` a series
804 // labelled by the start would shift every slot by a quarter hour — an
805 // error that sums to zero and is wrong for every balance group.
806 let s = series(&[
807 (0, "100.000", ReadingContext::TransactionBegin),
808 (15, "110.000", ReadingContext::SampleClock),
809 (30, "118.000", ReadingContext::TransactionEnd),
810 ]);
811 let split = into_quarter_hours(&s).unwrap();
812
813 assert_eq!(
814 split.market_series(),
815 vec![(at(15), kwh("10.000")), (at(30), kwh("8.000"))],
816 "the first period ends at 10:15 and is labelled 10:15"
817 );
818 assert_eq!(
819 split.slots[0].quarter_hour.start(),
820 at(0),
821 "…and starts at 10:00"
822 );
823
824 // The energy is the same energy either way round.
825 assert_eq!(
826 split
827 .market_series()
828 .iter()
829 .map(|(_, e)| *e)
830 .sum::<Energy>(),
831 split.total
832 );
833 }
834
835 #[test]
836 fn a_periodic_sample_on_a_boundary_is_still_interpolated() {
837 // The station chose that instant for its own reasons. Treating the
838 // coincidence as a clock-aligned measurement would report a settlement
839 // as authoritative on a day the phase drifted.
840 let s = series(&[
841 (0, "100", ReadingContext::TransactionBegin),
842 (15, "110", ReadingContext::SamplePeriodic),
843 (30, "118", ReadingContext::TransactionEnd),
844 ]);
845 let split = into_quarter_hours(&s).unwrap();
846 assert!(!split.fully_measured());
847
848 // …and with the same reading marked Sample.Clock, it is.
849 let s = series(&[
850 (0, "100", ReadingContext::TransactionBegin),
851 (15, "110", ReadingContext::SampleClock),
852 (30, "118", ReadingContext::TransactionEnd),
853 ]);
854 assert!(into_quarter_hours(&s).unwrap().fully_measured());
855 }
856
857 #[test]
858 fn a_session_inside_one_quarter_hour_is_one_slot() {
859 let s = series(&[
860 (1, "100", ReadingContext::TransactionBegin),
861 (9, "104", ReadingContext::TransactionEnd),
862 ]);
863 let split = into_quarter_hours(&s).unwrap();
864 assert_eq!(split.slots.len(), 1);
865 assert_eq!(split.slots[0].energy.to_string(), "4 kWh");
866 assert!(split.conserves());
867 }
868
869 #[test]
870 fn a_session_with_no_duration_is_refused() {
871 let s = MeterSeries::new(
872 Direction::Import,
873 vec![
874 MeterReading::new(
875 at(0),
876 kwh("100"),
877 Direction::Import,
878 ReadingContext::TransactionBegin,
879 ),
880 MeterReading::new(
881 at(0),
882 kwh("100"),
883 Direction::Import,
884 ReadingContext::TransactionEnd,
885 ),
886 ],
887 )
888 .unwrap();
889 assert!(matches!(
890 into_quarter_hours(&s),
891 Err(SplitError::NoDuration { .. })
892 ));
893 }
894
895 #[test]
896 fn an_implausibly_long_session_is_refused_before_it_allocates() {
897 let s = MeterSeries::new(
898 Direction::Import,
899 vec![
900 MeterReading::new(
901 at(0),
902 kwh("0"),
903 Direction::Import,
904 ReadingContext::TransactionBegin,
905 ),
906 MeterReading::new(
907 at(0) + time::Duration::days(400),
908 kwh("1"),
909 Direction::Import,
910 ReadingContext::TransactionEnd,
911 ),
912 ],
913 )
914 .unwrap();
915 assert!(matches!(
916 into_quarter_hours(&s),
917 Err(SplitError::ImplausiblyLong { .. })
918 ));
919 }
920
921 #[test]
922 fn quarter_hours_align_on_the_utc_grid() {
923 for (minute, expected) in [
924 (0, 0),
925 (7, 0),
926 (14, 0),
927 (15, 15),
928 (29, 15),
929 (30, 30),
930 (59, 45),
931 ] {
932 let q = QuarterHour::containing(at(minute));
933 assert_eq!(q.start().minute(), expected, "minute {minute}");
934 }
935 }
936
937 #[test]
938 fn a_clock_change_needs_no_special_case() {
939 // Europe/Berlin springs forward at 02:00 local on 2026-03-29. The slots
940 // either side are fifteen minutes of real time each; the local clock
941 // jumping is not the split's business.
942 let before = datetime!(2026-03-29 01:45:00 +1);
943 let after = before + time::Duration::minutes(30);
944 let s = MeterSeries::new(
945 Direction::Import,
946 vec![
947 MeterReading::new(
948 before,
949 kwh("0"),
950 Direction::Import,
951 ReadingContext::TransactionBegin,
952 ),
953 MeterReading::new(
954 after,
955 kwh("6"),
956 Direction::Import,
957 ReadingContext::TransactionEnd,
958 ),
959 ],
960 )
961 .unwrap();
962 let split = into_quarter_hours(&s).unwrap();
963 assert_eq!(split.slots.len(), 2, "two quarter hours of real time");
964 assert!(split.conserves());
965 }
966
967 #[test]
968 fn a_cut_divides_a_quarter_hour_without_moving_any_energy() {
969 // The charge finishes at 10:20, in the middle of the second quarter
970 // hour. Split on the grid alone, that whole quarter hour carries one
971 // answer to "was the vehicle charging"; cut, it carries two.
972 let s = series(&[
973 (0, "100.000", ReadingContext::TransactionBegin),
974 (20, "110.000", ReadingContext::InterruptionBegin),
975 (45, "110.000", ReadingContext::TransactionEnd),
976 ]);
977 let split = into_periods(&s, &[at(20)], &[]).unwrap();
978
979 let windows: Vec<(i64, i64)> = split
980 .slots
981 .iter()
982 .map(|slot| {
983 (
984 (slot.from - at(0)).whole_minutes(),
985 (slot.to - at(0)).whole_minutes(),
986 )
987 })
988 .collect();
989 assert_eq!(windows, vec![(0, 15), (15, 20), (20, 30), (30, 45)]);
990 assert_eq!(split.slots[1].quarter_hour, split.slots[2].quarter_hour);
991 assert!(split.conserves());
992 assert_eq!(
993 split.slots.iter().map(|x| x.energy).sum::<Energy>(),
994 kwh("10.000")
995 );
996 }
997
998 #[test]
999 fn the_market_series_sums_the_slices_of_one_messperiode() {
1000 // A cut divides a slot for *pricing*; the market side settles a whole
1001 // Messperiode against one balance group `[A6 §IV.1]`, so two entries
1002 // for one timestamp would be a file no allocation can read.
1003 let s = series(&[
1004 (0, "100.000", ReadingContext::TransactionBegin),
1005 (30, "110.000", ReadingContext::TransactionEnd),
1006 ]);
1007 let split = into_periods(&s, &[at(20), at(25)], &[]).unwrap();
1008 assert_eq!(split.slots.len(), 4, "10:00, 10:15, 10:20, 10:25");
1009
1010 let market = split.market_series();
1011 assert_eq!(
1012 market,
1013 vec![(at(15), kwh("5.000")), (at(30), kwh("5.000"))],
1014 "two quarter hours, whatever the pricing cuts did inside them"
1015 );
1016 assert_eq!(market.iter().map(|(_, e)| *e).sum::<Energy>(), split.total);
1017 }
1018
1019 #[test]
1020 fn a_cut_outside_the_series_or_on_a_boundary_changes_nothing() {
1021 let s = series(&[
1022 (0, "100.000", ReadingContext::TransactionBegin),
1023 (30, "118.000", ReadingContext::TransactionEnd),
1024 ]);
1025 let plain = into_quarter_hours(&s).unwrap();
1026 // Before the start, after the end, on the start, on the end, and on a
1027 // grid boundary the split already produced.
1028 let cut = into_periods(&s, &[at(-5), at(0), at(15), at(30), at(99)], &[]).unwrap();
1029 assert_eq!(cut, plain);
1030 // …and so does an idle interval that lies outside the series.
1031 let idle = into_periods(&s, &[], &[(at(-30), at(-5)), (at(30), at(60))]).unwrap();
1032 assert_eq!(idle, plain);
1033 }
1034
1035 #[test]
1036 fn energy_is_interpolated_over_charging_time_only() {
1037 // The ordinary OCPP 2.0.1 shape: the transaction opens `EVConnected`
1038 // with a `Transaction.Begin` reading, starts charging thirty seconds
1039 // later, and sends its next meter value at the quarter hour. Drawn as
1040 // one straight line, the first thirty seconds get 1/30 of the gap's
1041 // energy — attributed to an interval the session says moved none.
1042 let begin = at(0);
1043 let charging_from = at(0) + time::Duration::seconds(30);
1044 let s = series(&[
1045 (0, "100.000", ReadingContext::TransactionBegin),
1046 (15, "105.000", ReadingContext::SampleClock),
1047 ]);
1048
1049 let naive = into_periods(&s, &[charging_from], &[]).unwrap();
1050 assert!(
1051 !naive.slots[0].energy.is_zero(),
1052 "a straight line invents energy in the suspended interval: {}",
1053 naive.slots[0].energy
1054 );
1055
1056 let split = into_periods(&s, &[charging_from], &[(begin, charging_from)]).unwrap();
1057 assert_eq!(split.slots.len(), 2);
1058 assert!(
1059 split.slots[0].energy.is_zero(),
1060 "the register is held flat while nothing flows"
1061 );
1062 assert_eq!(split.slots[1].energy, kwh("5.000"));
1063 assert!(split.conserves());
1064 // …and both numbers are exact rather than assumed: the boundary at
1065 // 10:00:30 is the opening reading's value, held.
1066 assert_eq!(split.slots[0].provenance, Provenance::Held);
1067 assert_eq!(split.slots[1].provenance, Provenance::Held);
1068 assert!(split.fully_measured(), "nothing was interpolated");
1069 assert_eq!(split.interpolated().count(), 0);
1070 }
1071
1072 #[test]
1073 fn a_held_value_is_only_as_good_as_the_reading_it_is_held_from() {
1074 // Held from a `Sample.Periodic` reading — a coincidence rather than a
1075 // measurement — is still an assumption.
1076 let charging_from = at(15) + time::Duration::seconds(30);
1077 let s = series(&[
1078 (0, "100.000", ReadingContext::TransactionBegin),
1079 (15, "105.000", ReadingContext::SamplePeriodic),
1080 (30, "110.000", ReadingContext::TransactionEnd),
1081 ]);
1082 let split = into_periods(&s, &[charging_from], &[(at(15), charging_from)]).unwrap();
1083 assert_eq!(split.slots[1].energy, Energy::ZERO);
1084 assert_eq!(split.slots[1].provenance, Provenance::Interpolated);
1085 assert!(!split.fully_measured());
1086
1087 // Provenance orders as measured > held > interpolated.
1088 assert_eq!(
1089 Provenance::Measured.weaker(Provenance::Held),
1090 Provenance::Held
1091 );
1092 assert_eq!(Provenance::Held.weaker(Provenance::Held), Provenance::Held);
1093 assert_eq!(
1094 Provenance::Held.weaker(Provenance::Interpolated),
1095 Provenance::Interpolated
1096 );
1097 assert!(Provenance::Held.is_exact());
1098 assert!(!Provenance::Interpolated.is_exact());
1099 }
1100
1101 #[test]
1102 fn an_idle_interval_in_the_middle_of_a_gap_moves_energy_to_the_charging_sides() {
1103 // Readings at 10:00 and 10:30, 12 kWh between them; suspended from
1104 // 10:10 to 10:20. Twenty charging minutes carry the twelve
1105 // kilowatt-hours: six before the pause, none during it — on either
1106 // side of the 10:15 grid boundary — and six after.
1107 let s = series(&[
1108 (0, "0", ReadingContext::TransactionBegin),
1109 (30, "12", ReadingContext::TransactionEnd),
1110 ]);
1111 let split = into_periods(&s, &[at(10), at(20)], &[(at(10), at(20))]).unwrap();
1112 let energies: Vec<String> = split
1113 .slots
1114 .iter()
1115 .map(|slot| slot.energy.kwh().normalize().to_string())
1116 .collect();
1117 assert_eq!(energies, ["6", "0", "0", "6"]);
1118 assert!(split.conserves());
1119 }
1120
1121 #[test]
1122 fn a_register_that_moves_across_a_wholly_idle_gap_is_left_for_the_builder() {
1123 // The session says nothing flowed between the two readings and the
1124 // meter says 5 kWh did. There is no charging time to spread it over,
1125 // so the line is drawn across the whole gap — the contradiction is
1126 // real, and `emob-cdr` is where it is reported.
1127 let s = series(&[
1128 (0, "100", ReadingContext::TransactionBegin),
1129 (30, "105", ReadingContext::TransactionEnd),
1130 ]);
1131 let split = into_periods(&s, &[], &[(at(0), at(30))]).unwrap();
1132 assert_eq!(split.slots.len(), 2);
1133 assert_eq!(split.slots[0].energy.kwh().normalize().to_string(), "2.5");
1134 assert!(split.conserves());
1135 }
1136
1137 #[test]
1138 fn overlapping_and_touching_idle_intervals_count_each_second_once() {
1139 let s = series(&[
1140 (0, "0", ReadingContext::TransactionBegin),
1141 (30, "12", ReadingContext::TransactionEnd),
1142 ]);
1143 // 10:10–10:20 stated three times over, in pieces that overlap and touch.
1144 let messy = [(at(10), at(16)), (at(14), at(18)), (at(18), at(20))];
1145 let clean = [(at(10), at(20))];
1146 assert_eq!(
1147 into_periods(&s, &[at(10), at(20)], &messy).unwrap(),
1148 into_periods(&s, &[at(10), at(20)], &clean).unwrap()
1149 );
1150 }
1151
1152 #[test]
1153 fn provenance_takes_the_weaker_of_two_boundaries() {
1154 assert_eq!(
1155 Provenance::Measured.weaker(Provenance::Measured),
1156 Provenance::Measured
1157 );
1158 assert_eq!(
1159 Provenance::Measured.weaker(Provenance::Interpolated),
1160 Provenance::Interpolated
1161 );
1162 assert_eq!(
1163 Provenance::Interpolated.weaker(Provenance::Measured),
1164 Provenance::Interpolated
1165 );
1166 }
1167
1168 #[test]
1169 fn export_sessions_split_the_same_way_and_stay_export() {
1170 let s = MeterSeries::new(
1171 Direction::Export,
1172 vec![
1173 MeterReading::new(
1174 at(0),
1175 kwh("0"),
1176 Direction::Export,
1177 ReadingContext::TransactionBegin,
1178 ),
1179 MeterReading::new(
1180 at(30),
1181 kwh("5"),
1182 Direction::Export,
1183 ReadingContext::TransactionEnd,
1184 ),
1185 ],
1186 )
1187 .unwrap();
1188 let split = into_quarter_hours(&s).unwrap();
1189 assert_eq!(split.direction, Direction::Export);
1190 assert!(split.slots.iter().all(|x| x.direction == Direction::Export));
1191 assert!(split.conserves());
1192 }
1193}