"""EV-21 fix round 2 (review of 5759e9d, PM rulings R1-R5). `python3 -B test_ev21_fix2.py` - T34 (iv), R1: the reviewer's repro. Solar's own 1 -> 3 change has sent its 0 A, the read-back is 4 s late (still 16 A on 1 phase), the house heads the period over with no battery headroom. A cut due during Solar's own change ENDS the change at its 0 A: no select after it, no closing current, the car never draws more than before the cut. - T34 (v), R1: the same for a change from 3 phases to 1. - N6 / P27, R2: a refused closing write retried under a cut that came in between is never above the cut's cap (the `_seq_want` cap); under 6 A (3 A, 0 A) nothing is written after the cut (fix round 3, row (a)), also at controller level with the house heading over before the retry (b). - N9: a standing cap survives a cycle with a blind guard or a stale meter. - R1 standing cut (fix round 3): a standing partial cut goes to 0 A when a cut is due during Solar's own change. The real Controller on `tools/ev20_sun.py` through `tools/ev21_kit.py`, and for the N6/P27 row the real `SolarWriter` on a stub charger. Mutating a module this file grades? Read MUTATION.md first (purge __pycache__). """ import asyncio import dataclasses import os import sys from datetime import datetime, timezone HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.join(HERE, "tools")) from app import carmode, chargers as CH # noqa: E402 from ev20_kit import LOG, check, fails, const, step_fn, TSim # noqa: E402 from ev21_kit import AIM, after, drive, both, _mode, shape, never # noqa: E402 n_log0 = LOG.mark() def lag(s): def f(p, c): p.ch.lag_s = s return f def own_change_run(sun, kw, house_w, find): """Run once to find Solar's own change (`find(log)` gives the second of its 0 A), then again with the house at `house_w` from one second later. Both batteries switched off in battery modes (no headroom), the read-back 4 s late, the write beside the cycle.""" ev = {0: both(lag(4.0), _mode("ab", False))} r0 = drive(const(900.0), sun, **dict(kw, events=ev)) tb = find(r0["c"].car_solar.log) kw = dict(kw, dur=(tb or 400) + 120) r = drive(step_fn(((tb or 400) + 1, house_w), base=900.0), sun, **dict(kw, events=ev)) return tb, r def zero_before_select(log, n_to): """The 0 A that began Solar's change to `n_to` phases.""" sel = [t for k, a, t, ok in log if k == "phases" and a == n_to] z = [t for k, a, t, ok in log if k == "current" and a == 0.0 and sel and t <= sel[0]] return int(z[-1]) if z else None def judge(name, tb, r): rows = r["rec"].rows t1 = (tb or 0) + 1 pre = [x["car"] for x in rows if x["t"] == t1 - 1] car_pre = pre[0] if pre else None first = next((x for x in rows if x["t"] >= t1 and x["cap"] is not None), {}) nz = [(t, a) for t, a, _ in after(r, t1) if a > 0.0] sel = [(x[0], x[2]) for x in r["sim"].log if x[1] == "phases" and x[0] > first.get("t", 1e9)] more = [(x["t"], x["car"], round(x["proj"] or 0)) for x in rows if x["t"] > t1 and x["cap"] is not None and x["car"] > (car_pre or 0.0) + 50.0] check(f"{name}: Solar's change began at {tb}; the house heads over at " f"{t1}; the cut at {first.get('t')} is {first.get('cap')} A (the " f"change ends at its 0 A); no select after it ({sel[:2]}), no " f"non-zero write ({nz[:3]}), the car never above its " f"{car_pre} W before the cut ({more[:3]})", tb is not None and first.get("cap") == 0.0 and first.get("t", 1e9) <= t1 + 1 and not sel and not nz and not more) never(name, r) # =========================================================================== # print("\n1. T34 (iv), (v): A CUT DURING SOLAR'S OWN CHANGE ENDS IT (PM R1)") # =========================================================================== # # (iv) 1 -> 3: the reviewer's repro (review of 5759e9d, Major 1). kw = dict(dur=700, first="car", phases=1, socs={"a": 10.0, "b": 10.0}, opts={"ev_phases": "auto"}, beside=True) tb, r = own_change_run(const(9280.0), kw, 11500.0, lambda log: zero_before_select(log, 3)) judge("T34 (iv) 1 -> 3, late 0 A read-back", tb, r) # (v) 3 -> 1: Solar runs 3 phases (up at about 300 s), the sun falls to a # target under 4 kW at 700 s, the change down comes after the 300 s dwell # and the 600 s phase gap; the house heads over during it. sun5 = step_fn((700, 900.0 + 3500.0 + 100.0), base=9280.0) kw = dict(dur=1200, first="car", phases=1, socs={"a": 10.0, "b": 10.0}, opts={"ev_phases": "auto"}, beside=True) tb, r = own_change_run(sun5, kw, 11500.0, lambda log: zero_before_select(log, 1)) judge("T34 (v) 3 -> 1, late 0 A read-back", tb, r) # =========================================================================== # print("\n2. N6 / P27: A REFUSED CLOSE RETRIED UNDER A CUT (PM R2)") # =========================================================================== # UTC = datetime(2026, 11, 23, 12, 0, tzinfo=timezone.utc) class Drv: """A charger whose read-back follows at once; `refuse` makes it refuse a current write.""" polls = () def __init__(self): self.a, self.n, self.refuse = 0.0, 1, False async def write_current(self, a, **kw): if self.refuse: return False self.a = float(a) return True async def write_phases(self, n): self.n = n return True def rd(a, n, e): return CH.ChargerReading( available=True, state="C" if a > 0 else "B", connected=True, charging=a > 0, power_w=a * 230.0 * n, energy_kwh=e, current_a=tuple(a if i < n else 0.0 for i in range(3)), setpoint_a=a, allowed_a=a, phases_allowed=n) async def refused_close(cap): """Solar's own 1 -> 3 change; its closing write is refused; then a cut of `cap` A comes before the retry 5 s later. Returns (the refused close, the writes after the cut).""" w, tr, drv = carmode.SolarWriter(), CH.CarTracker(), Drv() e = [4000.0] sun = carmode.SunInputs(target_w=9180.0, auto=True, spare_w=9280.0, margin_w=100.0) refused, t = None, 0.0 async def step(t, cut=None): r = rd(drv.a, drv.n, e[0]) e[0] += drv.a * 230.0 * drv.n / 3.6e6 tr.observe(r, t, UTC, "2026-11-23") w.cut_a = cut await w.step(drv, r, mode=carmode.SOLAR, sun=sun, clamp=16.0, now=t, tracker=tr, writing=True, status=CH.CHARGING, clock=lambda: t) while t < 900.0 and refused is None: q = w.seq drv.refuse = bool(q is not None and q.get("stage") == "settle" and drv.n == 3) n0 = len(w.log) await step(t) bad = [x for x in w.log[n0:] if x[0] == "current" and not x[3] and x[1] > 0.0] if bad: refused = bad[0] t += 1.0 drv.refuse = False n1 = len(w.log) for _ in range(12): await step(t, cut=cap) t += 1.0 return refused, [(x[2], x[1]) for x in w.log[n1:] if x[0] == "current"], drv.a refused, later, _end = asyncio.run(refused_close(6.0)) check(f"N6/P27: Solar's closing write {refused} is refused; a cut to 6 A " f"comes before its retry: the retry is never above 6 A ({later})", refused is not None and refused[1] > 6.0 and bool(later) and all(a <= 6.0 for _t, a in later)) # Fix round 3 (re-review Major 1): a cut under 6 A before the retry ends the # change in the writer (carmode.py, `plan.a < MIN_A` in the change): no # write after the cut at all, and the charger stays at 0 A. for cap in (3.0, 0.0): refused, later, end = asyncio.run(refused_close(cap)) check(f"N6/P27 (a) [cut {cap:.0f} A]: Solar's closing write {refused} is " f"refused; the cut comes before its retry: no write after it " f"({later}), the charger ends at {end} A", refused is not None and refused[1] > 6.0 and not later and end == 0.0) # (b) The same at controller level (the re-reviewer's row B): Solar 16 A on # 1 phase, auto, sun 9280 W, both batteries switched off in battery modes. # Solar's own 1 -> 3 change; its close is refused (a 2 s "error" window); # the house steps to 18 kW one second after the window, before the retry # (5 s after the close). Expected: a 0 A cut at once, no retry, no car power # under the cut. kw = dict(dur=700, first="car", phases=1, socs={"a": 10.0, "b": 10.0}, opts={"ev_phases": "auto"}, beside=True) ev = {0: both(lag(0.0), _mode("ab", False))} r0 = drive(const(900.0), const(9280.0), **dict(kw, events=ev)) log0 = r0["c"].car_solar.log sel = [t for k, a, t, ok in log0 if k == "phases" and a == 3] close = [(t, a) for k, a, t, ok in log0 if k == "current" and a > 0.0 and sel and t > sel[0]] tc = close[0][0] if close else None if tc is not None: sim = TSim(setpoint_a=0, windows=[(tc - 1.0, tc + 1.0, "error")]) r = drive(step_fn((tc + 2, 18000.0), base=900.0), const(9280.0), **dict(kw, events=ev, sim=sim, dur=tc + 200)) log = r["c"].car_solar.log tried = [(t, a, ok) for k, a, t, ok in log if k == "current" and t >= tc - 1] retry = [(t, a) for t, a, ok in tried if a > 0.0 and t >= tc + 2] rows = r["rec"].rows caps = [(x["t"], x["cap"]) for x in rows if x["t"] >= tc + 2 and x["cap"] is not None] car_hi = [(x["t"], x["car"]) for x in rows if x["t"] > tc + 2 and x["cap"] is not None and (x["car"] or 0) > 50.0] ok_b = (bool(caps) and caps[0] == (tc + 2, 0.0) and not retry and not car_hi) else: tried, retry, caps, car_hi, ok_b, r = [], [], [], [], False, None check(f"N6/P27 (b): Solar's change selects at {sel[:1]}, its close at {tc} " f"is refused, the house is at 18 kW from {tc and tc + 2}: the cut " f"{caps[:1]} (0 A at once), no non-zero retry after it ({retry[:2]}), " f"no car power under it ({car_hi[:2]}); writes {tried[:5]}", ok_b) if r is not None: never("N6/P27 (b)", r) # =========================================================================== # print("\n3. N9: A STANDING CUT SURVIVES A STALE CYCLE") # =========================================================================== # r = shape("C", dur=1000) c = r["c"] st = c._cut cap0 = st.get("cap") t = c.car_now() blind = dataclasses.replace(c.peak_guard, blind="meter gap") c.car_solar.cut_a = None c._car_cut_tick(c._peak_proj_real, blind, AIM, t) a_blind = c.car_solar.cut_a c.car_solar.cut_a = None c._car_cut_meter_fresh = lambda: False c._car_cut_tick(c._peak_proj_real, c.peak_guard, AIM, t) a_stale = c.car_solar.cut_a check(f"N9: a cut of {cap0} A stands; a cycle with a blind guard gives the " f"writer {a_blind} A, one with a stale meter {a_stale} A: the cap " f"stays", cap0 is not None and a_blind == cap0 and a_stale == cap0) # =========================================================================== # print("\n4. PM R1: A STANDING PARTIAL CUT GOES TO 0 A IF A CHANGE IS UNDER WAY") # =========================================================================== # # Fix round 3 (re-review Minor): `_car_cut_tick` itself. A partial cut of # 8 A stands, Solar's plan has decided a phase change (`plan.switch`) and a # cut is due again (the car draws, the projection is over the aim): the # standing cap goes to 0 A, which ends the change at its 0 A (R1). r = shape("C", dur=950) c = r["c"] w = c.car_solar t = c.car_now() c._car_cut_meter_fresh = lambda: True left = 900.0 - 300.0 proj = dataclasses.replace(c._peak_proj_real, elapsed_s=300.0, projected_w=AIM + 1000.0 * left / 900.0) st = c._cut = c._cut_fresh(proj.block_start) st.update(cap=8.0, ex=1e9, car0=6900.0, base=10.0, cuts=1, at=t, since=t) w.plan.switch = True c._car_cut_tick(proj, c.peak_guard, AIM, t) cap_switch = c._cut["cap"] w.plan.switch = False st = c._cut = c._cut_fresh(proj.block_start) st.update(cap=8.0, ex=1e9, car0=6900.0, base=10.0, cuts=1, at=t, since=t) c._car_cut_tick(proj, c.peak_guard, AIM, t) cap_plain = c._cut["cap"] check(f"R1 standing cut: a cut of 8 A stands and a cut is due again; with " f"Solar's own change decided it becomes {cap_switch} A, without one " f"it stays {cap_plain} A", cap_switch == 0.0 and cap_plain == 8.0) tb_ = LOG.tracebacks(n_log0) check(f"N11: no traceback in this file's runs ({tb_[:1]})", not tb_) print(f"\n{'FAILED: ' + str(len(fails)) if fails else 'ALL PASSED'}") sys.exit(1 if fails else 0)