SAFETY-81 review: 10 s hold, ERROR line per episode, more scenarios
checks / unit (pull_request) Successful in 20m31s
infra-pin / fresh (pull_request) Successful in 2s

- The alarm must hold for peakguard.ALARM_HOLD_S (10 s) on the projection's
  clock. A load that tops cap + battery for ~5 s every 30 s alarmed at every
  quarter start while the quarter landed under the aim (sine4500_fast).
- A cycle with no battery reading leaves the hold alone.
- Notified once per quarter, but the ERROR line is written per episode.
- New sim scenarios (sine4500_fast, twice7000, step6500_gap) with 5a4cdc2
  digests; control still byte-identical. Unit checks for export and the
  hold across a missing reading. test_peakguard's saturated fixture moves
  the hold start back instead of waiting it out.
- DECISIONS and DOCS updated: costs of the hold, tolerance reasoning, the
  double count in control left to a follow-up.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-09-29 20:58:37 +02:00
co-authored by Claude Opus 5.5
parent 6eb67c0f9c
commit f967073cfe
7 changed files with 170 additions and 47 deletions
+36 -10
View File
@@ -18,6 +18,7 @@ changed and what did not.
import asyncio
import hashlib
import logging
import os
import random
import sys
@@ -75,8 +76,9 @@ def ramp(before, after, at, secs):
class _Plant:
"""One battery that reaches its command RESPONSE_S after the write."""
def __init__(self, load, rating, soc):
def __init__(self, load, rating, soc, batt_gap=()):
self.load, self.rating, self.soc = load, rating, soc
self.batt_gap = batt_gap # (from, to): the battery reading is lost
self.t = 0.0
self.hist = [(-1e9, 0.0)] # (time the command takes effect, W)
self.notes = []
@@ -106,6 +108,8 @@ class _Plant:
if e.startswith("sensor.soc"):
return self.soc
if e.startswith("sensor.batt"):
if self.batt_gap and self.batt_gap[0] <= self.t < self.batt_gap[1]:
return None
return self.batt(self.t)
return None
@@ -115,10 +119,11 @@ class _Plant:
def run(load, *, margin=50, dur=2700.0, rating=2000.0, cap=3500.0,
late_at=(), soc=60.0):
"""Alarm times (s from the start of the first quarter) and a digest of
every cycle's target and written command. A sample is also late at each
`t % 900` in `late_at`."""
late_at=(), soc=60.0, batt_gap=()):
"""Alarm times (s from the start of the first quarter), a digest of every
cycle's target and written command, the Controller, the rows, and the
times of the ERROR log line. A sample is also late at each `t % 900` in
`late_at`."""
opts = rig._options(1, {
"meter_source": "ha_signed", "p1_net_entity": "sensor.net",
"meter_phases": 1, "peak_cap_w": cap, "peak_margin_w": margin,
@@ -129,7 +134,7 @@ def run(load, *, margin=50, dur=2700.0, rating=2000.0, cap=3500.0,
db = os.path.join(tempfile.mkdtemp(prefix="s81-"), "tariff.db")
async def go():
plant = _Plant(load, rating, soc)
plant = _Plant(load, rating, soc, batt_gap)
c = Controller(opts, plant, store, rig._Pub(), stop=asyncio.Event(),
peak_db_path=db)
for i in c.inverters:
@@ -143,6 +148,14 @@ def run(load, *, margin=50, dur=2700.0, rating=2000.0, cap=3500.0,
return rig.BASE + timedelta(seconds=clock[0])
m.datetime = _DT
rows, late = [], random.Random(8100)
errors = []
class _Err(logging.Handler):
def emit(self, r):
if "battery alone cannot keep" in r.getMessage():
errors.append(plant.t)
h = _Err()
logging.getLogger("goodwe").addHandler(h)
try:
t = 0.0
while t < dur:
@@ -161,10 +174,12 @@ def run(load, *, margin=50, dur=2700.0, rating=2000.0, cap=3500.0,
t += TICK
finally:
m.datetime = real_dt
return plant, c, rows
plant, c, rows = asyncio.run(go())
logging.getLogger("goodwe").removeHandler(h)
return plant, c, rows, errors
plant, c, rows, errors = asyncio.run(go())
alarms = [t for t, nid in plant.notes if nid == ALARM]
return alarms, hashlib.sha256(repr(rows).encode()).hexdigest(), c, rows
return (alarms, hashlib.sha256(repr(rows).encode()).hexdigest(), c, rows,
errors)
# Three quarters each (2700 s); a new quarter starts at 900 s and 1800 s.
@@ -194,10 +209,21 @@ SCENARIOS = {
# The pack under its peak reserve (20 %), and a load far over cap +
# battery: that is "Battery stopped limiting the peak", not this alarm.
"step7500_reserve": dict(load=step(4500.0, 7500.0, 1200.0), soc=15.0),
# Review: a load swinging 4500 +/- 1200 W every 30 s (a hob or heater
# cycling). It tops cap + battery for about 5 s a swing, and the quarter
# still lands under the aim.
"sine4500_fast": dict(load=sine(4500.0, 1200.0, period=30.0, noise=200.0)),
# Review: two real overloads in one quarter, 1000-1100 s and 1500-1700 s.
"twice7000": dict(load=lambda t: 7000.0 if (1000 <= t < 1100
or 1500 <= t < 1700)
else 4500.0),
# Review: step6500, and the battery reading is lost 1203-1215 s.
"step6500_gap": dict(load=step(4500.0, 6500.0, 1200.0),
batt_gap=(1203.0, 1215.0)),
}
if __name__ == "__main__":
for k, v in SCENARIOS.items():
a, d, _, _ = run(**v)
a, d, _, _, _ = run(**v)
print(f"{k:16s} alarms at {a} digest {d}")