EV-04 round 2: race-free another-writer check, refused phase select, undo before the select, clamped restore, energy-corroborated car figure
checks / unit (pull_request) Successful in 21m14s
infra-pin / fresh (pull_request) Successful in 1s

M1 the writer ignores a reading taken before its latest confirmed write.
M2 a refused phase select gives the current back and stops after 3 tries (amber row).
M3 Off, shadow mode or a control/safety stop before the select undoes the change.
M4 the restore on shutdown (and the undo) is clamped.
M5 the car's power reaches the alarm path only while the charger's energy meter agrees with it.
L1 fuzz other-writer branch reachable and shown to run. L2 one wording. L3 Batteries-help-off text.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
glenn schrooyen
2026-11-16 06:51:15 +01:00
co-authored by Claude
parent 0c92239a63
commit 661a3b009a
11 changed files with 493 additions and 68 deletions
+306 -32
View File
@@ -186,6 +186,18 @@ class World:
await self.c.cycle()
await self.c.car_settle()
async def step_race(self, n=1, dt=1.0):
"""The production order: the writer task can finish AFTER the cycle's
read and BEFORE that cycle's kick (read -> task settles -> cycle), so
the step that follows sees a reading older than the write."""
for _ in range(n):
self.sim.tick(dt)
self.t += dt
CLOCK[0] = self.t
await self.c.read_inputs(now_mono=self.t)
await self.c.car_settle()
await self.c.cycle()
async def act(self, what, value):
return await self.c.handle_action(what, value=value)
@@ -682,6 +694,134 @@ async def phases_in_off():
check("in Off a phase change writes nothing either",
run(phases_in_off()).writes() == [])
print("\n5b. ROUND 2: THE SEQUENCE UNDER A RACING WRITER, A REFUSED SELECT, "
"A MODE CHANGE, THE CLAMP")
async def m1_race(lag):
# the writer task finishes between a cycle's read and that cycle's kick
w = World(setpoint=10, phases=1)
w.sim.lag_s = lag
await w.step(8)
await w.act("car_mode", "manual")
await w.act("car_current", 10)
await w.step(10)
n0 = len(w.writes())
await w.act("car_phases", 3)
await w.step_race(60)
seq = [(x[1], x[2]) for x in w.writes()[n0:]]
await w.step_race(300)
return w, seq
for _lag in (0.0, 3.0):
w_m1, seq_m1 = run(m1_race(_lag))
check(f"M1 (read -> writer settles -> cycle, read-back lag {_lag:.0f} s): "
"the phases are selected and the car gets its 10 A back, with no "
f"false 'something else changed the charger' ({seq_m1})",
seq_m1 == [("current", 0.0), ("phases", 3), ("current", 10.0)]
and w_m1.sim.readback_a == 10 and w_m1.sim.phases_allowed == 3
and not w_m1.c.car_writer.hold and "charger_other" not in w_m1.rows()
and w_m1.sim.power_w > 6000)
async def m2_refused():
w = World(setpoint=10, phases=1)
await w.step(8)
await w.act("car_mode", "manual")
await w.act("car_current", 10)
await w.step(5)
sim = w.sim
def deaf(n): # Home Assistant says yes, nothing moves
sim.log.append((sim.t, "phases", n, sim.power_w, sim.setpoint_a))
return True
sim.request_phases = deaf
n0 = len(w.writes())
await w.act("car_phases", 3)
await w.step(3700)
mid = [x for x in w.writes()[n0:]]
ph = [x for x in mid if x[1] == "phases"]
zeros = [x for x in mid if x[1] == "current" and x[2] == 0.0]
out = dict(ph=len(ph), zeros=len(zeros), rb=sim.readback_a,
gave=getattr(w.c.car_writer, "phases_gave_up", None), row=w.rows().get(
"charger_phases"), power=sim.power_w)
await w.act("car_phases", 3) # the user asks again: tried again
await w.step(60)
out["after_user"] = len([x for x in w.writes() if x[1] == "phases"]) - len(ph)
return out
m2 = run(m2_refused())
check("M2: a phase select the charger never takes is tried 3 times (10 minutes "
"apart), not for ever", m2["ph"] == 3 and m2["zeros"] == 3)
check("...each time the car gets its current back on the old phases (10 A, "
"drawing), and at the end it is not left paused", m2["rb"] == 10
and m2["power"] > 2000)
check("...then an amber row says the charger did not take the phases, and "
"the add-on stops trying", m2["gave"] is True
and m2["row"]["ok"] is False and m2["row"]["warn"] is True)
check("...until the user changes something: then it tries again",
m2["after_user"] == 1)
async def m3(trigger):
w = World(setpoint=10, phases=1)
w.sim.ramp_w_s = 50.0
w.sim.stop_delay_s = 40.0
await w.step(60)
await w.act("car_mode", "manual")
await w.act("car_current", 10)
await w.step(3)
await w.act("car_phases", 3)
await w.step(3) # 0 A written, the select not yet
n0 = len(w.writes())
mid = (w.sim.readback_a, w.c.car_writer.seq["stage"])
if trigger == "off":
await w.act("car_mode", "off")
elif trigger == "shadow":
w.c.o["shadow_mode"] = "on"
elif trigger == "stop":
await w.c.handle_action("auto_toggle")
w.c.o["shadow_mode"] = "off"
elif trigger == "safety":
w.c.inverters[0].sign_wd.tripped = True
await w.step(80)
return w, mid, [(x[1], x[2]) for x in w.writes()[n0:]]
for _trig, _want in (("off", [("current", 10.0)]), ("shadow", []),
("stop", [("current", 10.0)]),
("safety", [("current", 10.0)])):
w_m3, mid_m3, wr_m3 = run(m3(_trig))
check(f"M3 ({_trig} mid-sequence, before the select): no phase switch, "
+ ("nothing is written further" if not _want else
"the old 10 A comes back") + f" ({wr_m3})",
mid_m3[0] == 0.0 and wr_m3 == _want and w_m3.writes("phases") == []
and w_m3.sim.phases_allowed == 1 and w_m3.c.car_writer.seq is None)
async def m4():
w = World(dict(CAR, ev_max_a=10), setpoint=16, phases=1)
w.sim.ramp_w_s = 50.0
w.sim.stop_delay_s = 40.0
await w.step(60)
await w.act("car_mode", "manual")
await w.act("car_phases", 3)
await w.step(4)
prev = w.c.car_writer.seq["prev"]
await w.c.car_shutdown()
return w, prev
w_m4, prev_m4 = run(m4())
check("M4: the old read-back was 16 A (another writer's) against ev_max_a 10; "
"the restore on shutdown is clamped: the car gets 10 A back, no "
"software fault is logged",
prev_m4 == 16.0 and w_m4.sim.readback_a == 10.0
and w_m4.drv.clamp_faults == [] and w_m4.drv.sent[-1] == 10.0)
# --- every write path: who calls the seam, and a fuzz over the lot --------- #
def seam_callers():
"""(file, name) of every call of the charger's write methods in app/."""
@@ -712,47 +852,71 @@ async def fuzz(seed):
rnd = random.Random(seed)
w = World(setpoint=rnd.choice([6, 10, 16]), phases=rnd.choice([1, 3]))
w.sim.lag_s = rnd.choice([0.0, 0.0, 3.0, 12.0])
bad = []
seen = 0
race = seed % 2 == 1 # half the sites run read -> settle -> cycle
bad, seen, others, holds, undos = [], 0, 0, 0, 0
last_switch = None
if rnd.random() < 0.8:
await w.act("car_mode", "manual")
for step in range(400):
c, sim = w.c, w.sim
seq = c.car_writer.seq is not None
wr = c.car_writer
stage = wr.seq["stage"] if wr.seq is not None else None
seq = stage is not None
r = rnd.random()
if r < 0.02:
if stage in ("zero", "select") and rnd.random() < 0.15:
# the user, a stop or shadow mode arrives mid-sequence
pick = rnd.choice(["off", "stop", "shadow"])
if pick == "off":
await w.act("car_mode", "off")
elif pick == "stop":
c.auto = False
else:
c.o["shadow_mode"] = "on"
elif r < 0.02:
await w.act("car_mode", rnd.choice(["off", "manual", "manual"]))
elif r < 0.07:
await w.act("car_current", rnd.randint(6, 16))
elif r < 0.09:
await w.act("car_phases", rnd.choice([1, 3]))
elif r < 0.095 and not seq:
elif r < 0.093 and not seq:
sim.go_unavailable(rnd.random() < 0.5)
elif r < 0.10 and not seq:
elif r < 0.096 and not seq:
sim.station_a = float(rnd.choice([10, 13, 16]))
elif r < 0.105 and not seq:
elif r < 0.099 and not seq:
(sim.unplug if sim.state != "A" else sim.plug_in)()
elif r < 0.103 and rnd.random() < 0.5:
elif r < 0.108:
sim.set_current(rnd.randint(0, 16)) # another writer
elif r < 0.115:
others += 1
elif r < 0.112:
sim.refuse = rnd.choice([None, None, "ignore", "error"])
elif r < 0.12:
elif r < 0.116:
c.auto = rnd.random() < 0.8
mode_now, auto_now = c.car_mode, c.auto
n0 = len(sim.log)
await w.step(1)
elif r < 0.12:
c.o["shadow_mode"] = rnd.choice(["on", "off", "off"])
mode_now, auto_now, shadow_now = c.car_mode, c.auto, c.shadow
n0, u0 = len(sim.log), getattr(wr, "undone", 0)
await (w.step_race(1) if race else w.step(1))
undone = getattr(wr, "undone", 0) > u0
undos += undone
holds += bool(wr.hold)
for t, what, v, power, sp in sim.log[n0:]:
clamp = min(16.0, sim.station_a)
# a sequence whose select has gone out is finished whatever the
# mode says; one undone before it gives the old current back
exempt = stage == "settle" or undone
if what == "current" and not 0.0 <= v <= clamp + 1e-9:
bad.append((seed, step, "over the clamp", v, clamp))
if what == "current" and (mode_now != "manual" and not seq):
if what == "current" and mode_now != "manual" and not exempt:
bad.append((seed, step, "written outside Manual", mode_now))
if what in ("current", "phases") and not auto_now and not seq:
if what in ("current", "phases") and not auto_now and not exempt:
bad.append((seed, step, "written with control stopped"))
if what in ("current", "phases") and shadow_now and not exempt:
bad.append((seed, step, "written in shadow mode"))
if what == "current" and sim.state == "A" and not seq:
bad.append((seed, step, "written with no car"))
if what == "phases":
if mode_now != "manual" or not auto_now or shadow_now:
bad.append((seed, step, "phases selected outside Manual"))
if sp != 0.0:
bad.append((seed, step, "phases with the setpoint up", sp))
if last_switch is not None and t - last_switch < 600.0:
@@ -760,19 +924,26 @@ async def fuzz(seed):
t - last_switch))
last_switch = t
seen += len(sim.log) - n0
return bad, seen
return bad, seen, others, holds, undos
fz_bad, fz_n = [], 0
fz_bad, fz_n, fz_o, fz_h, fz_u = [], 0, 0, 0, 0
for _seed in range(14):
_b, _n = run(fuzz(_seed))
_b, _n, _o, _h, _u = run(fuzz(_seed))
fz_bad += _b
fz_n += _n
fz_o += _o
fz_h += _h
fz_u += _u
check(f"fuzz: {fz_n} charger writes over 14 random sites and 5600 steps of "
f"random user changes, outages, unplugs, refusals and other writers: "
f"none over the clamp, none outside Manual, none with control stopped "
f"or no car, the phases never moved with the car drawing, one switch "
f"per 10 minutes ({fz_bad[:3]})", not fz_bad and fz_n > 100)
f"random user changes, outages, unplugs, refusals, shadow and control "
f"stops, in both cycle orders: none over the clamp, none outside "
f"Manual, none with control stopped, in shadow mode or with no car, the "
f"phases never selected outside Manual or with the car drawing, one "
f"switch per 10 minutes ({fz_bad[:3]})", not fz_bad and fz_n > 100)
check(f"fuzz: the other-writer branch runs ({fz_o} other writers made, "
f"{fz_h} steps with the add-on holding off one, {fz_u} sequences undone)",
fz_o > 30 and fz_h > 5 and fz_u > 0)
# =========================================================================== #
print("\n6. SHADOW MODE AND A STOPPED CONTROL WRITE NOTHING")
@@ -1160,16 +1331,101 @@ w_ = r_stuck["c"]
check("...while stuck, the car figure is not used by the alarm path",
w_.car.stuck(w_.car_now()) and w_.car_alarm_w() is None)
# a plausible figure is bounded by what the read-back allows
# a plausible figure is bounded by what the read-back allows (and needs an
# energy meter that agrees with it)
def corr(tr, t):
f = getattr(tr, "corroborated", None)
return f(t) if f else True # an old tree has no such rule
def charging_reading(e_kwh, w=11000.0, a=6.0):
return CH.ChargerReading(available=True, state="C", charging=True,
power_w=w, allowed_a=a, setpoint_a=a,
phases_allowed=1, energy_kwh=e_kwh)
def feed(tr, secs, e_of, w=11000.0, t0=100.0):
for i in range(secs):
tr.observe(charging_reading(e_of(i), w), t0 + i,
datetime(2026, 11, 16, tzinfo=timezone.utc), "2026-11-16")
return t0 + secs - 1
tr = CH.CarTracker()
tr.observe(CH.ChargerReading(available=True, state="C", power_w=11000.0,
allowed_a=6.0, setpoint_a=6.0,
phases_allowed=1), 100.0,
datetime(2026, 11, 16, tzinfo=timezone.utc), "2026-11-16")
check("a car figure of 11 kW on a 6 A, 1 phase read-back counts for no more "
t_end = feed(tr, 80, lambda i: 1000.0 + i * 11000.0 / 3.6e6)
check("an honest 11 kW figure on a 6 A, 1 phase read-back counts for no more "
"than that allows (1.5 kW), so an old figure cannot cover a house "
"overload", abs(tr.car_w_trusted(100.0) - 6 * 253) < 1)
check("...and None when it is not fresh", tr.car_w_trusted(100.0 + 16) is None)
"overload", abs(tr.car_w_trusted(t_end) - 6 * 253) < 1
and corr(tr, t_end))
check("...and None when it is not fresh", tr.car_w_trusted(t_end + 16) is None)
tr = CH.CarTracker()
t_end = feed(tr, 20, lambda i: 1000.0)
check("the first minute of readings is believed (a session just began): no "
"false alarm while the meter has had no time to show it",
corr(tr, t_end) and tr.car_w_trusted(t_end) is not None)
t_end = feed(tr, 80, lambda i: 1000.0, t0=t_end + 1)
check("M5: a power figure of 11 kW with an energy meter that does not move "
"is not corroborated after a window: no car figure for the alarms",
not corr(tr, t_end) and tr.car_w_trusted(t_end) is None)
tr = CH.CarTracker()
t_end = feed(tr, 80, lambda i: 1000.0 + i * 1500.0 / 3.6e6)
check("M5: a meter that gains 1.5 kW while the power says 11 kW is not "
"corroborated either", not corr(tr, t_end))
tr = CH.CarTracker()
t_end = feed(tr, 80, lambda i: None)
check("M5: no energy entity: never corroborated, so never used",
not corr(tr, t_end) and tr.car_w_trusted(t_end) is None)
tr = CH.CarTracker()
t_end = feed(tr, 80, lambda i: 1000.0 + i * 5000.0 / 3.6e6, w=5000.0)
t_end = feed(tr, 80, lambda i: 1000.0 + i * 11000.0 / 3.6e6, t0=t_end + 1)
check("a car that really ramps up (5 kW to 11 kW) stays corroborated",
corr(tr, t_end))
# --- M5 end to end: the meter, the plant and the real controller ------------- #
def freeze_all(plant, c):
plant.ch.freeze() # every reading sticks
plant.ch.set_current(0) # the car really stops
plant.load = lambda at: 9000.0 + plant.ch.power_w
def freeze_power_only(plant, c):
plant.ch.freeze_power() # only the power sensor sticks
plant.ch.set_current(6) # the car really draws 1.4 kW
plant.ch.set_phases(1)
plant.load = lambda at: 9000.0 + plant.ch.power_w
r_fz_mid = P.drive(HOUSE, dur=400, events={120: freeze_all})
r_fz_pw = P.drive(HOUSE, dur=400, events={120: freeze_power_only})
r_fz_0 = P.drive(HOUSE, dur=400, events={5: freeze_all})
r_noe = P.drive(HOUSE, dur=240, sim=SimCharger(setpoint_a=16))
for _name, _r, _t0 in (("a freeze in the middle of a session (everything "
"stuck, the car stops)", r_fz_mid, 120),
("only the power sensor sticks while the car draws "
"1.4 kW", r_fz_pw, 120),
("a freeze from the start", r_fz_0, 5)):
_al = alarms(_r)
check(f"M5: {_name} and the house steps to 9 kW: after a window the "
f"normal alarm fires ({_al})",
[n for _t, n in _al] == ["goodwe_peak_saturated"]
and _t0 < _al[0][0] < _t0 + 60 + 25)
r_honest = P.drive(HOUSE, dur=400)
check("M5: an honest charging car still suppresses the alarms for the whole "
"run, meter and all", alarms(r_honest) == []
and len(P.ids(r_honest, P.OVER)) == 1)
class _NoE(SimCharger):
pass
_sim_noe = SimCharger(setpoint_a=16)
_sim_noe.no_energy = True
r_noe = P.drive(HOUSE, dur=240, sim=_sim_noe)
check("M5: a charger with no energy entity does not suppress: the normal "
"alarm fires and there is no car notice",
[n for _t, n in alarms(r_noe)] == ["goodwe_peak_saturated"]
and P.ids(r_noe, P.OVER) == [])
# =========================================================================== #
print("\n10. DECISION 1: BATTERIES HELP WITH THE PEAK, ON AND OFF")
@@ -1187,8 +1443,9 @@ check("off: the guard sees the house without the car, is not engaged, and the "
check("off: the quarter goes over by the car alone, and the add-on says so "
"(one grey notice), with no alarm",
alarms(r_no) == [] and len(P.ids(r_no, P.OVER)) == 1)
check("off: the Why says the batteries keep their charge",
"keep their charge" in cardwhy(r_no))
check("off: the Why says the guard ignores the car (and promises nothing "
"about the batteries)", "guard ignores the car" in cardwhy(r_no)
and "keep their charge" not in cardwhy(r_no))
check("either way the car is never throttled",
r_on["sim"].writes() == [] and r_no["sim"].writes() == []
and r_no["sim"].setpoint_a == 16 and r_no["sim"].power_w > 10000)
@@ -1445,6 +1702,23 @@ check("the Dutch is not the English for the sentences",
for k in ("manual_set", "manual_cover", "manual_over", "manual_full",
"manual_nocover", "manual_wait", "manual_would",
"manual_stopped", "manual_blocked")))
check("L2: one wording for 'something else changes the charger', in Off and "
"Manual, English and Dutch",
en["home_words"]["attn"]["charger_other"]
== en["home_words"]["attn"]["charger_writer"]
and nl["home_words"]["attn"]["charger_other"]
== nl["home_words"]["attn"]["charger_writer"]
and "changes the charger" in str(messages.row_charger_other())
and "wijzigt de laadpaal" in messages.row_charger_other().nl
and "changed" not in str(messages.row_charger_other()))
check("L3: with Batteries help off the Why promises nothing about the "
"batteries, and DOCS says what it does",
"keep their charge" not in json.dumps(en) + json.dumps(nl)
.replace("houden hun lading", "keep their charge")
and "zero-grid control can still discharge them for the car"
in io.open(os.path.join(HERE, "DOCS.md"), encoding="utf-8").read()
.replace("\n", " ").replace("Normal zero-grid control can still",
"zero-grid control can still"))
check("every new row, notice and refusal is bilingual",
all(getattr(f, "nl", None) for f in (
messages.row_car_over(), messages.row_charger_other(),