"""EV-60: Solar never passes EV-54's cap of MAX_TRIES refused cut tries per quarter key (the phase change's 0 A and the capped close included), and a Solar press during the close retries gives the value MAX_TRIES tries. `python3 -B test_ev60.py` Rows T1-T24 (with T1b, T2b, T2c, T3b, T3c, T8b, T21b) and N1-N14 of reports/EV-60-test-plan.md. Here: T1-T11, T14 (writer level), T16-T22, T24 (the shutdown rows against `Base60`), and the source checks of T15, T23 and N7, N10, N11. Carried by the other suites, green: T12 (test_ev54*), T13 (test_ev59 Manual rows, test_ev56, test_ev28, test_ev15, test_ev04), T15 (test_ev56 T12, "T20 T12 [R]"), T23. Writer level: `SolarWriter` on a stub driver, a stub tracker and a stub reading; time is the 1 s step counter, never wall time. R = the answer False, X = it raises. `Base60` is 2e09622's Solar (the three methods this ticket changes, restored); it is the red side of every row (mutant M1). Mutating a module this file grades? Read MUTATION.md first (purge __pycache__). """ import asyncio import hashlib import inspect import logging import os import sys HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.join(HERE, "tools")) from app import carmode as CM # noqa: E402 fails = [] CLOCK = {"t": 0} LOG = [] REF_S = "until you press Solar: CHARGER_REFUSED." Q3W = "tries again next quarter: CHARGER_REFUSED." CUTDBG = "The peak cut write failed" REC = "The car charger step failed" MANUAL_SHA = "284ce1a94bfb7a6335f224a29bddc4e0b80c36af78b5c7907031c511a6a9eaa8" class Cap(logging.Handler): def emit(self, rec): LOG.append((CLOCK["t"], rec.levelname, rec.getMessage())) logging.getLogger("goodwe").addHandler(Cap()) logging.getLogger("goodwe").setLevel(logging.DEBUG) def check(name, cond): print(f" {'ok ' if cond else 'FAIL'} {name}") if not cond: fails.append(name) def near(got, want, tol=1.0): return len(got) == len(want) and all(abs(g - w) <= tol for g, w in zip(got, want)) class Rd: def __init__(self, a, ph=1, power=None, state="C"): self.available = True self.allowed_a = self.setpoint_a = a self.phases_allowed = ph self.power_w = power self.state = state self.error = False self.charging = True self.current_a = () self.station_a = None class Trk: obs_at = None def __init__(self): self.notes = [] def begin_write(self): pass def end_write(self, *_): pass def note_write(self, now, was, a, ok, polls=()): self.notes.append((now, a, ok)) def stuck(self, now): return False class Drv: def __init__(self, cur, answer, ph=1, sel=True): self.cur, self.ph, self.answer, self.sel = cur, ph, answer, sel self.calls, self.now, self.polls = [], 0.0, () self.phases_log = [] async def write_current(self, a, **kw): self.calls.append((self.now, float(a))) r = self.answer(float(a), len(self.calls)) if r == "raise": raise RuntimeError("HA call error") if r: self.cur = float(a) return bool(r) async def write_phases(self, n): self.phases_log.append((self.now, n, self.cur)) if self.sel: self.ph = n return self.sel def _clock(self): return self.now async def _sleep(self, s): self.now += s class Base60(CM.SolarWriter): """2e09622's Solar: the three things EV-60 changes, as they were.""" async def _begin_solar(self, drv, r, cur, n, now, tracker) -> None: self.phase_done_at = None if not (cur is not None and cur <= CM.TOL_A and self.sent_a == 0.0 and self.taken): if not await self._write(drv, 0.0, cur, now, tracker): self.plan.end_switch(False) return self.seq = {"stage": "zero", "t0": now, "n": n, "tries": 0, "prev": None, "from": r.phases_allowed} async def _advance(self, *a, **k): return await CM.ManualWriter._advance(self, *a, **k) def _close_end(self, now) -> None: self._failed(now) def solar_writer(cur, cls=None): w = (cls or CM.SolarWriter)() w.engaged, w.mode_was = True, CM.SOLAR w.fresh_start = w.restart = False w.was_available = w._seen = True w.sent_a, w.taken, w.last_a = cur, True, cur w.plan.a, w.plan.n = cur, 1 def plan_step(sun, now, clamp, n, gap): """The plan's own rule, the part that matters here: a standing cap lowers its current (`SolarPlan.step` -> `_cut`), nothing else moves.""" c = w.cut_a if c is not None and c >= CM.CH.MIN_A and w.plan.a > c + 1e-9: w.plan._cut(c) w._plan_step = plan_step return w def set_cap(w, a): w.cut_a, w.cut_on = a, a is not None LOOP = asyncio.new_event_loop() ALL = [] # every writer-level run of the design class Res: pass def state(w, drv): q = w.seq return dict(cf=w.cut_fails, f=w.fails, gu=w.gave_up, seq=None if q is None else (q["stage"], q["tries"]), sw=w.plan.switch, n=len(drv.calls), re=w.reapply, la=w.last_a, rv=w.rev_applied, pa=w.plan.a, pn=w.plan.n, warned=w.cut_warned) def world(kind, until, *, start=0, setup=None, pre=None, post=None, take=None, cls=None, cur=8.0, sun=None, avail=None): """One writer-level run from `start` to `until` (both included). `take` (a, drv, w) -> True: the charger takes the write; the others are refused (R) or raise (X) as `kind`'s characters say, one per refused write, the last repeated. `pre` / `post`: (w, drv, t) before / after each step.""" del LOG[:] r = Res() r.kind, r.tries, r.viol, r.snap, r.refused = kind, [], [], {}, 0 r.ended, r.noncut, r.cap_ = None, 0, CM.MAX_TRIES w = solar_writer(cur, cls) trk = Trk() def answer(a, n): cut = w.cut_a if cut is not None and a > cut + CM.TOL_A: r.viol.append((drv.now, a)) if 0.0 < a < CM.CH.MIN_A - 1e-9: r.viol.append((drv.now, a)) ok = take(a, drv, w) if take else (a == 0.0 and w.cut_a is None) if ok: return True c = kind[min(r.refused, len(kind) - 1)] r.refused += 1 if cut is not None and a <= cut + CM.TOL_A: r.tries.append(int(drv.now)) else: r.noncut += 1 return "raise" if c == "X" else False drv = Drv(cur, answer) r.w, r.drv = w, drv if setup: setup(w, drv) for t in range(start, until + 1): drv.now = float(t) CLOCK["t"] = t if pre: pre(w, drv, t) w.cut_quarter(int(t // 900)) rd = Rd(drv.cur, drv.ph, power=(0.0 if drv.cur == 0 else 1840.0)) if avail is not None and not avail(t): rd.available = False had = w.seq is not None s = sun(t) if sun else CM.SunInputs(target_w=2000.0) LOOP.run_until_complete(w.step( drv, rd, mode=CM.SOLAR, sun=s, clamp=16.0, now=float(t), tracker=trk, writing=True, status="charging")) if had and w.seq is None and r.ended is None: r.ended = t r.snap[t] = state(w, drv) if post: post(w, drv, t) r.log = list(LOG) r.errs = [m for _t, lv, m in LOG if lv == "ERROR"] r.refs = [t for t, lv, m in LOG if lv == "WARNING" and REF_S in m] r.q3w = [t for t, lv, m in LOG if lv == "WARNING" and Q3W in m] r.cutdbg = [t for t, lv, m in LOG if CUTDBG in m] r.nz = [(int(t), a) for t, a in drv.calls if a > 0] r.zeros = [int(t) for t, a in drv.calls if a == 0.0] if (cls or CM.SolarWriter) is CM.SolarWriter: ALL.append(r) return r def per_key(tries): out = {} for t in tries: out[t // 900] = out.get(t // 900, 0) + 1 return out # ------------------------------------------------------------ the worlds def route_a(kind, until=899, plan_a=8.0, take=None, cls=None, post=None, pre_extra=None): """EV-56 c4c: 0 A cut tries by `_put` at 0, 60, 120; the cut lifts at 121 (drop); the plan decides 1 -> 3; a 6 A cap comes back.""" def pre(w, d, t): if t == 0: set_cap(w, 0.0) w.plan.a = 0.0 if t == 121: set_cap(w, None) w.plan.a = 8.0 if pre_extra: pre_extra(w, d, t) def post_(w, d, t): if t == 121: w.plan._set(8.0, 121.0, 3) set_cap(w, 6.0) w.plan.a = plan_a if post: post(w, d, t) return world(kind, until, pre=pre, post=post_, cls=cls, take=take or (lambda a, d, w: False)) def route_b(kind, put_tries=3, until=898, cls=None, take_after=False): """EV-56 c4b: `put_tries` refused 0 A cut tries by `_put`; the cut lifts (drop); the plan decides 1 -> 3; the change's 0 A and select are taken; a 6 A cap comes in settle and the capped close is refused.""" t_lift = 60 * put_tries ph = {"all": True} def take(a, d, w): return (not ph["all"]) and a == 0.0 and w.cut_a is None def pre(w, d, t): if t == 0: set_cap(w, 0.0) w.plan.a = 0.0 if t == t_lift: set_cap(w, None) ph["all"] = False w.plan.a = 8.0 def post(w, d, t): if t == t_lift: w.plan._set(8.0, float(t), 3) elif t > t_lift and w.seq is not None \ and w.seq.get("stage") == "settle" and w.cut_a is None: set_cap(w, 6.0) return world(kind, until, pre=pre, post=post, take=take, cls=cls) def one_cut(w, d, t): """A cut try of 0 A refused at 100; the cut lifts at 120 (drop); a press at 125 clears `fail_at` (F3) so a change can begin at 130 / 140.""" if t == 100: set_cap(w, 0.0) w.plan.a = 0.0 if t == 120: set_cap(w, None) w.plan.a = 8.0 if t == 125: w.user_changed() def cap_in_settle(at=None): def post(w, d, t): if w.seq is not None and w.seq.get("stage") == "settle" \ and w.cut_a is None and (at is None or t >= at): set_cap(w, 6.0) return post def t2b(kind, begin=140, until=240, extra_pre=None, take=None, cls=None, avail=None, sun=None): def pre(w, d, t): one_cut(w, d, t) if t == begin: w.plan._set(8.0, float(begin), 3) if extra_pre: extra_pre(w, d, t) return world(kind, until, start=90, pre=pre, post=cap_in_settle(), take=take, cls=cls, avail=avail, sun=sun) def t2c(kind, until=240, cls=None): """Q6: close 1 (8 A, no cap) refused; the cap arrives at 143; close 2 is a cut try within RETRY_S of cut_fail_at 100.""" def pre(w, d, t): one_cut(w, d, t) if t == 130: w.plan._set(8.0, 130.0, 3) if t == 143: set_cap(w, 6.0) return world(kind, until, start=90, pre=pre, cls=cls, take=lambda a, d, w: a == 0.0 and d.now >= 120) def t3(kind, until=899, cls=None, extra_pre=None): """Route (a) then (b), one key: a 6 A cap stands; the change's 0 A is refused at 0 and taken at 60; the capped close is refused.""" def pre(w, d, t): if t == 0: set_cap(w, 6.0) w.plan._set(8.0, 0.0, 3) if t == 60 and not w.plan.switch: w.plan._set(8.0, 60.0, 3) if extra_pre: extra_pre(w, d, t) return world(kind, until, pre=pre, cls=cls, take=lambda a, d, w: a == 0.0 and d.now >= 60) def sp3(kind, press=None, until=299, cls=None): def pre(w, d, t): if press is not None and t == press: w.user_changed() return world(kind, until, start=1, pre=pre, cls=cls, setup=lambda w, d: w.plan._set(8.0, 0.0, 3), take=lambda a, d, w: a == 0.0) # =========================================================================== # print("1. ROUTE (a): THE PHASE CHANGE'S 0 A (T1, T1b, T4, T5)") # =========================================================================== # RA = {k: route_a(k) for k in "RX"} for k in "RX": r = RA[k] after = [(t, a) for t, a in r.drv.calls if t > 121] check(f"T1 [{k}]: cut tries [0, 60, 120], cut_fails 3, no write at all in " f"122-899 ({r.tries}, {r.w.cut_fails}, {after[:3]}), seq None, " f"switch True, no give-up, no select, no ERROR record", r.tries == [0, 60, 120] and r.w.cut_fails == 3 and not after and r.w.seq is None and r.w.plan.switch and not r.w.gave_up and not r.drv.phases_log and not r.errs) check("T1: X equals R (calls, cut_fails, fails, seq, switch)", RA["X"].drv.calls == RA["R"].drv.calls and RA["X"].snap[899] == RA["R"].snap[899]) r = RA["R"] flat = {tuple(sorted((k, str(v)) for k, v in r.snap[t].items() if k != "n")) for t in range(122, 900)} check("T4: the gated steps 122-899 change nothing: cut_fails, fails, gave_up, " "seq, switch the same every step; the change waits (switch True), " "end_switch never called by the gate", len(flat) == 1 and r.snap[899]["sw"] and not r.snap[899]["gu"] and not r.refs and len(r.q3w) == 1) check(f"T10: the cut's one CHARGER_REFUSED, in the step cut_fails reached 3 " f"({r.q3w}); REF_S never from cut tries ({r.refs})", r.q3w == [120] and not r.refs) def t1b(kind, cls=None): def pre(w, d, t): if t == 0: set_cap(w, 0.0) w.plan.a = 0.0 if t == 30: set_cap(w, None) w.plan.a = 8.0 if t == 31: w.plan._set(8.0, 31.0, 3) if t == 32: set_cap(w, 6.0) if t == 33: w.user_changed() return world(kind, 119, pre=pre, cls=cls, take=lambda a, d, w: a == 0.0 and d.now >= 60) for k in "RX": r = t1b(k) fire = [t for t in r.zeros] check(f"T1b [{k}] (F3): no 0 A in 31-59 although the press cleared " f"fail_at; 0 A at 60 ({fire}); cut_fails 1 after the press " f"({r.snap[59]['cf']}); then select and the capped closes, 3 " f"cut tries in all ({r.tries}), no 3rd close", not [t for t in fire if 31 <= t <= 59] and 60 in fire and r.snap[59]["cf"] == 1 and len(r.tries) == 3 and r.tries[0] == 0 and near(r.tries[1:], [71, 76], 1) and r.w.cut_fails == 3 and not r.w.gave_up and not r.errs) # T5: the next key gives control back for k in "R": # (a) the cap stands, the charger takes from 900 r = route_a(k, until=1500, plan_a=6.0, take=lambda a, d, w: d.now >= 900) z = [t for t in r.zeros if t >= 900] check(f"T5a: at key 1 cut_fails is 0 and Solar controls again: 0 A at 900 " f"({z[:1]}), 6 A close, plan.n 3, seq None, cut_warned False " f"({r.snap[900]['cf']}, {r.w.plan.n}, {r.w.cut_warned})", r.snap[899]["cf"] == 3 and r.snap[900]["cf"] == 0 and z and abs(z[0] - 900) <= 1 and r.w.plan.n == 3 and r.w.seq is None and not r.w.cut_warned and any(a == 6.0 and t > 900 for t, a in r.drv.calls) and not r.w.gave_up) # (c) the charger still refuses r = route_a(k, until=1500, plan_a=6.0) k1 = [t for t in r.tries if t >= 900] check(f"T5c: charger still refuses: exactly 3 refused cut tries in key 1, " f">= 60 s apart, then a wait ({k1}); gave_up never; Q3W once per " f"reaching ({r.q3w}); no REF_S ({r.refs})", len(k1) == 3 and all(b - a >= 60 for a, b in zip(k1, k1[1:])) and not r.w.gave_up and not r.refs and r.q3w == [120]) # T5b: route (b)'s world, the cap lifts at 900 and the plan decides a change ph5 = {"all": True} def t5b_pre(w, d, t): if t == 0: set_cap(w, 0.0) w.plan.a = 0.0 if t == 180: set_cap(w, None) ph5["all"] = False w.plan.a = 8.0 if t == 900: set_cap(w, None) w.plan.a = 8.0 w.plan.n = 3 w.plan._set(8.0, 900.0, 1) # 3 -> 1 phase, no cap def t5b_post(w, d, t): if t == 180: w.plan._set(8.0, 180.0, 3) elif 180 < t < 900 and w.seq is not None \ and w.seq.get("stage") == "settle" and w.cut_a is None: set_cap(w, 6.0) r = world("R", 1000, pre=t5b_pre, post=t5b_post, take=lambda a, d, w: d.now >= 900 or ( not ph5["all"] and a == 0.0 and w.cut_a is None)) c900 = [(int(t), a) for t, a in r.drv.calls if t >= 900] check(f"T5b: route (b) tries used up in key 0 (cut_fails {r.snap[899]['cf']}); " f"at key 1 the cut is lifted and the phase change runs with no cut " f"try: the 0 A already stands, the select, the close at the plan's " f"value 8 A at ~911 ({c900}); cut_fails {r.snap[900]['cf']}, no " f"refused cut try in key 1 ({[t for t in r.tries if t >= 900]}), " f"plan.n {r.w.plan.n}, seq None, no give-up", r.snap[899]["cf"] == 3 and r.snap[900]["cf"] == 0 and len(c900) == 1 and abs(c900[0][0] - 911) <= 1 and c900[0][1] == 8.0 and not [t for t in r.tries if t >= 900] and r.w.plan.n == 1 and not r.w.plan.switch and r.w.seq is None and not r.w.gave_up and len(r.drv.phases_log) == 2) # T11a: no cap any more: not a cut try r = route_a("R", until=420, plan_a=8.0, take=lambda a, d, w: a == 0.0 and w.cut_a is None or d.now >= 300, pre_extra=lambda w, d, t: ( (set_cap(w, None), setattr(w.plan, "a", 8.0)) if t == 299 else None)) c300 = [(int(t), a) for t, a in r.drv.calls if t >= 299] check(f"T11a: cut_fails 3, the cap lifted: the pending change's 0 A at 300, " f"the select and the close at the plan's value 8 A, not cut tries " f"({c300}); one tries list {r.tries}", c300 and abs(c300[0][0] - 300) <= 1 and c300[0][1] == 0.0 and len(c300) == 2 and c300[1][1] == 8.0 and len(r.drv.phases_log) == 1 and r.tries == [0, 60, 120] and r.w.plan.n == 3) # =========================================================================== # print("\n2. ROUTE (b): THE CAPPED CLOSE (T2, T2b, T2c, T3, T6, T21)") # =========================================================================== # RB = {k: route_b(k) for k in "RX"} for k in "RX": r = RB[k] sixes = [t for t, a in r.nz if a == 6.0] e = r.snap[r.ended] if r.ended else {} check(f"T2 [{k}]: cut tries [0, 60, 120], cut_fails 3, no close write " f"({r.tries}, {r.w.cut_fails}, {sixes}); the sequence ends at " f"192 ({r.ended}); no non-zero write while the cap stands", r.tries == [0, 60, 120] and r.w.cut_fails == 3 and not sixes and r.ended is not None and abs(r.ended - 192) <= 1 and not r.nz and not r.errs) r = RB["R"] e, e0 = r.snap[r.ended], r.snap[r.ended - 1] check(f"T6: the capped close end: seq None, reapply, last_a and rev_applied " f"None, end_switch(False): switch False, plan back at its value before " f"the change (a 8, n 1), no write in that step, last write 0 A, " f"gave_up False, cut_fails 3, no extra _failed ({e})", e["seq"] is None and e["re"] is True and e["la"] is None and e["rv"] is None and not e["sw"] and e["pa"] == 8.0 and e["pn"] == 1 and e["n"] == e0["n"] and r.drv.calls[-1][1] == 0.0 and not e["gu"] and e["cf"] == 3 and e["f"] == e0["f"]) check("T2: X equals R", RB["X"].drv.calls == RB["R"].drv.calls and RB["X"].ended == RB["R"].ended) for k in "RX": r = t2b(k) wait = range(151, 160) calls_wait = [t for t, a in r.nz if 151 <= t <= 159] closes = [t for t, a in r.nz if a == 6.0] fa = {r.snap[t]["f"] for t in wait} check(f"T2b [{k}] (Q5, T22): 151-159 no write, seq in settle, the car at " f"0 A, cut_fails 1, fails unchanged, no give-up, no REF; close 1 " f"at 160, close 2 at 165 ({closes}); cut_fails 3, one Q3W at 165 " f"({r.q3w}); the end 5 s later (T6 state) ({r.ended})", not calls_wait and all(r.snap[t]["seq"] and r.snap[t]["seq"][0] == "settle" and r.snap[t]["cf"] == 1 and not r.snap[t]["gu"] for t in wait) and len(fa) == 1 and r.drv.cur == 0.0 and near(closes, [160, 165], 1) and r.w.cut_fails == 3 and near(r.q3w, [165], 1) and not r.refs and not r.w.gave_up and r.ended and abs(r.ended - 170) <= 1 and r.snap[r.ended]["re"] and not r.snap[r.ended]["sw"] and r.snap[r.ended]["n"] == r.snap[r.ended - 1]["n"] and r.snap[r.ended]["cf"] == 3 and not r.errs) for k in "RX": r = t2c(k) w130 = [(int(t), a) for t, a in r.drv.calls if t >= 130] check(f"T2c [{k}] (Q6): 0 A 130, 8 A close 1 ~141 (not a cut try), the cap " f"at 143; 146-159 no write, no try counted (cut_fails 1, fails 1), " f"seq in settle, no give-up, no REF; close 2 (6 A) at 160, close " f"3 at 165 ({w130}); cut_fails 3, one Q3W at 165 ({r.q3w}); the " f"end on its 3 tries, no 4th close, no extra _failed", len(w130) == 4 and abs(w130[1][0] - 141) <= 1 and w130[1][1] == 8.0 and near([x for x, _a in w130[2:]], [160, 165], 1) and all(a == 6.0 for _x, a in w130[2:]) and all(r.snap[t]["cf"] == 1 and r.snap[t]["f"] == 1 and r.snap[t]["seq"][0] == "settle" and r.snap[t]["n"] == r.snap[146]["n"] for t in range(146, 160)) and r.w.cut_fails == 3 and near(r.q3w, [165], 1) and not r.refs and not r.w.gave_up and r.w.seq is None and r.w.reapply and len(r.errs) <= 1) # X: the 8 A close is no cut try (G1) for k in "RX": r = t3(k) c1 = r.tries[1] if len(r.tries) > 1 else None check(f"T3 [{k}] (Q1): refused cut tries [0, c1, c1+5] = 3 ({r.tries}); " f"no close at c1+10; the T6 end; cut_fails 3; one Q3W in the c1+5 " f"step ({r.q3w})", len(r.tries) == 3 and r.tries[0] == 0 and c1 >= 60 and r.tries[2] == c1 + 5 and r.w.cut_fails == 3 and r.q3w == [c1 + 5] and r.ended is not None and abs(r.ended - (c1 + 10)) <= 1 and r.w.seq is None and r.w.reapply and not r.w.plan.switch and r.drv.calls[-1][1] == 6.0 and not r.w.gave_up and not r.errs) r3 = t3("R", extra_pre=lambda w, d, t: ( (setattr(w.plan, "n", 3), w.plan._set(8.0, 200.0, 1)) if t == 200 else None)) # the plan on 3 phases decides back to 1 after = [(int(t), a) for t, a in r3.drv.calls if t > 81] check(f"T3b (Q1): route (b) then (a): cut_fails 3 in key 0; a new switch " f"under the cap writes no 0 A until key 1 ({after}); it waits " f"(switch True), no give-up", not after and r3.w.cut_fails == 3 and r3.w.plan.switch and not r3.w.gave_up and r3.w.seq is None) flat = {tuple(sorted((k, str(v)) for k, v in r3.snap[t].items() if k != "n")) for t in range(201, 900)} check("T4: T3b's gated steps change nothing, no REF_S, one Q3W", len(flat) == 1 and not r3.refs and len(r3.q3w) == 1) # T3c: mixed answers base3 = t3("R") mix = t3("XRX") check(f"T3c: X, R, X in that order: the same times and counts as R " f"({mix.tries} vs {base3.tries}); each raise one try; one CUTDBG per " f"raised cut try ({len(mix.cutdbg)}); 0 ERROR records", mix.tries == base3.tries and mix.w.cut_fails == 3 and len(mix.cutdbg) == 2 and not mix.errs and mix.drv.calls == base3.drv.calls) mixb = t2b("XR") bb = t2b("R") check(f"T3c: T2b with X then R: same calls and counts as R; one CUTDBG " f"({len(mixb.cutdbg)})", mixb.drv.calls == bb.drv.calls and mixb.w.cut_fails == 3 and len(mixb.cutdbg) == 1 and not mixb.errs) # T10 over the routes for nm, r, at in (("T2b", t2b("R"), 165), ("T2c", t2c("R"), 165), ("T3", t3("R"), None)): check(f"T10 [{nm}]: Q3W exactly once ({r.q3w}), none in a gated or " f"waiting step, REF_S never ({r.refs})", len(r.q3w) == 1 and not r.refs and (at is None or abs(r.q3w[0] - at) <= 1)) # T21: the key rolls between the closes def pre_roll(fail_at, begin): def setup(w, d): w.cut_key, w.cut_fails, w.cut_fail_at = 0, 2, float(fail_at) def pre(w, d, t): if t == begin: w.plan._set(8.0, float(begin), 3) return setup, pre for k in "RX": setup, pre = pre_roll(800, 884) r = world(k, 960, start=870, setup=setup, pre=pre, post=cap_in_settle()) cl = [t for t, a in r.nz if a == 6.0] key1 = [t for t in r.tries if t >= 900] check(f"T21 [{k}]: cut_fails 2, close 1 refused at 895 (key 0 ends at 3), " f"close 2 at 900 (key 1 fresh), close 3 at 905 ({cl}); key 1 holds " f"2 ({key1}, {r.w.cut_fails}); the sequence never has a 4th close; " f"gave_up False; no extra _failed ({r.snap[899]['cf']})", near(cl, [895, 900, 905], 1) and r.snap[899]["cf"] == 3 and r.w.cut_fails == 2 and len(key1) == 2 and not r.w.gave_up and r.w.seq is None and r.w.reapply and not r.errs) for k in "RX": setup, pre = pre_roll(870, 874) r = world(k, 990, start=870, setup=setup, pre=pre, post=cap_in_settle()) cl = [t for t, a in r.nz if a == 6.0] quiet = [t for t, a in r.nz if 880 <= t <= 929] check(f"T21b [{k}] (Q5, T22): 885-929 no write, waiting at 0 A, no try " f"counted, no give-up; key 0 stays 2; the close at 930 " f"(cut_fail_at + RETRY_S across the roll), 935, 940 ({cl}); key 1 " f"= 3, one Q3W at 940 ({r.q3w}); the end on its 3 tries", not quiet and r.snap[899]["cf"] == 2 and r.snap[900]["cf"] == 0 and all(not r.snap[t]["gu"] for t in range(885, 930)) and near(cl, [930, 935, 940], 1) and r.w.cut_fails == 3 and near(r.q3w, [940], 1) and r.w.seq is None and r.w.reapply and not r.w.gave_up and not r.errs) setup, pre = pre_roll(870, 874) r = world("R", 990, start=870, setup=setup, pre=pre, post=cap_in_settle(), take=lambda a, d, w: a == 0.0 and w.cut_a is None or d.now >= 930) check("T21b variant: the charger takes the close at 930: the change is done " f"(plan.n {r.w.plan.n}, switch {r.w.plan.switch})", r.w.plan.n == 3 and not r.w.plan.switch and r.w.seq is None and r.w.cut_fails == 0) # =========================================================================== # print("\n3. SOLAR'S CLOSE RETRIES AND THE PRESS (T7, T8, T8b, T9, T17)") # =========================================================================== # for k in "RX": r = sp3(k) check(f"T7 [{k}] (C5s, no press): 8 A at 12, 17, 22, fails 3, gave_up, " f"REF_S once at 22, no write after 22 ({[t for t, _a in r.nz]}, " f"{r.w.fails}, {r.refs})", [t for t, _a in r.nz] == [12, 17, 22] and r.w.fails == 3 and r.w.gave_up and r.refs == [22] and len(r.errs) <= 1) for k in "RX": r = sp3(k, press=13) check(f"T8 [{k}] (C5s, press at 13): 8 A at 12, 17, 22, 82; at 22 fails " f"2, no give-up, no REF; at 82 fails 3, gave_up, REF once " f"({[t for t, _a in r.nz]}, {r.snap[22]['f']}, {r.refs})", [t for t, _a in r.nz] == [12, 17, 22, 82] and r.snap[22]["f"] == 2 and not r.snap[22]["gu"] and r.snap[82]["f"] == 3 and r.snap[82]["gu"] and r.refs == [82] and len(r.errs) <= 2) # X: the press re-arms the ERROR line r = sp3("R", press=18) r2 = sp3("R", press=11) check(f"T8b: (a) press at 18: 12, 17, 22, 82, 142, REF at 142 only " f"({[t for t, _a in r.nz]}, {r.refs}); (b) press at 11: 12, 17, 22, " f"fails 3, REF at 22 ({[t for t, _a in r2.nz]}, {r2.w.fails}, " f"{r2.refs})", [t for t, _a in r.nz] == [12, 17, 22, 82, 142] and r.refs == [142] and [t for t, _a in r2.nz] == [12, 17, 22] and r2.w.fails == 3 and r2.refs == [22]) LOG14 = [] def t14c(cls=CM.SolarWriter): del LOG[:] w = solar_writer(8.0, cls) drv = Drv(0.0, lambda a, n: False) w.seq = {"stage": "settle", "t0": 0.0, "n": 3, "tries": 0, "prev": 8.0, "t1": 0.0} vals = {10: 8.0, 15: 7.0, 20: 6.0} async def main(): for t in range(10, 40): if w.seq is None: break drv.now = float(t) CLOCK["t"] = t await w._advance(drv, Rd(drv.cur, drv.ph, power=0.0), 0.0, float(t), Trk(), lambda q: vals.get(t, 5.0), 16.0, 1) LOOP.run_until_complete(main()) rf = [t for t, lv, m in LOG if lv == "WARNING" and REF_S in m] return [(int(t), a) for t, a in drv.calls], w.fails, w.gave_up, rf, w.seq S9 = t14c() check(f"T9: the close value moves 8, 7, 6 A at 10, 15, 20: fails 3, gave_up, " f"REF at 20, seq None ({S9})", S9 == ([(10, 8.0), (15, 7.0), (20, 6.0)], 3, True, [20], None)) setup, pre = pre_roll(0, 0) r = t2b("R", extra_pre=lambda w, d, t: w.user_changed() if t == 162 else None) cl = [t for t, a in r.nz if a == 6.0] check(f"T17: a Solar press between close 1 and close 2 resets neither " f"cut_fails nor the sequence's tries: closes {cl}, cut_fails " f"{r.w.cut_fails}, end as T6, no give-up", near(cl, [160, 165], 1) and r.w.cut_fails == 3 and not r.w.gave_up and r.ended and abs(r.ended - 170) <= 1 and r.snap[r.ended]["re"] and not r.snap[r.ended]["sw"]) # =========================================================================== # print("\n4. M1: THE BASE CLASS IS RED, A CHARGER THAT ANSWERS IS THE SAME") # =========================================================================== # r = route_a("R", cls=Base60) check(f"M1 self-check: Base60 is 2e09622 on route (a): cut tries " f"{r.tries} (base [0, 60, 120, 180]), cut_fails {r.w.cut_fails}", r.tries == [0, 60, 120, 180] and r.w.cut_fails == 4) r = route_b("R", cls=Base60, until=250) check(f"M1 self-check: Base60 on route (b): {r.tries} (base [0, 60, 120, " f"192, 197, 202]), cut_fails {r.w.cut_fails}", r.tries == [0, 60, 120, 192, 197, 202] and r.w.cut_fails == 7) r = sp3("R", cls=Base60) check(f"M1 self-check: Base60 on sp3: fails {r.w.fails} (base 4), REF " f"{r.refs}", r.w.fails == 4 and r.refs == [22]) # T14: a charger that answers: the same writes at the same times as base for nm, fn in (("route (a) world, the cap standing, all taken", lambda c: route_a("R", until=300, plan_a=6.0, cls=c, take=lambda a, d, w: True)), ("a standing cap, the change's 0 A and close taken", lambda c: world("R", 300, cls=c, setup=lambda w, d: ( set_cap(w, 6.0), w.plan._set(8.0, 0.0, 3)), take=lambda a_, d, w: True)), ("capped change in settle (T2b), the charger takes all", lambda c: t2b("R", until=240, cls=c, take=lambda a, d, w: True)), ("no cap, close at the plan's value (sp3 shape)", lambda c: world("R", 120, start=1, cls=c, setup=lambda w, d: w.plan._set(8.0, 0.0, 3), take=lambda a, d, w: True))): a, b = fn(CM.SolarWriter), fn(Base60) check(f"T14 (N8): {nm}: same writes at the same times and selects as " f"base ({a.drv.calls[:4]}); same plan, fails 0", a.drv.calls == b.drv.calls and a.drv.phases_log == b.drv.phases_log and a.w.fails == b.w.fails == 0 and a.w.plan.n == b.w.plan.n and a.w.cut_fails == b.w.cut_fails) # T11b: no cap ever, every write refused (non-cut): same as base a = world("R", 399, start=1, setup=lambda w, d: w.plan._set(8.0, 0.0, 3), take=lambda a_, d, w: False) b = world("R", 399, start=1, setup=lambda w, d: w.plan._set(8.0, 0.0, 3), take=lambda a_, d, w: False, cls=Base60) check(f"T11b: no cap, every write refused: same calls as base " f"({a.drv.calls[:3]}), same fails and give-up", a.drv.calls == b.drv.calls and a.w.fails == b.w.fails and a.w.gave_up == b.w.gave_up) def zero_way(cls): w = solar_writer(8.0, cls) drv = Drv(8.0, lambda a, n: False) set_cap(w, 6.0) w.cut_key, w.cut_fails = 0, 3 drv.now = 10.0 LOOP.run_until_complete(w._zero(drv, 8.0, 10.0, Trk())) return drv.calls, w.cut_fails, w.fails check("T11c: the way out's 0 A with the cap and cut_fails 3: as base", zero_way(CM.SolarWriter) == zero_way(Base60)) # =========================================================================== # print("\n5. T16, T18-T20, T24") # =========================================================================== # for cap_ in (2, 4): saved = CM.MAX_TRIES CM.MAX_TRIES = cap_ try: ra = route_a("R", until=899) r2b = t2b("R", until=260) r3_ = t3("R", until=300) r7 = sp3("R") finally: CM.MAX_TRIES = saved check(f"T16: MAX_TRIES {cap_}: cut tries per key == {cap_} on T1 " f"({len(ra.tries)}), T2b ({len(r2b.tries)}), T3 ({len(r3_.tries)}); " f"T7 tries == {cap_} then REF ({[t for t, _a in r7.nz]}, " f"{r7.refs})", len(ra.tries) == cap_ and len(r2b.tries) == cap_ and len(r3_.tries) == cap_ and len(r7.nz) == cap_ and len(r7.refs) == 1) w18 = CM.SolarWriter() check("T18: a new SolarWriter after a restart: cut_fails 0, cut_key None, " "cut_fail_at None, no counters carried", w18.cut_fails == 0 and w18.cut_key is None and w18.cut_fail_at is None and not w18.gave_up) # T19 (a): the meter goes silent in the Q5 wait: C17 r = t2b("R", sun=lambda t: CM.SunInputs(target_w=2000.0, silent=(t >= 155))) late = [(int(t), a) for t, a in r.drv.calls if t >= 150 and a > 0] check(f"T19a (C17): silent meter in the Q5 wait: the change ends at its 0 A " f"(seq None, switch False), no non-zero write ({late}), cut_fails 1", r.snap[155]["seq"] is None and not r.snap[155]["sw"] and not late and r.snap[155]["cf"] == 1 and not r.errs) # (b) a stale meter: no retry of the refused value (N7, N14) w19 = solar_writer(8.0) set_cap(w19, 6.0) w19.cut_blind, w19.refused_cut, w19.sent_a, w19.taken = True, 6.0, 6.0, False w19.sent_cut = True d19 = Drv(8.0, lambda a, n: False) d19.now = 500.0 LOOP.run_until_complete(w19._put(d19, 6.0, 8.0, 500.0, Trk())) check("T19b/N14: cut_blind with the refused 6 A: no retry on a stale meter", not d19.calls) # T20: the charger unavailable r = t2b("R", avail=lambda t: not (155 <= t <= 175)) down = [t for t, a in r.drv.calls if 155 <= t <= 175] check(f"T20a: unavailable 155-175: no write while down ({down}); the key's " f"cut tries stay at most 3 ({r.tries}); no ERROR", not down and len(r.tries) <= 3 and r.w.cut_fails <= 3 and not r.errs) r = world("R", 300, avail=lambda t: False, setup=lambda w, d: (set_cap(w, 0.0), setattr(w.plan, "a", 0.0))) check("T20b: no charger: 0 writes, no count", not r.drv.calls and r.w.cut_fails == 0) # T24: shutdown as base (EV-61 is out of scope) def rel(cls): w = solar_writer(8.0, cls) set_cap(w, 6.0) d = Drv(8.0, lambda a, n: False) d.now = 0.0 res = LOOP.run_until_complete(w.release(d, Rd(8.0), 0.0, Trk())) return d.calls, res, w.cut_fails, w.fails check(f"T24: release as base: 3 tries 5 s apart, not released ({rel(CM.SolarWriter)})", rel(CM.SolarWriter) == rel(Base60) and len(rel(CM.SolarWriter)[0]) == 3) r = route_a("R") d24 = Drv(8.0, lambda a, n: False) res24 = LOOP.run_until_complete(r.w.release(d24, Rd(8.0), 899.0, Trk())) check(f"T24: shutdown during T1's wait: no exception, release as base " f"({d24.calls})", res24 in (False, None) and len(d24.calls) in (0, 3)) # =========================================================================== # print("\n6. THE NEVERS OVER EVERY RUN, SOURCE CHECKS (N1-N14, T15, T23)") # =========================================================================== # worst = max((max(per_key(r.tries).values(), default=0) - r.cap_ for r in ALL), default=0) check(f"N1: never more than MAX_TRIES refused or raised cut tries in one " f"quarter key, over {len(ALL)} runs (worst: {worst} over the cap)", worst <= 0 and len(ALL) > 40) check("N2: no write above the cap or between 0 and 6 A, over every run", not [v for r in ALL for v in r.viol]) CUT_ONLY = [r for r in ALL if r.tries and r.w.cut_fails >= 1 and not r.noncut] check(f"N3: no give-up and no REF_S from cut tries, the gate or the Q5 wait " f"({len(CUT_ONLY)} cut runs)", len(CUT_ONLY) > 10 and not [1 for r in CUT_ONLY if r.w.gave_up or r.refs]) check("N5: no select while the car drew (0 A not taken), over every run", all(c == 0.0 for r in ALL for _t, _n, c in r.drv.phases_log)) check("N9: no exception out of a step or release in any run (every run " "completed), and no ERROR record on a cut try (G1)", not [e for r in CUT_ONLY for e in r.errs]) check("N7: ManualWriter's source is 2e09622's, byte for byte", hashlib.sha256(inspect.getsource(CM.ManualWriter).encode()) .hexdigest() == MANUAL_SHA) def tsrc(name): return open(os.path.join(HERE, name), encoding="utf-8").read() src = tsrc(os.path.join("app", "carmode.py")) check("N10 (write_phases and the notices untouched): one write_phases( and " "one drv.write_current( call, no new asyncio.sleep, create_task or " "_LOG.warning (1, 1, 1, 0, 10)", src.count("write_phases(") == 1 and src.count("drv.write_current(") == 1 and src.count("asyncio.sleep") == 1 and src.count("create_task") == 0 and src.count("_LOG.warning(") == 10) print() if fails: print(f"FAIL: {len(fails)} check(s)") for f in fails: print(" -", f[:200]) sys.exit(1) print("OK")