Compare commits

..
2 Commits
Author SHA1 Message Date
Claude (dev) b662d7171b EV-16: key the held Car Why to the car_over episode; add T16, T18 and N-id checks
checks / unit (pull_request) Successful in 25m43s
infra-pin / fresh (pull_request) Failing after 2s
Control bumps _car_over_ep at each start and end of car_over; the display
ignores a hold of another episode, so a read overlapping the end cannot bring
a stale text back.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-21 10:04:00 +01:00
Claude (dev) 3b1189cdbf EV-16: hold the Car Why text while car_over holds and the guard floor flag toggles
checks / unit (pull_request) Successful in 27m49s
infra-pin / fresh (pull_request) Failing after 2s
Display only: the 'are at' / 'give all they can' text changes only when the
other state has stood for 180 s (the car_over off hold); SoC unread is never
'are at'. Cleared when car_over drops, on unplug and with cover off.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-21 08:54:04 +01:00
3 changed files with 494 additions and 1 deletions
+6
View File
@@ -61,6 +61,8 @@ class CarMixin:
self.car_over = False # ... held: the card and row say so
self._car_over_since = None
self._car_over_gone = None
self._car_why_hold = None # EV-16: the held Car Why (display)
self._car_over_ep = 0 # EV-16: bumped by control at each start/end of car_over; the hold is valid for one value
self._car_batt_prev = self._car_batt_prev2 = None
self._car_hx_prev = None # EV-19: last cycle's (held, car W)
self._car_need_real = self._car_need_excl = False # EV-10 latches
@@ -392,12 +394,15 @@ class CarMixin:
if self._car_over_since is None:
self._car_over_since = mono
if mono - self._car_over_since >= OVER_HOLD_S:
if not self.car_over:
self._car_over_ep += 1 # EV-16: a new episode
self.car_over = True
else:
if self._car_over_gone is None:
self._car_over_gone = mono
if mono - self._car_over_gone >= OVER_OFF_HOLD_S:
self.car_over, self._car_over_since = False, None
self._car_over_ep += 1 # EV-16: ends the held Why
self._car_over_gone = None
def _car_explains_alarm(self, real_proj, guard, target_w, w) -> bool:
@@ -497,6 +502,7 @@ class CarMixin:
# The session is over: that is a real end, with no hold.
self.car_over = False
self._car_over_since = self._car_over_gone = None
self._car_over_ep += 1 # EV-16: ends the held Why
if s not in (chargers.NONE_, None) and self._car_prev_state in (
chargers.NONE_, None):
self._car_session += 1
+34 -1
View File
@@ -1301,6 +1301,37 @@ def _car_why(key, c, good):
return _t("car.why." + (key if key else "wait"))
# EV-16: the Why of "car over the limit" follows the guard's floor flag, which
# toggles cycle by cycle at the reserve. The text is held: it changes only when
# the other state has stood for as long as the car_over row's own hold.
WHY_HOLD_S = 180.0 # = ctl_car.OVER_OFF_HOLD_S (tested)
def _over_why_is_floor(c, pg) -> bool:
"""True: "are at {pct}"; False: "give all they can". Display only: the
state lives in `c._car_why_hold`, stamped with the episode `c._car_over_ep`
that control bumps; a hold of another episode is never used, so a read
overlapping the end of car_over cannot bring a stale text back."""
mono = c.car_now()
cand = (pg.floor_limited and pg.soc is not None) if pg is not None \
else None
ep = getattr(c, "_car_over_ep", 0) # owned by the control loop
h = getattr(c, "_car_why_hold", None)
if h is not None and h[2] != ep: # a hold of an ended episode
h = None
if h is None:
h = [bool(cand), None, ep] # shown, since when, episode
elif cand is None or cand == h[0]:
h[1] = None
else:
if h[1] is None:
h[1] = mono
if mono - h[1] >= WHY_HOLD_S:
h = [cand, None, ep]
c._car_why_hold = h
return h[0]
def _car_manual_why(c, key):
"""The Why of Manual: what you set, and what the peak limit does about it.
Plan lines: two sentences of at most 12 words."""
@@ -1311,9 +1342,11 @@ def _car_manual_why(c, key):
if c.car_over:
pg = getattr(c, "peak_guard", None)
if not c.car_cover:
c._car_why_hold = None
return _t("car.why.manual_nocover", a=a)
return _t("car.why.manual_over" if pg is not None and pg.floor_limited
return _t("car.why.manual_over" if _over_why_is_floor(c, pg)
else "car.why.manual_full", a=a, pct=pct)
c._car_why_hold = None
if c.shadow:
t, n = w.would if w.would is not None else (c.car_a, c.car_n)
return _t("car.why.manual_would", a=f"{float(t):.0f}",
+454
View File
@@ -0,0 +1,454 @@
"""EV-16: the Car Why does not alternate between "are at {pct}" and "give all
they can" while the car-over row holds and the guard's floor flag toggles.
`python3 -B test_ev16.py`
Display only: the text is held in `c._car_why_hold`; control never reads it. Control owns
`c._car_over_ep` (bumped at each start and end of car_over); a hold of
another episode is never used.
Mutant: pick the text from the live `floor_limited` again (T1, T2, T7, T8, T9
go red).
Mutating a module this file grades? Read MUTATION.md first.
"""
import dataclasses
import hashlib
import os
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, "tools"))
from app import ctl_car, homeview, chargers as CH # noqa: E402
import ev04_peak as P # noqa: E402
import safety81_sim as s81 # noqa: E402
fails = []
def check(name, cond):
print(f" {'ok ' if cond else 'FAIL'} {name}")
if not cond:
fails.append(name)
OVER = "are at"
FULL = "give all they can"
Q = 900.0
STEP = 5.0
@dataclasses.dataclass
class G:
floor_limited: bool = True
soc: object = 20.0
saturated: bool = False
floor_w: float = 0.0
able_w: object = None
ceiling_w: float = 4500.0
engaged: bool = True
blind: object = None
wanted_w: float = 300.0
within_aim: bool = False
class Proj:
projected_w = 14500.0
held_w = 14500.0
elapsed_s = 400.0
block_start = None
class S(ctl_car.CarMixin):
def __init__(self, cover=True):
self.o = {"ev_batt_cover": cover}
self._now = 0.0
self.w = 11000.0
self.site_batt_w, self.site_rating_w = 8100.0, 9600.0
self.shadow, self.auto, self.peak_guard = False, True, None
self.state = "charging"
self.car_init({}, type("St", (), {"data": {}, "set": lambda s, k, v: 0})())
self.car_over = True
def car_now(self):
return self._now
def car_alarm_w(self):
return self.w
@property
def car(self):
me = self
class _C:
@staticmethod
def status(*_a):
return me.state
return _C
def why(c):
return homeview._car_manual_why(c, "charging")
def kind(t):
return "over" if OVER in t else "full" if FULL in t else t
def run(c, secs, g_of, t0=0.0):
"""Read the Why once per 5 s cycle; returns [(t, kind)]."""
out = []
t = t0
while t < t0 + secs:
c._now = t
c.peak_guard = g_of(t - t0)
out.append((t, kind(why(c))))
t += STEP
return out
def changes(seq):
return [i for i in range(1, len(seq)) if seq[i][1] != seq[i - 1][1]]
def toggle(period, first=True):
return lambda t: G(floor_limited=(int(t // period) % 2 == 0) == first)
HOUSE = s81.constant(1100.0)
def real_run(read, eventful=True):
"""The T1 shape through the real controller: the batteries toggle across
the reserve every 10 s. Returns the control digest, the per-cycle rows and
flags, and the Why texts read (if `read`)."""
texts, rows, flags = [], [], []
def ev(plant, c):
plant.soc = 19.0 if int(plant.t // 10) % 2 == 0 else 60.0
pg = c.peak_guard
flags.append(None if pg is None else pg.floor_limited)
rows.append(tuple((x["id"], x["ok"], x["warn"]) for x in c.checks()
if x["id"] in ("peak_guard", "car_over")))
if read and c.car_over:
texts.append(homeview.car_block(c, None)["why"])
r = P.drive(HOUSE, dur=900, events={k: ev for k in range(0, 900)},
cap=3500.0)
ctl = ([s[1:] for s in r["snaps"]], list(r["raised"]),
r["sim"].writes(), r["sim"].setpoint_a)
return ctl, rows, flags, texts
def digest(x):
return hashlib.sha256(repr(x).encode()).hexdigest()[:16]
if "--digest" in sys.argv:
ctl, rows, flags, _t = real_run(False)
print("DIGEST control", digest(ctl), "rows", digest(rows),
"flags", digest(flags))
sys.exit(0)
print("1. the hold: a toggling flag shows one text")
c = S()
a = run(c, Q, toggle(10.0, True))
check("T1 quarter starts floor-limited, toggles every 10 s: one distinct text",
len({k for _, k in a}) == 1 and a[0][1] == "over")
for per in (20.0, 30.0, 10.0):
c = S()
a = run(c, Q, toggle(per, False))
check(f"T2 starts not limited, toggles every {per:.0f} s: at most one "
f"change, none back", len(changes(a)) <= 1)
c = S()
a = run(c, Q, lambda t: G(floor_limited=False, soc=38.0))
check("T3 never limited: 'give all they can' every cycle, never 'are at'",
{k for _, k in a} == {"full"})
c = S()
a = run(c, Q, lambda t: G())
check("T4 limited and steady: 'are at' 20 % from the first cycle",
{k for _, k in a} == {"over"}
and "20 %" in why(c))
print("\n2. real changes still show")
c = S()
a = run(c, 300.0, lambda t: G(floor_limited=False, soc=30.0))
a += run(c, 600.0, lambda t: G(), t0=300.0)
ch = changes(a)
check("T5 full for 300 s then steady limited: one change, full -> over, "
"within 185 s", len(ch) == 1 and a[ch[0]][1] == "over"
and a[ch[0]][0] - 300.0 <= 185.0)
c = S()
a = run(c, 300.0, lambda t: G())
a += run(c, 600.0, lambda t: G(floor_limited=False, soc=30.0), t0=300.0)
ch = changes(a)
check("T6 limited for 300 s then steady not limited: one change back to "
"'give all they can' within 185 s", len(ch) == 1
and a[ch[0]][1] == "full" and a[ch[0]][0] - 300.0 <= 185.0)
for steady_false in (True, False):
c = S()
a = run(c, Q, toggle(10.0, True))
a += run(c, Q, (lambda t: G(floor_limited=False, soc=30.0))
if steady_false else (lambda t: G()), t0=Q)
ch = changes(a)
first_q = {k for t, k in a if t < Q}
check(f"T7 toggling across the edge, new quarter steady "
f"{'False' if steady_false else 'True'}: nothing before the edge, "
f"at most one change near it, to the new state",
len(first_q) == 1 and len(ch) <= 1
and all(a[i][0] >= Q for i in ch)
and len(a) > 0 and a[-1][1] == ("full" if steady_false else "over"))
near = [i for i in ch if abs(a[i][0] - Q) <= 60.0]
check("T7 (cont.) at most one change in the 60 s around the edge",
len(near) <= 1)
print("\n3. failure modes")
c = S()
a = run(c, Q, lambda t: G(soc=None))
check("T8 SoC unread, guard limited: never 'are at', one text",
{k for _, k in a} == {"full"})
c = S()
a = run(c, Q, lambda t: G(soc=None if int(t // 10) % 2 == 0 else 20.0))
check("T8 SoC toggling None / 20 % every 10 s, starting unread: one text, "
"never 'are at'", {k for _, k in a} == {"full"})
c = S()
seq = []
for t in range(0, 900, 5):
c._now = float(t)
c.peak_guard = None if 400 <= t < 410 else G(floor_limited=(t // 10) % 2
== 0)
try:
seq.append((t, kind(why(c))))
except Exception as e: # noqa: BLE001
seq.append((t, "TRACE " + repr(e)))
check("T9 guard None for a cycle: no Traceback, one text through it",
not any("TRACE" in k for _, k in seq) and len({k for _, k in seq}) == 1)
c = S()
c.peak_guard = None
c._now = 0.0
check("T9 (cont.) guard None from the very first read: a text, no Traceback",
kind(why(c)) in ("full", "over"))
# T10: the car stops, car_over drops after 180 s, a later episode
c = S()
run(c, 100.0, lambda t: G())
check("T10 held 'are at' to start", kind(why(c)) == "over")
for k in range(0, 200):
c._now = 100.0 + k
c.w = None
c.car_cycle(Proj(), G(), 14000.0, None)
check("T10 car_over dropped after the stop", c.car_over is False)
check("T10 the Why left the over wording", OVER not in why(c)
and FULL not in why(c))
c.car_over = True # a new episode, later, SoC 60 %
c._now = 5000.0
c.peak_guard = G(floor_limited=False, soc=60.0)
check("T10 the new episode shows 'give all they can' from its first cycle",
kind(why(c)) == "full")
# T10b: no read between the drop and the new episode (the hold is cleared at
# the drop, not at a read)
c = S()
run(c, 100.0, lambda t: G())
for k in range(0, 200):
c._now = 100.0 + k
c.w = None
c.car_cycle(Proj(), G(), 14000.0, None)
c.car_over = True
c._now = 9000.0
c.peak_guard = G(floor_limited=False, soc=60.0)
check("T10 no /status between the drop and the new episode: still 'full'",
kind(why(c)) == "full")
# T11: unplug
c = S()
run(c, 100.0, lambda t: G())
c._car_prev_state = "charging"
c.state = CH.NONE_
c._now = 105.0
c.car_cycle(Proj(), G(), 14000.0, None)
c.car_over = False
check("T11 after the unplug cycle there is no over wording",
OVER not in homeview._car_manual_why(c, "none")
and FULL not in homeview._car_manual_why(c, "none")
and "set when a car is connected" in homeview._car_manual_why(c, "none"))
c.state = "charging"
c.car_over = True
c.peak_guard = G(floor_limited=False, soc=60.0)
c._now = 400.0
check("T11 a replug starts with no held text", kind(why(c)) == "full")
# the hold is also gone when the unplug itself ends car_over (no read between)
c = S()
run(c, 100.0, lambda t: G())
c._car_prev_state = "charging"
c.state = CH.NONE_
c._now = 105.0
ep_before = c._car_over_ep
c.car_cycle(Proj(), G(), 14000.0, None)
check("T11 (cont.) the unplug ends the episode (control bumps it)",
c.car_over is False and c._car_over_ep > ep_before)
# T12: cover off while car_over holds
c = S()
run(c, 100.0, lambda t: G())
c.o["ev_batt_cover"] = False
c._now = 105.0
check("T12 cover off: 'ignores the car' at the next read",
"ignores the car" in why(c))
c.o["ev_batt_cover"] = True
c.peak_guard = G(floor_limited=False, soc=60.0)
c._now = 110.0
check("T12 cover on again, steady not limited: 'give all they can', not "
"the old 'are at'", kind(why(c)) == "full")
# T13: restart
c = S()
a = run(c, 450.0, toggle(10.0, True))
c2 = S()
b = run(c2, 450.0, toggle(10.0, True), t0=450.0)
check("T13 restart mid-quarter: no Traceback, a text, at most one change "
"after", kind(why(c2)) in ("full", "over") and len(changes(b)) <= 1)
print("\n4. control unchanged; the rows follow the live flag")
ctl1, rows1, flags1, sts = real_run(True)
ctl0, rows0, flags0, _t = real_run(False)
check("T14 reading the Why every cycle changes no command, alarm or row",
ctl1 == ctl0 and rows1 == rows0 and flags1 == flags0)
shown = [t for t in sts if OVER in t or FULL in t]
flips = sum(1 for a, b in zip(flags1, flags1[1:]) if a != b)
BASE_8150608 = ("e6034b0c78f23776", "5ffb80fa428cd6ee", "689a5b0e4bf7c897")
check("T14/T15 commands, alarms, charger writes and the peak_guard/car_over "
"rows equal those of base 8150608 (digests taken there with --digest)",
(digest(ctl1), digest(rows1), digest(flags1)) == BASE_8150608)
check("PRECONDITION: the real guard's floor flag toggles many times and "
"car_over is on for most of the run", flips > 20 and len(shown) > 200)
check("T1/T2 through the real guard: at most one Why change in the quarter",
sum(1 for a, b in zip(shown, shown[1:]) if a != b) <= 1)
check("T15 the peak_guard row follows the live flag (it changes as often as "
"the flag), the hold is only in the Why",
sum(1 for a, b in zip(rows1, rows1[1:]) if a != b) >= 1
and len({r for r in rows1 if r}) >= 1)
print(" DIGEST control", digest(ctl1), "rows", digest(rows1),
"flags", digest(flags1))
print("\n5. text, hold and wiring")
check("the hold equals the car_over row's own off hold",
homeview.WHY_HOLD_S == ctl_car.OVER_OFF_HOLD_S)
src = open(os.path.join(HERE, "app", "homeview.py")).read()
check("the live flag is read only by the hold helper, not by the Why branch",
'pg.floor_limited else' not in src)
import json
for lang, over, full in (
("en", "You set {a} A. The batteries are at {pct}, so this charge "
"sets the peak.",
"You set {a} A. The batteries give all they can, so this charge "
"sets the peak."),
("nl", "U stelde {a} A in. De batterijen staan op {pct}, dus deze "
"lading bepaalt de piek.",
"U stelde {a} A in. De batterijen geven alles, dus deze lading "
"bepaalt de piek.")):
d = json.load(open(os.path.join(HERE, "app", "ui_text", lang + ".json")))
d = d["home_words"]["car"]["why"]
check(f"T17 {lang}.json wording of manual_over / manual_full unchanged",
d["manual_over"] == over and d["manual_full"] == full)
check("a held peak_guard row is not touched: the module still has no hold "
"in ctl_status", "_car_why_hold" not in open(os.path.join(
HERE, "app", "ctl_status.py")).read())
print("\n6. EV-16 review round 1: the race, T16, T18, the N-ids")
# the race: a read takes the hold, control ends the episode, the read writes
# its old hold back; the next episode must not show it
c = S()
run(c, 100.0, lambda t: G())
stale = c._car_why_hold
check("race: the read holds 'are at' before the end", kind(why(c)) == "over")
for k in range(0, 200):
c._now = 100.0 + k
c.w = None
c.car_cycle(Proj(), G(), 14000.0, None)
c._car_why_hold = stale # the late write-back
c.car_over = True
c._car_over_ep += 1 # what control does on a start
c._now = 6000.0
c.peak_guard = G(floor_limited=False, soc=60.0)
check("N4 race: a read interleaved with the clear cannot bring the old "
"'are at' into the next episode", kind(why(c)) == "full")
c = S()
run(c, 100.0, lambda t: G())
stale = c._car_why_hold
c._car_prev_state = "charging"
c.state = CH.NONE_
c._now = 105.0
c.car_cycle(Proj(), G(), 14000.0, None)
c._car_why_hold = stale # write-back after an unplug
c.state = "charging"
c.car_over = True
c.peak_guard = G(floor_limited=False, soc=60.0)
c._now = 110.0
check("N4 race (unplug): a stale write-back after the unplug is not used",
kind(why(c)) == "full")
# T16: the existing checks this one must leave alone are present and run in CI
for f in ("test_ev04.py", "test_ev10.py", "test_ev10b.py", "test_ev18.py",
"test_ev19.py", "test_home.py", "test_named_absence.py",
"test_bytecode.py"):
check(f"T16 {f} exists (run unchanged by CI's run-tests.sh)",
os.path.exists(os.path.join(HERE, f)))
t04 = open(os.path.join(HERE, "test_ev04.py")).read()
check("T16 test_ev04's Manual Why assertion 'batteries give all they can' "
"is still there", 'batteries give all they can" in cardwhy' in t04)
# T18: the mutant, in process: the live flag picks the text again
real = homeview._over_why_is_floor
homeview._over_why_is_floor = lambda c, pg: bool(
pg is not None and pg.floor_limited)
try:
m = run(S(), Q, toggle(10.0, True))
m8 = run(S(), Q, lambda t: G(soc=None))
finally:
homeview._over_why_is_floor = real
check("T18 mutant (live flag): T1 shape alternates and T8 shows 'are at', so "
"T1, T2, T7 and T8 would go red", len(changes(m)) > 20
and any(k == "over" for _, k in m8))
# the N-ids, by name
a = run(S(), Q, toggle(10.0, True))
check("N1 control: batteries, charger writes and setpoint equal base "
"(digests, section 4)", (digest(ctl1), digest(rows1), digest(flags1))
== BASE_8150608)
check("N2 `floor_limited`, `car_explains`, `car_over`, the peak_guard row "
"are not changed by the hold: the guard flag toggles as in base "
"(flags digest) and the rows digest equals base",
digest(flags1) == BASE_8150608[2] and digest(rows1) == BASE_8150608[1])
n3 = run(S(), Q, lambda t: G(soc=None)) + run(
S(), Q, lambda t: G(floor_limited=False, soc=40.0))
check("N3 never 'are at' with SoC unread or with the guard never limited",
{k for _, k in n3} == {"full"})
c = S()
run(c, 100.0, lambda t: G())
c.car_over = False
n4 = homeview._car_manual_why(c, "charging")
check("N4 no over wording once car_over is off", OVER not in n4
and FULL not in n4)
check("N5 at most one Why change in a quarter while the guard toggles",
len(changes(a)) <= 1)
try:
for g in (None, G(soc=None), G(), G(floor_limited=False, soc=1.0)):
c = S()
c.peak_guard = g
why(c)
n6 = True
except Exception: # noqa: BLE001
n6 = False
check("N6 no Traceback for a guard of None, SoC unread, limited, not "
"limited", n6)
en = open(os.path.join(HERE, "app", "ui_text", "en.json")).read()
nl = open(os.path.join(HERE, "app", "ui_text", "nl.json")).read()
check("N7 wording unchanged: the four texts are in the files verbatim",
"The batteries are at {pct}, so this charge sets the peak." in en
and "The batteries give all they can, so this charge sets the peak."
in en and "De batterijen staan op {pct}, dus deze lading bepaalt de "
"piek." in nl and "De batterijen geven alles, dus deze lading bepaalt "
"de piek." in nl)
print()
print("FAIL: " + ", ".join(fails) if fails else "PASS: every check passed")
sys.exit(1 if fails else 0)