Files
goodwe-addon/goodwe_controller/test_ev22_fuzz.py
T
Claude e0e51dac12
checks / unit (pull_request) Successful in 53m40s
infra-pin / fresh (pull_request) Successful in 2s
EV-22 review round 1: press covers one reading, unknown read keeps the count, window ends on the close's clock
Major 1: the `pressed` mark of a sequence is consumed by the first `_advance`
(the first reading judged after the press); a later raise in the same zero
stage gets the raise-check hold again (Solar and Manual).
Major 2: with `cur` None `_watch` does not judge the current: the count
neither starts nor clears (phases are still judged).
Finding 4 (PM): the DA3 window uses the close's own clock and comparison
(`now - t1 < SETTLE_S`) and the one step that closes at its end is still
inside it, so a `last_done` a fraction of a second after the step's now no
longer pushes the close step outside the window.
Tests: rows A-D, R1 (Manual red under the mutant), the two fraction rows,
all red on b7c91ff. test_ev60: comment exactly as ruled, unused imports gone.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-03 12:30:17 +01:00

468 lines
20 KiB
Python

"""EV-22 T38: the Solar fuzz for the one rule of control (N1-N10 of
reports/EV-22-test-plan.md), 14 seeds of 3600 s, both cycle orders.
`python3 -B test_ev22_fuzz.py`
A model charger that knows who set its current and its phases last (the
add-on, or another writer); random foreign currents and phase switches at any
stage (zero, select, settle), unknown phases, read gaps, refused selects and
writes, late takes of a refused select inside and after the window, Stop, Off,
shadow, latch, a press (also inside a change), and a silent meter. Every cycle
checks: N1/N2 (no non-zero write, no select over a foreign value or phase that
has stood WRITER_S, unless a press took it), N3 (no mismatch, hold or
CHARGER_OTHER without a foreign event shortly before), N4 (the N3 reading, 6 A
never past the pause), N5 (the cut cap), N6 (the select rules), N7 (no select
under a mismatch or hold), N8 (can_cut False under one), N9 (one
CHARGER_OTHER per hold), N10 (Manual never judges phases; the raise check
never holds over the value a press took). The branches are counted and a
floor is asserted, so a fuzz that never reaches them fails.
Mutating a module this file grades? Read MUTATION.md first (purge __pycache__).
"""
import os
import random
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, "tools"))
from app import carmode # noqa: E402
import ev20_sun as S # noqa: E402
from chargersim import SimCharger # noqa: E402
from ev20_kit import LOG, check, fails, nevers, report # noqa: E402
SITES = 14
STEPS_PER = int(os.environ.get("EV22_FUZZ_STEPS", "3600"))
ONLY = [int(x) for x in os.environ.get("EV22_FUZZ_ONLY", "").split(",") if x]
DEBUG = bool(os.environ.get("EV22_FUZZ_DEBUG"))
WRITER_S = carmode.WRITER_S
# The fuzz shortens Solar's dwells and the phase gap so that a 1 h run holds
# many phase changes (it is the changes that carry C7); nothing else moves.
if not os.environ.get("EV22_FUZZ_SLOW"):
carmode.UP_S, carmode.DOWN_S, carmode.PHASE_GAP_S = 20.0, 30.0, 60.0
class FSim(SimCharger):
"""Who set the current and the phases last, and when."""
ctl = None
def __init__(self, *a, **kw):
super().__init__(*a, **kw)
self.setter = None
self.cur_other_at = None # a foreign current stands since
self.ph_other_at = None # foreign phases stand since
self.own_ph = None # set at the first event (the start)
self.unknown = False
self.sel_log = [] # (sim t, n, taken?) of own selects
self.late = None # (n, t_sent) a refused select to take
def _apply(self, what, v):
if what == "current":
self.setter = "solar"
self.cur_other_at = None
else:
self.own_ph = 3 if v == 3 else 1
self.ph_other_at = None
super()._apply(what, v)
now_t = 0.0 # the plant's clock (not this model's)
refuse_ph = False # only the phase selects are ignored
last_sel = None # (n, plant second) of the latest select
def request_phases(self, n):
self.last_sel = (n, self.now_t)
self.sel_log.append((self.now_t, n, self.refuse_ph, self.refuse,
self.phases_allowed, self.own_ph))
keep = self.refuse
if self.refuse_ph:
self.refuse = "ignore"
try:
ok = super().request_phases(n)
finally:
self.refuse = keep
if ok and (self.refuse_ph or keep == "ignore"):
self.late = (n, self.now_t)
return ok
def set_current(self, a):
if abs(float(a) - self.setpoint_a) > 0.5:
self.setter = "other"
self.cur_other_at = self.now_t
super().set_current(a)
def set_phases(self, n):
super().set_phases(n)
if self.own_ph is None:
return # Solar has no phases of its own yet
if self.phases_allowed != self.own_ph:
self.ph_other_at = self.now_t
else:
self.ph_other_at = None
def _build(self):
out = super()._build()
if self.unknown:
for k in list(out):
if "phases" in k and ("select." in k or "max_allowed" in k):
out[k] = dict(out[k], state="unknown")
return out
COUNT = {}
EVLOG = []
NOW = [0.0]
def bump(k, n=1):
COUNT[k] = COUNT.get(k, 0) + n
EVLOG.append((NOW[0], k))
HIST = {}
def fuzz_site(seed):
rnd = random.Random(seed)
HIST.clear()
del EVLOG[:]
sim = FSim(setpoint_a=rnd.choice([0, 6, 10, 16]))
sim.lag_s = rnd.choice([0.0, 0.0, 3.0, 12.0])
if seed % 3 == 0:
sim.ramp_w_s, sim.stop_delay_s = 300.0, 4.0
state = {"sun": rnd.uniform(3000, 11000), "house": rnd.uniform(300, 2000)}
bad, mem = [], dict(last_foreign=-1e9, press_at=-1e9, hold=False,
rises=0, n_sel=0, n_cur=0, seq=None, zero_cnt=0,
was_ms=False)
pend = {} # name -> end second of an outage
async def ev(p, c):
sim.ctl = c
w = c.car_solar
t = p.t
NOW[0] = sim.now_t = t
def takes_charger():
"""The user's press (or Solar entered, or the charger back with
no hold) takes the charger as it is: nothing on it is foreign,
and Solar's phases are the first known read after it (OQ2), which
`on_cycle` copies from Solar's start state."""
sim.own_ph, sim.ph_other_at = None, None
sim.cur_other_at = None
if pend.get("outage") is not None and t >= pend["outage"] \
and not w.hold:
takes_charger()
for k, off in (("outage", lambda: p.ch.go_unavailable(False)),
("meter", lambda: setattr(p, "meter_on", True)),
("stop", lambda: setattr(c, "auto", True)),
("unknown", lambda: setattr(sim, "unknown", False)),
("shadow", lambda: c.o.__setitem__("shadow_mode",
"off"))):
if pend.get(k) is not None and t >= pend[k]:
off()
pend[k] = None
if pend.get("mode") is not None and t >= pend["mode"]:
pend["mode"] = None
mem["press_at"] = t
takes_charger()
await c.handle_action("car_mode", value="solar")
if sim.refuse is not None and rnd.random() < 0.03:
sim.refuse = None
# a late take of a refused select: inside (<= 12 s after it went) or
# after (>= 25 s) the window
if sim.late is not None:
n_, t_ = sim.late
age = t - t_
if 3 <= age <= 12 and rnd.random() < 0.005:
sim.set_phases(n_)
sim.own_ph = sim.phases_allowed
sim.ph_other_at = None
sim.late = None
bump("late_in")
elif age >= 25 and rnd.random() < 0.2:
sim.set_phases(n_)
mem["last_foreign"] = t
sim.late = None
bump("late_after")
elif age > 400:
sim.late = None
if pend.get("latch") is not None and t >= pend["latch"]:
c.circ_wd.tripped = False
pend["latch"] = None
seqnow = w.seq is not None
s = "_seq" if seqnow else ""
# independent draws; a change in progress draws far more events
if rnd.random() < 0.02:
state["sun"] = max(0.0, min(12000.0, state["sun"]
+ rnd.uniform(-8000, 8000)))
if rnd.random() < 0.002:
state["house"] = rnd.uniform(300, 4000)
if rnd.random() < 0.0004 and pend.get("outage") is None:
p.ch.go_unavailable(True)
pend["outage"] = t + rnd.uniform(1, 40)
bump("outage")
if rnd.random() < 0.0003:
(p.ch.unplug if p.ch.state != "A" else p.ch.plug_in)()
if rnd.random() < 0.002:
sim.refuse = rnd.choice([None, "ignore", "ignore", "error"])
bump("refuse")
if rnd.random() < (0.12 if seqnow else 0.0015):
sim.set_current(rnd.choice([0, 5, 6, 13, 16]))
mem["last_foreign"] = t
bump("f_cur" + s)
if rnd.random() < (0.12 if seqnow else 0.003):
x = rnd.choice([1, 3])
ls = sim.last_sel
if ls is not None and t - ls[1] <= 25:
# inside Solar's own select window nothing is judged (DA3,
# Finding 4): a foreign switch there can hide behind the take
# and is not drawn; T47 and T48 cover its edges
bump("f_ph_skipped_in_window")
else:
sim.set_phases(x)
if sim.ph_other_at is not None:
mem["last_foreign"] = t
bump("f_ph" + s)
ls = sim.last_sel
in_sel = ls is not None and t - ls[1] <= 40
if in_sel and sim.unknown:
# a take that nobody could read inside the window is judged when
# seen (DA3, Finding 3): no unknown phases around an own select
sim.unknown, pend["unknown"] = False, None
if rnd.random() < 0.001 and pend.get("unknown") is None \
and not in_sel:
sim.unknown = True
pend["unknown"] = t + rnd.uniform(3, 30)
bump("unknown")
if (w.hold or w.mismatch_since is not None) and rnd.random() < 0.012:
# the other writer puts its change back: the read-back is ours
if w.last_a is not None:
sim.set_current(w.last_a)
if sim.own_ph is not None:
sim.set_phases(sim.own_ph)
sim.setter = "solar"
sim.cur_other_at = sim.ph_other_at = None
bump("put_back")
if (w.hold or w.gave_up) and rnd.random() < 0.025:
mem["press_at"] = t
takes_charger()
bump("press_hold")
await c.handle_action("car_mode", value="solar")
elif seqnow and rnd.random() < (0.3 if w.mismatch_since is not None
else 0.03):
if w.hold or w.mismatch_since is not None:
bump("lift_press_seq")
mem["press_at"] = t
takes_charger()
bump("press_seq")
await c.handle_action("car_mode", value="solar")
if seqnow and not sim.refuse_ph and rnd.random() < 0.2:
sim.refuse_ph = True # a select the charger ignores
bump("refuse_seq")
elif sim.refuse_ph and rnd.random() < 0.02:
sim.refuse_ph = False
if rnd.random() < 0.0004 and pend.get("meter") is None:
p.meter_on = False
pend["meter"] = t + rnd.uniform(5, 60)
bump("meter")
counting = w.mismatch_since is not None and not w.hold
if rnd.random() < (0.05 if seqnow else 0.05 if counting else 0.0006):
k = rnd.choice(["stop", "shadow", "mode", "latch"])
bump(k + s)
back = t + rnd.uniform(5, 60)
if k == "stop" and pend.get("stop") is None:
c.auto = False
c.o["shadow_mode"] = rnd.choice(["off", "auto"])
pend["stop"] = back
elif k == "shadow" and pend.get("shadow") is None:
c.o["shadow_mode"] = "on"
pend["shadow"] = back
elif k == "latch" and pend.get("latch") is None:
c.circ_wd.tripped = True
pend["latch"] = back
elif k == "mode" and pend.get("mode") is None:
await c.handle_action("car_mode", value="off")
pend["mode"] = back
if rnd.random() < 0.0005:
await c.handle_action("car_sun_first", value=rnd.choice(
["batteries", "car"]))
def on_cycle(p, c, t):
w, m = c.car_solar, c.car_writer
t = float(t)
if sim.own_ph is None and getattr(w, "_own_n", None) is not None:
sim.own_ph = w._own_n
HIST[t] = (w.mismatch_since, w.hold, getattr(w, "_own_n", None),
getattr(w, "_win_t1", None),
None if w.seq is None else w.seq["stage"],
p.ch.phases_allowed, p.ch.own_ph, p.ch.ph_other_at,
w.sent_a, p.ch.setpoint_a)
held = w.hold
was_hold = mem["hold"]
ms = w.mismatch_since is not None
# N8
if (held or ms) and c.car_solar_can_cut():
bad.append((seed, t, "N8 can_cut under a mismatch or hold"))
# N10: Manual never judges phases
if getattr(m, "_ph_diff", False):
bad.append((seed, t, "N10 Manual judges phases"))
# N3: a mismatch or hold needs a foreign event shortly before
# (judged where it starts: a foreign value that stands unseen while
# Solar does not watch, no car or a fault, is seen when it does)
explained = (sim.ph_other_at is not None
or sim.cur_other_at is not None
or t - mem["last_foreign"] <= 400
or t - mem["press_at"] <= 400)
if ((ms and not mem["was_ms"]) or (held and not mem["hold"])) \
and not explained:
bad.append((seed, t, "N3 mismatch or hold with no foreign event",
w.mismatch_since, held))
if ms and not mem["was_ms"]:
bump("mismatch")
if mem["seq"] is not None:
bump("mismatch_seq")
mem["was_ms"] = ms
mem["seq"] = w.seq
if held and not mem["hold"]:
mem["rises"] += 1
bump("hold")
if getattr(w, "_ph_diff", False):
bump("hold_ph")
if mem["hold"] and not held:
if t - mem["press_at"] <= 2:
bump("lift_press")
else:
bump("lift_match")
mem["hold"] = held
# N10: no hold over the value a press took, in the 3 cycles after it
if held and 0 <= t - mem["press_at"] <= 3 \
and t - mem["last_foreign"] > 3:
bad.append((seed, t, "N10 hold right after a press"))
# N9: one CHARGER_OTHER per hold
others = len([1 for m_ in LOG.since(mem.get("mark", 0), "WARNING")
if "CHARGER_OTHER" in m_])
if others > mem["rises"]:
bad.append((seed, t, "N9 more CHARGER_OTHER than holds", others,
mem["rises"]))
# N5: the cut cap
if w.cut_fails > carmode.MAX_TRIES:
bad.append((seed, t, "N5 cut tries over the cap", w.cut_fails))
# N1 / N2 / N7 on the writes of this cycle
for e in p.wlog[mem["n_wlog"]:]:
# a write waits for its read-back, so its own stamp runs ahead of
# the cycle that sent it: judge by the cycle's second
tt, what, v = t, e[1], e[2]
if what == "current" and v > 0:
bump("nz_write")
for lab, since in (("N1 current", sim.cur_other_at),
("N2 phases", sim.ph_other_at)):
if since is not None and sim.setter in ("other", "solar") \
and tt - since >= WRITER_S + 2 \
and mem["press_at"] < since:
bad.append((seed, tt, lab, "write over a foreign "
"value that stood", v, since))
if what == "phases":
bump("select")
if sim.ph_other_at is not None \
and tt - sim.ph_other_at >= WRITER_S + 2 \
and mem["press_at"] < sim.ph_other_at:
bad.append((seed, tt, "N2 select over foreign phases",
sim.ph_other_at, mem["press_at"],
sim.own_ph, sim.phases_allowed))
if ms or held:
bad.append((seed, tt, "N7 select under a mismatch/hold"))
if what == "current" and v == 0.0 and ms and not held:
bump("zero_in_count")
# (the way-out 0 A of the step in which the count runs out is
# written before the watch holds: OQ1)
if what == "current" and v == 0.0 and held and was_hold:
bad.append((seed, tt, "N2 0 A written under a hold"))
mem["n_wlog"] = len(p.wlog)
if held and (c.car_mode != "solar" or not c.car_writing()):
bump("stop_under_hold")
# N4: 6 A never past the pause
pause_s = 60.0 * carmode.solar_option(c.o, "ev_pause_min")
rd = c.car.reading
avail = bool(rd is not None and rd.available)
if c.car_mode == "solar" and c.car_writing() and avail \
and (w.sent_a or 0.0) >= 6.0 and w.taken \
and sim.setter == "solar" and sim.setpoint_a >= 6.0 \
and w.plan.low_since is not None \
and t - w.plan.low_since > pause_s + 2.0 and not ms and not held:
bad.append((seed, t, "N4 6 A past the pause"))
race = seed % 2 == 1
evs = {t: ev for t in range(30, STEPS_PER)}
mark = LOG.mark()
mem["mark"] = mark
mem["n_wlog"] = 0
r = S.drive(lambda t: state["house"], lambda t: state["sun"],
dur=STEPS_PER, first=rnd.choice(["batteries", "car", "car"]),
socs={"a": rnd.uniform(40, 100), "b": rnd.uniform(70, 100)},
sim=sim, race=race, events=evs, on_cycle=on_cycle,
phases=rnd.choice([1, 3]),
opts={"ev_start_min": rnd.choice([1, 1, 2]),
"ev_pause_min": rnd.choice([1, 2, 5]),
"ev_phases": rnd.choice(["auto"] * 5 + ["1", "3"])})
r["_log"] = mark
nv = nevers(r, f"N6/N13 seed {seed}", gap=carmode.PHASE_GAP_S)
if DEBUG and bad:
t0 = float(os.environ.get("EV22_FUZZ_T0") or bad[0][1])
print(" DEBUG first bad", bad[0])
print(" writes", [(x[0], x[1], x[2]) for x in r["plant"].wlog
if t0 - 90 <= x[0] <= t0 + 5])
print(" events", sorted(x for x in EVLOG if t0 - 120 <= x[0] <= t0 + 5))
print(" lag", sim.lag_s, "seed", seed)
print(" selects (plant s, n, refuse_ph, refuse, phases, own)",
[x for x in sim.sel_log if t0 - 200 <= x[0] <= t0 + 5])
print(" hist (t, ms, hold, own_n, win_end, seq, phases, model own,"
" model foreign since)")
for tk in sorted(HIST):
if t0 - 40 <= tk <= t0 + 2:
print(" ", tk, HIST[tk])
return bad, nv
print("T38: THE FUZZ")
allbad, allnv = [], []
for seed in (ONLY or range(SITES)):
bad, nv = fuzz_site(seed)
allbad += bad
allnv += nv
if bad:
print(" seed", seed, bad[:2])
check(f"T38: N1-N5, N7-N10 hold in every cycle of {SITES} seeds x "
f"{STEPS_PER} s ({allbad[:3]})", not allbad)
WHAT = {
"N1": "no non-zero current write over a foreign current that stood "
"WRITER_S (the close, the EV-28 restore, an undo included)",
"N2": "no non-zero write and no select over foreign phases that stood "
"WRITER_S; a 0 A is never written under a hold",
"N3": "no mismatch, hold or CHARGER_OTHER without a foreign event shortly "
"before (own writes, own selects, own sequence values, a reading "
"from before the step's own 0 A, unknown, stale or failed reads)",
"N4": "the N3 reading: never 6 A past pause_s",
"N5": "at most MAX_TRIES cut tries per quarter key",
"N7": "no phase select under a mismatch or a hold",
"N8": "car_solar_can_cut is never True under a mismatch or a hold",
"N9": "at most one CHARGER_OTHER per hold",
"N10": "Manual never judges phases; no hold right after a press",
}
for k, txt in WHAT.items():
check(f"{k}: {txt} (every cycle of {SITES} seeds)",
not [b for b in allbad if b[2].split()[0] == k])
check(f"N6: no write above the clamp, a select only at 0 A under 100 W, one "
f"per 600 s, no Traceback (nevers of every seed) ({allnv[:2]})",
not allnv)
print(" counts", dict(sorted(COUNT.items())), "UP_S", carmode.UP_S,
"PHASE_GAP_S", carmode.PHASE_GAP_S)
floor = {"mismatch_seq": 20, "hold_ph": 10, "lift_match": 10, "lift_press": 10,
"lift_press_seq": 5, "zero_in_count": 5, "stop_under_hold": 5,
"late_after": 5}
if STEPS_PER >= 3600:
check(f"T38: the fuzz reaches its branches ({ {k: COUNT.get(k, 0) for k in floor} }, "
f"floor {floor})", all(COUNT.get(k, 0) >= v for k, v in floor.items()))
report()