Skip to content
SlateGitOrgPublic

About

EV-charging kWh windows whose output, operator state and input offsets commit in one transaction, crashed at every kill point to prove no meter reading is billed twice or lost.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

2 Commits

Folders and files

Repository files navigation

killpoint

CI

killpoint

killpoint bills EV-charging energy from a stream of meter readings and proves it never bills a reading twice or loses one. Readings go into a SQLite-backed partitioned log, consumer-group members aggregate them into 15-minute event-time windows per charging session, and each window, the readings inside it, the operator state and the input offsets are committed in a single SQLite transaction. A fault injector crashes the processor at six named kill points, dozens of times per run, and a Polars batch oracle checks that the billing table afterwards is identical to a crash-free computation. The same crash plan is then replayed against at-least-once and at-most-once variants of the processor to show the over- and under-billing that atomicity prevents. All data is synthetic.

The problem

An operator bills drivers and roaming partners from meter readings streamed by its chargers. Chargers resend readings after connectivity drops, an offline site flushes a buffer late, and the stream processor restarts on every deploy and crash. At-least-once processing double counts energy after a restart. At-most-once loses it. Either becomes a billing dispute, and "it only happens on restarts" is not an answer a finance team accepts.

The pipeline here has to get four things right at once: readings that arrive twice (inside the dedup horizon and long after it), readings that arrive too late to change a closed window, implausible spikes, and a partition that goes quiet and must not stall every window. Then it has to keep getting them right when the process dies at the worst possible moment.

How it works

flowchart LR
    CH["Charger readings<br/>resends, out of order,<br/>late buffer, spikes"] --> PROD["Producers<br/>partition = crc32(charger) % 4"]
    PROD --> LOG[("log.db<br/>partitioned SQLite log<br/>records, group_offsets")]
    LOG --> POLL["Group members poll<br/>range assignment, rebalance()"]
    POLL --> OP["Windowed operator<br/>validate, dedup,<br/>watermarks, idle detection,<br/>15-min tumbling windows"]
    OP --> TX["Sink transaction in billing.db<br/>windows + billed readings +<br/>operator state + input offsets"]
    TX --> ADV["Advisory group-offset commit"]
    ADV --> LOG
    FI["Fault injector<br/>seeded FaultPlan"] -. "Crash at each kill point" .-> POLL
    FI -.-> OP
    FI -.-> TX
    FI -.-> ADV
    LOG --> ORA["Polars batch oracle<br/>same rules, replayed<br/>member watermark"]
    TX --> CMP{"window_energy<br/>equals oracle?"}
    ORA --> CMP
Loading

The stream is replayed on a simulated clock: tick N polls at clock_start + N * 30 s and sees only records whose arrival_ts has passed. That makes a quiet partition show up as polls that return nothing, which is what idle detection counts, and it makes every run deterministic.

The operator, in one poll:

  1. Each member polls its partitions (range assignment, an equal share of the poll size per partition).
  2. A reading whose energy exceeds the charger's rated power times the interval goes to rejected_readings.
  3. A reading whose window is already finalised takes the late path. If the durable billed_readings index knows it, it is a duplicate. Otherwise it goes to late_readings for the billing-correction process.
  4. Any other reading is deduplicated against an in-memory set of (charger_id, reading_seq) and added to its (session_id, window_start) window. The set only holds readings of open windows, so it is bounded.
  5. The partition watermark is the newest event time seen minus 2 minutes. The member watermark is the minimum over its non-idle partitions (idle: no records in the last 6 polls) and never decreases. A window is finalised when the watermark reaches window_end + 10 minutes.
  6. One transaction in billing.db writes the finalised windows, the readings in them, rejected and late readings, counters, every owned partition's state snapshot and sink_offsets. Only then is the advisory group offset committed.

On start, a member restores offsets and state from billing.db, never from the log's group offsets.

Kill points: after_poll, after_state_update, mid_sink_txn (inside the open transaction, after the windows are written and before the state and offsets are), before_sink_commit (inside the open transaction, everything written, not yet committed), after_sink_commit (before the advisory offset commit) and after_rebalance. The harness restarts a fresh processor after every crash and continues until the log is drained.

Quick start

python -m venv .venv
. .venv/bin/activate
pip install -e ".[dev]"

killpoint generate --seed 7 --out data      # chargers.csv, readings.csv, truth.json
killpoint produce --data data --work work   # fill the partitioned log work/log.db
killpoint run --data data --work work       # crash-free run, compared with the oracle
killpoint torture                           # 8 crashes at each of the 6 kill points, exactly-once
killpoint compare-modes                     # same crash plan, three delivery modes
killpoint report                            # print the saved results again

generate --small produces the test-size dataset (40 chargers, 90 minutes). run accepts --mode, --rebalance-every, --no-idle-detection and --crashes-per-point. A full-size torture takes about 13 seconds and compare-modes about 22.

Example output

All numbers below come from killpoint generate --seed 7, which writes 38,784 log records: 37,291 distinct readings from 120 chargers at 15 sites over 6 hours, 1,493 duplicate resends and 12 energy spikes, with one site offline for 40 minutes and one partition silent for about 20.

$ killpoint run
exactly_once: 4,150,772 Wh billed, oracle 4,150,772 Wh, 0 crashes, 1 instances
counters: {"consumed": 38784, "dup_durable": 20, "dup_memory": 1473, "late": 205, "rejected": 12}
window_energy equals the oracle

dup_memory + dup_durable is 1,493, the generator's duplicate count. The 20 durable catches are resends of readings delivered just before the offline site dropped, arriving after their windows were finalised. late is the 205 buffered readings beyond the lateness bound, and rejected is the 12 spikes.

$ killpoint torture
crashes by kill point (exactly_once torture run)
┏━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━━━━━━━┓
┃ kill point         ┃ crashes ┃ times reached ┃
┡━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━━━━━━━┩
│ after_poll         │       8 │         1,438 │
│ after_state_update │       8 │         1,440 │
│ mid_sink_txn       │       8 │         1,440 │
│ before_sink_commit │       8 │         1,440 │
│ after_sink_commit  │       8 │         1,440 │
│ after_rebalance    │       8 │            35 │
│ total              │      48 │               │
└────────────────────┴─────────┴───────────────┘
48 crashes, 49 processor instances started
window_energy vs oracle: identical (4,150,772 Wh billed, 4,150,772 Wh oracle, 1,816 windows)
billing.db vs the crash-free run: identical
dedup state: max observed 3,204, bound at that poll 3,251 (largest bound 3,423); 1,462 polls checked, within
the bound at every poll

The dedup bound is the number of distinct readings consumed so far whose event time is above watermark - lateness - window length, recomputed from the log at every poll. The set stays under it while the stream as a whole holds 37,291 readings.

$ killpoint compare-modes
           compare-modes: same crash plan, three delivery modes
┏━━━━━━━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━┓
┃ mode          ┃ crashes ┃ restarts ┃ Wh billed ┃ oracle Wh ┃ difference ┃
┡━━━━━━━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━━┩
│ exactly_once  │      48 │       49 │ 4,150,772 │ 4,150,772 │         +0 │
│ at_least_once │      48 │       49 │ 4,203,362 │ 4,150,772 │    +52,590 │
│ at_most_once  │      48 │       49 │   282,957 │ 4,150,772 │ -3,867,815 │
└───────────────┴─────────┴──────────┴───────────┴───────────┴────────────┘
at_least_once re-billed 489 readings (52,590 Wh) replayed after 48 crashes
at_most_once lost 34,654 readings (3,867,815 Wh) that were polled or held in memory at a crash

"restarts" is the number of processor instances started, one more than the crashes. The at-most-once loss is large because each crash discards every open window in memory (about 25 minutes of readings across all partitions) and, in this mode, nothing brings them back. The reconciliation behind these figures attributes only the skipped side of at-most-once to the crash log (every missing reading was polled-but-unapplied or in memory at a crash); the re-billed readings it also reports are ones its restarted state no longer remembered as late or duplicate, and are not traced to a log range.

Design decisions

Atomic commit instead of retries or idempotent writes. Windows, readings, operator state and offsets share one SQLite transaction, so a restart cannot observe output without the matching state or state without the matching offsets. The cost is that every poll rewrites the owned partitions' state snapshots as JSON (the open windows and dedup set, up to about 150 KB per poll at full size), and that the sink and the state must live in the same database. A design that wrote to an external system would need transactions there too, or idempotent keys.

Bounded dedup plus a durable index. The in-memory set is evicted when a window finalises, which keeps memory proportional to the lateness horizon and the snapshot small. A duplicate that outlives it lands on the late path and is caught by the billed_readings index. The index grows with the billing history, not with the horizon, so on a long-lived deployment it needs partitioning or expiry, which this project does not do.

Member watermark, replayed by the oracle without sharing code. Finalisation uses the minimum over a member's non-idle partitions, floored by the value stored with each partition snapshot so rebalances and idle returns cannot move it back, and a reading is judged against the floor at the start of its poll. A per-partition running maximum, the obvious oracle, differs from that in three ways: it never excludes idle partitions, it uses a per-record running maximum instead of the batch-start floor, and it takes each partition alone instead of the minimum over a member's own partitions. So the oracle replays the group on the same simulated clock (poll quotas, range assignment, scheduled rebalances, idle exclusion, the floor carried by each partition) in its own code, and classifies each reading against that floor. The two implementations agree on the generated data for single-member, rebalancing, idle-off and small-poll configurations, and on hand-built logs where a partition idles across the lateness boundary, a busy partition lags behind its member's others, and a straggler shares a poll with the record that moves the watermark; the per-partition oracle is pinned to its divergence on each of those. The cost is a second copy of the watermark logic that has to be kept in step with the operator.

Idle detection counts polls on a simulated clock. A partition is idle after 6 empty polls (3 minutes of clock time), which is deterministic and testable at the poll index where each window is emitted. The price is that wall-clock idleness, such as a stalled consumer, is not modelled, and the 6-poll threshold trades slower recovery from a quiet partition against a higher chance of excluding a partition that is only briefly quiet.

Comparison modes share the operator and differ only in what is durable. At-least-once appends windows in their own transaction and commits offsets afterwards, held back to the oldest reading still in an open window, with state rebuilt by replay. At-most-once commits offsets at poll time and keeps state in memory. This isolates the effect of the commit protocol, but it also makes at-most-once look worse than a production system that checkpoints state would. The reconciliation splits each difference into reprocessed and skipped energy by reading and checks them against the log ranges the harness recorded at each crash.

A crash is an exception plus a rollback. Crash is raised at a kill point, the open transaction is rolled back and a fresh instance is built from the files. That exercises every ordering of commit and offset write, including between the writes inside the transaction (mid_sink_txn), but relies on SQLite's own atomic commit. Power-loss durability (a torn write or a lost disk flush) is deliberately not modelled; databases use SQLite's default synchronous setting.

Testing

pytest -q

99 tests run offline in about a minute. They cover log semantics (contiguous offsets, offset-ordered polls, committed-offset resume, a mid-run rebalance consuming every offset once), the operator against hand-computed fixtures, the sink's transactions, the seeded fault plan, the generator's recorded truth, and end to end behaviour on the test-size data: a crash-free run equal to the oracle with and without rebalances, and the member-replay oracle checked against the processor on generated and hand-built logs, five torture seeds of about 48 crashes each with every kill point hit at least 6 times and the table equal to the oracle, a billing dump that is byte-identical across runs with the same seed and plan (and across different plans), at-least-once over-billing and at-most-once under-billing explained reading by reading, exactly the generator's duplicates, late readings and spikes, idle detection on and off checked at the poll index of each emitted window, and the dedup bound at every poll.

Project layout

src/killpoint/
  config.py       constants, SynthConfig, RunConfig
  synth.py        seeded generator and truth.json
  log.py          partitioned log, consumer group, range assignment
  operator.py     windows, validation, dedup, watermarks, idle detection
  sink.py         billing.db schema, transactions, deterministic dump
  faults.py       Crash, kill points, seeded FaultPlan
  runner.py       cluster of members, delivery modes, crash and restart harness
  oracle.py       Polars batch oracle with an independent member-watermark replay
  compare.py      table equality, reconciliation, dedup bound
  experiments.py  torture and compare-modes experiments
  report.py       rich tables for the saved results
  cli.py          Typer CLI
tests/            99 tests

License

MIT. See LICENSE.

About

EV-charging kWh windows whose output, operator state and input offsets commit in one transaction, crashed at every kill point to prove no meter reading is billed twice or lost.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages