Files
goodwe-addon/goodwe_controller/test_ev21_same.py
T
ems-agentandClaude 5759e9dc9f
checks / unit (pull_request) Successful in 46m9s
infra-pin / fresh (pull_request) Successful in 1s
EV-21 fix round 1 (formal round 4): C14 cut due while batteries charge; C15 grace once per value
C14 (PM Q2): slowing a battery charge counts as the batteries taking more, so the cut is due whatever the batteries do; their charge counts only as headroom for the 15 s wait. C15 (PM Q1): sent_at is renewed only for a new value, so a retry of a refused cut gets no new 2 s grace. test_ev21_fix1.py: both red on 36e9dd7; C16, C18 and Q1's other writer pinned as the code has them. Test shapes: slow batteries and refusals start after Solar's own start, which C14 would otherwise cut on its start blip; T38 cover off from 300 s; T46 bounds the excess; T39 counts writes after the cut.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-27 01:33:41 +01:00

315 lines
14 KiB
Python

"""EV-21: what must NOT change (Manual, Off, no excess, cloud edges the
batteries catch), the cut amount over a table of sites, the write seam, and
the docs and strings.
`python3 -B test_ev21_same.py`
Rows T4-T6, T11, T36 (the guard's floor), T37, T38, T47, T52, T53 of
reports/EV-21-test-plan.md. "Identical to c79eb37": each run's writes,
notices with their second, and per-second guard view (floor, car_explains,
car_over, red rows) are hashed (`ev21_kit.digest`); GOLDEN holds the hashes
the same runs give on c79eb37 (release/1.0 before EV-21), taken with
`EV21_GOLDEN=1 python3 -B test_ev21_same.py` on that tree. A hash that
differs fails, and the line prints what this tree gives.
Mutating a module this file grades? Read MUTATION.md first (purge __pycache__).
"""
import ast
import io
import os
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, "tools"))
import opt11_identity as rig # noqa: E402
from ev20_kit import LOG, check, fails, const, step_fn # noqa: E402
from ev21_kit import (AIM, after, digest, drive, shape, view_guard, # noqa: E402
view_writes, _cutamps, refuse_n1, merge)
n_log0 = LOG.mark()
TAKE = os.environ.get("EV21_GOLDEN") == "1"
GOLDEN = {
'T4 [Manual, cover on]': {
'writes': 'f391f105a59891b9',
'notes': '2e109ddce05805c1',
'guard': 'e9f0a5079393d301',
'floor': 'ee3dd0b6ddcda88a',
'batt': '0f657edaab7156ef'},
'T4 [Manual, cover off]': {
'writes': 'f391f105a59891b9',
'notes': '2e109ddce05805c1',
'guard': '461119b75fbb738a',
'floor': 'ee3dd0b6ddcda88a',
'batt': '0f657edaab7156ef'},
'T5 [Off]': {
'writes': '4f53cda18c2baa0c',
'notes': '346a74064b62c0f5',
'guard': '165d51d07b84c233',
'floor': 'ee3dd0b6ddcda88a',
'batt': 'a91930f22238e925'},
'T6 [Shape M: the batteries cover house and car]': {
'writes': '385ae1fbf07b25d6',
'notes': '4f53cda18c2baa0c',
'guard': 'a52b1c929747cd07',
'floor': 'f62cb235198fa562',
'batt': '26965ed24b700eae'},
'T11 (a) [the batteries catch it in a few seconds]': {
'writes': '2feff2d70bc160e2',
'notes': '4f53cda18c2baa0c',
'guard': '58bb40545886af53',
'floor': '547335adccb04a76',
'batt': '0954ff4dd06faae5'},
'T11 (b) [EV-05 T21b cloud edge, 16 A on 3 phases]': {
'writes': '65a8a3fa50b4d81c',
'notes': 'c70d97f8902a82a0',
'guard': '269d88368a15b2d9',
'floor': '309fe221f371aa6f',
'batt': '4719e28af092fdbe'},
'T38 [cover on]': {
'writes': '324aac021ce35055',
'notes': '4f53cda18c2baa0c',
'guard': '86809c51ba676e49',
'floor': 'f0e12bc7f14924dc',
'batt': '3ce6bd3c1711cc3b'},
'T38 [cover off]': {
'writes': '324aac021ce35055',
'notes': '4f53cda18c2baa0c',
'guard': '86809c51ba676e49',
'floor': 'f0e12bc7f14924dc',
'batt': '3ce6bd3c1711cc3b'},
'T36 [Shape M, cover off]': {
'writes': '385ae1fbf07b25d6',
'notes': '4f53cda18c2baa0c',
'guard': '912e434b12e20f7e',
'floor': 'bbb7dc2b3e81dba8',
'batt': 'c262ee254e496a16'},
}
got = {}
def same(name, r, t0=0, parts=("writes", "notes", "guard", "batt"),
t1=1e9):
"""The run against c79eb37, part by part: its charger writes, the
notices with their second, the per-second guard view (floor,
car_explains, car_over, red rows) and the battery commands."""
d = {"writes": digest(view_writes(r)), "notes": digest(r["raised"]),
"guard": digest(view_guard(r, t0)),
"floor": digest([(x["t"], round(x["floor"] or 0.0))
for x in r["trace"] if t0 <= x["t"] < t1]),
"batt": digest([(round(t), e, v) for t, e, v in r["plant"].sets
if e.startswith("number.sp_")])}
got[name] = d
if TAKE:
print(f"GOLDEN {name!r}: {d!r},")
return
want = GOLDEN.get(name) or {}
diff = [k for k in parts if want.get(k) != d[k]]
check(f"{name}: identical to c79eb37 in {', '.join(parts)} (differs in: "
f"{diff})", bool(want) and not diff)
def manual_store(a=10.0, n=3):
st = rig._Store()
st.data["car_current"], st.data["car_phases"] = a, n
return st
# =========================================================================== #
print("\n1. MANUAL AND OFF DO NOT CHANGE (T4, T5, T37)")
# =========================================================================== #
for cover in (True, False):
r = shape("C", mode="manual", cover=cover, dur=1300, store=manual_store(),
setpoint=0)
same(f"T4 [Manual, cover {'on' if cover else 'off'}]", r)
r = shape("C", mode="off", dur=1300)
check(f"T5 [Off]: zero charger writes ({r['sim'].log[:2]})", not r["sim"].log)
same("T5 [Off]", r)
# =========================================================================== #
print("\n2. NO CUT WHERE NONE IS DUE (T6, T11, T38)")
# =========================================================================== #
r = shape("M", dur=1300)
same("T6 [Shape M: the batteries cover house and car]", r)
check(f"T6: no cut state in Shape M "
f"({[x['t'] for x in r['rec'].rows if x['cap'] is not None][:2]})",
not [x for x in r["rec"].rows if x["cap"] is not None])
# (a) A house step of 5 kW the batteries (60 %, 1 s to respond) take over
# within a few seconds: the guard wants power briefly, no cut.
r = drive(step_fn((960, 5900.0), base=900.0), const(7900.0), dur=1300,
first="car", phases=3, socs={"a": 60.0, "b": 60.0},
opts={"ev_phases": "3"},
events={1: lambda p, c: setattr(p, "response_s", 1.0)})
wants = [x["t"] for x in r["rec"].rows if (x["want"] or 0) > 0]
check(f"T11 (a): the guard wants power {len(wants)} s ({wants[:1]}..."
f"{wants[-1:]}), no cut state "
f"({[x['t'] for x in r['rec'].rows if x['cap'] is not None][:2]})",
0 < len(wants) <= 8
and not [x for x in r["rec"].rows if x["cap"] is not None])
same("T11 (a) [the batteries catch it in a few seconds]", r)
r = drive(const(900.0), step_fn((910, 3000.0), (1030, 13000.0),
base=13000.0),
dur=1300, first="car", phases=3, socs={"a": 60.0, "b": 60.0},
opts={"ev_phases": "3"})
same("T11 (b) [EV-05 T21b cloud edge, 16 A on 3 phases]", r)
check(f"T11 (b): no cut state ({[x['t'] for x in r['rec'].rows if x['cap'] is not None][:2]})",
not [x for x in r["rec"].rows if x["cap"] is not None])
def house_trace(t):
"""A 1 h house trace, 600 to 1500 W, deterministic."""
k = int(t) // 37
return 600.0 + (k * 7919 % 900)
def cover_off(p, c):
c.o["ev_batt_cover"] = False
for cover in (True, False):
# Cover off from 300 s, once Solar's own start is past: with it off from
# the start, PM Q2 / formal C14 with OQ3 cut Solar's own start blip at
# once (dev report, Findings). On c79eb37 both hours hash the same.
r = drive(house_trace, lambda t: house_trace(t) + 7000.0, dur=3600,
first="car", phases=3, socs={"a": 60.0, "b": 60.0},
opts={"ev_phases": "3"},
events={} if cover else {300: cover_off})
caps = [x["t"] for x in r["rec"].rows if x["cap"] is not None]
check(f"T38 [cover {'on' if cover else 'off'}]: no cut in an hour with no "
f"excess ({caps[:2]})", not caps)
same(f"T38 [cover {'on' if cover else 'off'}]", r)
# =========================================================================== #
print("\n3. THE COVER OFF: THE GUARD'S FLOOR (T36)")
# =========================================================================== #
r = shape("M", cover=False, dur=1300)
# Up to the cut. From it the car is lowered, so the plant differs from
# c79eb37's (there the car runs on); the cut itself is T36 in
# test_ev21_paths.py.
same("T36 [Shape M, cover off]", r, parts=("floor",), t1=960)
# =========================================================================== #
print("\n4. THE CUT AMOUNT OVER A TABLE OF SITES (T47)")
# =========================================================================== #
cut = _cutamps()
rows47 = []
def stamp(p, c):
c.car_solar.nonzero_at = p.t # Solar's own 30 s gate is closed
for n in (2, 1):
for cover in (True, False):
for ph, car_ph in (("3", 3), ("1", 3), ("auto", 3), ("3", 1)):
for first in (("car", "batteries") if ph == "3" and car_ph == 3
else ("car",)):
ratings = {"a": 5000.0, "b": 4600.0} if n == 2 \
else {"a": 5000.0}
room = 0.0 if first == "car" else 9600.0
if ph == "3" and car_ph == 3:
car_w, n_draw = 6900.0, 3 # 10 A on 3 phases
elif ph == "3":
car_w, n_draw = 3680.0, 1 # a 1-phase car, 16 A
else:
car_w, n_draw = 2300.0 if ph == "1" else 3680.0, 1
sun0 = 900.0 + max(car_w, 4830.0 + 500.0 if car_ph == 1
else car_w) + 100.0 + room
# The house steps so about 6.4 A is left after the cut.
d = 3400.0 + car_w - 6.4 * 230.0 * n_draw + 150.0 + room
ev = {t: refuse_n1 for t in range(0, 1001)} if n == 1 else {}
ev = merge(ev, 958, stamp)
r = drive(step_fn((960, 900.0 + d), base=900.0),
const(sun0), dur=1000,
first=first, phases=1 if ph == "1" else 3,
car_phases=car_ph, ratings=ratings,
socs={u: 10.0 for u in ratings}, events=ev,
rows=False,
opts={"ev_phases": ph, "ev_batt_cover": cover})
w = after(r, 958)
ep = [x for x in r["rec"].rows if x["t"] >= 958
and x["cap"] is not None]
want = cut(ep[0]["car0"], ep[0]["ex"], n_draw) if ep \
else "none"
ok = bool(w) and w[0][0] <= 961 and bool(ep) \
and ep[0]["cap"] == want and w[0][1] == want
rows47.append(((n, cover, ph, car_ph, first), w[:1],
ep[0]["cap"] if ep else None, want, ok))
bad47 = [x for x in rows47 if not x[-1]]
check(f"T47: over N=1/2, cover on/off, ev_phases 1/3/auto, a 1-phase car on "
f"3, Car/Batteries first ({len(rows47)} sites): the cut within 1 cycle "
f"and floor((car0 - excess) / (230 x the phases the car draws on)) "
f"({bad47[:3]})", rows47 and not bad47)
# =========================================================================== #
print("\n5. THE WRITE SEAM (T52) AND THE DOCS AND STRINGS (T53)")
# =========================================================================== #
def seam_callers():
out = []
for f in sorted(os.listdir(os.path.join(HERE, "app"))):
if not f.endswith(".py") or f == "chargers.py":
continue
tree = ast.parse(io.open(os.path.join(HERE, "app", f),
encoding="utf-8").read())
for n in ast.walk(tree):
if isinstance(n, ast.Call) and isinstance(n.func, ast.Attribute) \
and n.func.attr in ("write_current", "write_phases"):
out.append((f, n.func.attr))
return sorted(out)
def calls_in(path, fn_names):
tree = ast.parse(io.open(os.path.join(HERE, "app", path),
encoding="utf-8").read())
out = []
for n in ast.walk(tree):
if isinstance(n, ast.FunctionDef) and n.name in fn_names:
for m in ast.walk(n):
if isinstance(m, ast.Call) and isinstance(m.func,
ast.Attribute):
out.append(m.func.attr)
return out
cut_calls = calls_in("ctl_car.py", {"_car_cut_tick", "_car_cut_hold",
"_car_cut_headroom"}) \
+ calls_in("carmode.py", {"_cut"})
check(f"T52: the write seam is still carmode.py's write_current and "
f"write_phases ({seam_callers()}); the cut's own code writes nothing and "
f"selects no phases ({sorted(set(cut_calls))})",
seam_callers() == [("carmode.py", "write_current"),
("carmode.py", "write_phases")]
and bool(cut_calls)
and not {"write_current", "write_phases", "_write", "_begin",
"_begin_solar", "_put"} & set(cut_calls))
def read(*p):
path = os.path.join(HERE, *p)
return io.open(path, encoding="utf-8").read() if os.path.exists(path) \
else ""
dec = " ".join(read("DECISIONS", "EV-21-car-cut-first.md").split())
docs = " ".join(read("DOCS.md").split())
chlog = read("CHANGELOG.md")
need = ["cut first", "15 s", "120 s", "Once per episode", "start power",
"can really cut"]
check(f"T53: DECISIONS/EV-21-car-cut-first.md states the rule in plain words "
f"({[w for w in need if w.lower() not in dec.lower()]} missing)",
bool(dec) and all(w.lower() in dec.lower() for w in need))
check("T53: DOCS 'Car charger' Solar section says the car is cut first, and "
"documents the grey note; the CHANGELOG has an EV-21 line",
"the car is cut first" in docs and "### Car lowered for the peak"
in docs and "`goodwe_car_cut`" in docs and "[[EV-21]]" in chlog)
tb = LOG.tracebacks(n_log0)
check(f"N11: no traceback in this file's runs ({tb[:1]})", not tb)
if TAKE:
print("(golden taken; no checks graded)")
sys.exit(0)
print(f"\n{'FAILED: ' + str(len(fails)) if fails else 'ALL PASSED'}")
sys.exit(1 if fails else 0)