Compare commits

...
2 Commits
Author SHA1 Message Date
Claude b7c91ff746 EV-22: retire the ManualWriter source pin in test_ev60 N7 (PM ruling)
infra-pin / fresh (pull_request) Successful in 2s
checks / unit (pull_request) Failing after 1h14m26s
The SHA-256 of ManualWriter's source was an EV-60 review-time pin. EV-22
changes ManualWriter by design (C7, DA1), so the pin is removed; the
behavioural Manual rows of test_ev56, test_ev59 and test_ev60 are unchanged
and green.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-03 05:32:46 +01:00
Claude c7b1b7dbd1 EV-22: Solar and Manual never write over another writer; one rule of control
checks / unit (pull_request) Failing after 57m18s
infra-pin / fresh (pull_request) Successful in 3s
C7: the other-writer watch now runs in every step of a phase change (zero,
select, settle) in both writers, with the change's own 0 A and every closing
current it tried counted as own. While a difference or a hold stands, nothing
non-zero is written over it: no settle close, no EV-28 restore, no select, no
Manual undo or abandon. The 6 A raise check stays and runs first.

D4 (Solar): the read-back phases are judged like the current, against the
phases Solar itself chose (start state = first known read-back outside an own
select window, or an own select seen taken), never the plan's adopted n.
Same mismatch_since, hold and CHARGER_OTHER; lift only when current and
phases both match, or a press. The window of an own select is SETTLE_S from
the try's return; a take seen after it is another writer's.

DA1: a press that lifts a difference inside a phase change ends the change
at its 0 A (both writers); the raise check never holds over a value the
press took. DA2: the not-writing path does not judge the current with the
reading from before its own 0 A.

test_ev22.py (T1-T49, review row T48 (stale)), test_ev22_fuzz.py (T38,
N1-N10). test_ev20_writers T46 (a)(b)(c) edited as ruled (PM, v3).

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-03 04:21:38 +01:00
7 changed files with 1701 additions and 54 deletions
+1
View File
@@ -2,6 +2,7 @@
### Not in a release yet ### Not in a release yet
- **Solar no longer writes over another writer's car current or phases.** If something else changes the car's current or its phases, also in the middle of a phase change, the add-on writes nothing over it. After 30 seconds it stops writing until you press Solar, and warns CHARGER_OTHER once. Manual does the same for a current changed during its own phase change ([[EV-22]]).
- **A car phase change whose current the charger refuses no longer sends that current five times.** After three refused tries the add-on stops at once and warns CHARGER_REFUSED; the car stays at 0 A until you change something. A value you change meanwhile gets its own three tries ([[EV-59]]). - **A car phase change whose current the charger refuses no longer sends that current five times.** After three refused tries the add-on stops at once and warns CHARGER_REFUSED; the car stays at 0 A until you change something. A value you change meanwhile gets its own three tries ([[EV-59]]).
- **A car current the add-on cannot send because of an error is no longer sent again every second.** It counts as a write the charger did not take: 3 tries a minute apart, then the add-on stops and warns CHARGER_REFUSED. The error is logged once per current ([[EV-56]]). - **A car current the add-on cannot send because of an error is no longer sent again every second.** It counts as a write the charger did not take: 3 tries a minute apart, then the add-on stops and warns CHARGER_REFUSED. The error is logged once per current ([[EV-56]]).
- **A peak cut the charger does not take no longer stops Solar.** After three refused tries in a 15-minute period, Solar goes on controlling the car and tries the cut again at the start of the next period while it is still needed. The warning now says "The charger did not take the peak cut, so the add-on tries again next quarter: CHARGER_REFUSED." ([[EV-54]]). - **A peak cut the charger does not take no longer stops Solar.** After three refused tries in a 15-minute period, Solar goes on controlling the car and tries the cut again at the start of the next period while it is still needed. The warning now says "The charger did not take the peak cut, so the add-on tries again next quarter: CHARGER_REFUSED." ([[EV-54]]).
+5 -4
View File
@@ -3370,10 +3370,11 @@ changes at most once per 30 seconds and only by 1 A or more.
be charging* follows. be charging* follows.
- **Shadow mode** writes nothing but that one 0 A; a start in shadow mode writes - **Shadow mode** writes nothing but that one 0 A; a start in shadow mode writes
nothing at all. The card says what Solar would set. nothing at all. The card says what Solar would set.
- **Another writer.** If the charger shows a current Solar did not set for 30 - **Another writer.** If the charger shows a current or a number of phases
seconds, Solar writes nothing over it (also no 0 A), shows an amber row and that Solar did not set, Solar writes nothing over it from the first moment,
logs one warning, until you press Solar again or the charger shows Solar's also in the middle of a phase change. After 30 seconds it writes nothing more
value. (also no 0 A), shows an amber row and logs one warning, until you press Solar
again or the charger shows Solar's own current and phases.
- **The peak limit: the car is cut first.** When the 15-minute period heads - **The peak limit: the car is cut first.** When the 15-minute period heads
over the peak limit, Solar lowers the car first, also while the batteries over the peak limit, Solar lowers the car first, also while the batteries
could instead charge less: by the excess, to 0 A when less than 6 A would be left. could instead charge less: by the excess, to 0 A when less than 6 A would be left.
+148 -27
View File
@@ -150,11 +150,20 @@ class ManualWriter:
self._late = None # (a, was, why, n) of a write not taken self._late = None # (a, was, why, n) of a write not taken
self._rec_a = None # EV-56: the raised value already logged self._rec_a = None # EV-56: the raised value already logged
self._close_k = 0 # EV-59: not-taken closes of the value owed self._close_k = 0 # EV-59: not-taken closes of the value owed
self._ph_diff = False # EV-22: the phases differ from our own
# (Solar only; Manual never sets it)
# ------------------------------------------------------------------ user # ------------------------------------------------------------------ user
def user_changed(self) -> None: def user_changed(self) -> None:
"""The user changed the mode or a value: one more write is allowed, """The user changed the mode or a value: one more write is allowed,
and another writer's hold is lifted.""" and another writer's hold is lifted. EV-22 (DA1): a change that lifts
a difference inside a phase change ends the change at its 0 A; the
raise check never holds over the value the user's change took."""
if self.seq is not None:
if self._other_stands():
self.seq = None
else:
self.seq["pressed"] = True # the raise check holds off
self.boot = False self.boot = False
self.rev_applied = None self.rev_applied = None
self.hold = self.other = False self.hold = self.other = False
@@ -192,6 +201,9 @@ class ManualWriter:
self._rec_a = None # EV-56 (G2): logged again self._rec_a = None # EV-56 (G2): logged again
cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a
if self.seq is not None: if self.seq is not None:
# EV-22 (C7): the watch runs in every step of a phase change; the
# change's own values count as own (`_own_values`).
self._watch(cur, now)
if self.seq["stage"] in ("zero", "select") \ if self.seq["stage"] in ("zero", "select") \
and (mode != MANUAL or not writing): and (mode != MANUAL or not writing):
await self._undo(drv, now, tracker, clamp, shadow) await self._undo(drv, now, tracker, clamp, shadow)
@@ -275,26 +287,54 @@ class ManualWriter:
self.fails = max(min(self._close_k, MAX_TRIES) - 1, 0) self.fails = max(min(self._close_k, MAX_TRIES) - 1, 0)
self._failed(now) self._failed(now)
def _watch(self, cur, now) -> None: def _other_stands(self) -> bool:
"""Is the read-back what we wrote? A difference that stands for """EV-22: another writer's value is held, or its count is running:
`WRITER_S` is another writer.""" nothing non-zero is written over it."""
known = [x for x in (self.last_a, self.attempted_a, self.prior_a) return bool(self.hold or self.mismatch_since is not None)
def _own_values(self) -> list:
"""The currents that are ours: what we wrote, tried or saw before a
try, and (EV-22, C7) every value of the phase change under way: its
0 A and each closing current it tried (also after a user change
cleared `attempted_a`)."""
vals = [x for x in (self.last_a, self.attempted_a, self.prior_a)
if x is not None] if x is not None]
if not known or cur is None: if self.seq is not None:
self.mismatch_since = None vals += self.seq.get("own", ())
return return vals
if any(abs(cur - k) <= TOL_A for k in known):
self.mismatch_since = None def _watch(self, cur, now, judge=True) -> None:
if self.hold: """Is the read-back what we wrote? A difference that stands for
self.hold = self.other = False `WRITER_S` is another writer. EV-22: one count and one hold for the
return current and (Solar) the phases; `judge=False`: the reading is from
before our own write of this step, so the current is not judged and
the count stands."""
known, diff = [], None
if judge:
known = self._own_values()
if known and cur is not None:
diff = not any(abs(cur - k) <= TOL_A for k in known)
if diff or self._ph_diff:
if self.mismatch_since is None: if self.mismatch_since is None:
self.mismatch_since = now self.mismatch_since = now
elif now - self.mismatch_since >= WRITER_S and not self.hold: elif now - self.mismatch_since >= WRITER_S and not self.hold:
self.hold = self.other = True self.hold = self.other = True
_LOG.info("Something else changes the charger (read-back %.0f A, " if diff:
"the add-on set %.0f A), so the add-on stops writing " _LOG.info("Something else changes the charger (read-back "
"to it until you change it.", cur, known[0]) "%.0f A, the add-on set %.0f A), so the add-on "
"stops writing to it until you change it.",
cur, known[0])
else:
_LOG.info("Something else changes the charger (the "
"phases are not the ones the add-on chose), so "
"the add-on stops writing to it until you "
"change it.")
return
if not judge:
return
self.mismatch_since = None
if diff is False and self.hold:
self.hold = self.other = False
# ----------------------------------------------------- EV-52: the info line # ----------------------------------------------------- EV-52: the info line
def _why_default(self) -> str: def _why_default(self) -> str:
@@ -410,7 +450,8 @@ class ManualWriter:
self.undone += 1 self.undone += 1
self.rev_applied, self.reapply = None, True self.rev_applied, self.reapply = None, True
a = self._restore_a(q.get("prev"), clamp) a = self._restore_a(q.get("prev"), clamp)
if a is not None: if a is not None and not self._other_stands(): # EV-22: not over theirs
q.setdefault("own", []).append(a)
await self._write(drv, a, 0.0, now, tracker, why="Manual") await self._write(drv, a, 0.0, now, tracker, why="Manual")
async def _begin(self, drv, r, cur, n, now, tracker) -> None: async def _begin(self, drv, r, cur, n, now, tracker) -> None:
@@ -428,7 +469,7 @@ class ManualWriter:
self._failed(now) self._failed(now)
return return
self.seq = {"stage": "zero", "t0": now, "n": n, "tries": 0, self.seq = {"stage": "zero", "t0": now, "n": n, "tries": 0,
"prev": cur} "prev": cur, "own": [0.0]}
async def abandon(self, drv, now, tracker, clamp=None) -> None: async def abandon(self, drv, now, tracker, clamp=None) -> None:
"""The add-on is stopping in the middle of a phase change: give the car """The add-on is stopping in the middle of a phase change: give the car
@@ -436,11 +477,19 @@ class ManualWriter:
like every write. The phases stay as the select left them.""" like every write. The phases stay as the select left them."""
q, self.seq = self.seq, None q, self.seq = self.seq, None
a = None if q is None else self._restore_a(q.get("prev"), clamp) a = None if q is None else self._restore_a(q.get("prev"), clamp)
if a is not None: if a is not None and not self._other_stands(): # EV-22: not over theirs
self._clock = self._clock or (lambda: now) self._clock = self._clock or (lambda: now)
await self._write(drv, a, 0.0, now, tracker, why="shutdown", await self._write(drv, a, 0.0, now, tracker, why="shutdown",
strict=True) strict=True)
def _select_try(self, n, ok) -> None:
"""EV-22: a phase select of ours went out and returned (Solar's
window and own phases; Manual does not judge phases)."""
def _took_as_is(self) -> None:
"""EV-22 (DA1): a user's change took the charger's value as it is
(Solar forgets what it sent)."""
async def _advance(self, drv, r, cur, now, tracker, want_a, clamp, rev): async def _advance(self, drv, r, cur, now, tracker, want_a, clamp, rev):
q = self.seq q = self.seq
if q["stage"] in ("zero", "select") and cur is not None \ if q["stage"] in ("zero", "select") and cur is not None \
@@ -450,11 +499,20 @@ class ManualWriter:
# change, and leave the charger to whoever set it until the user # change, and leave the charger to whoever set it until the user
# changes something. # changes something.
self.seq = None self.seq = None
self.hold = self.other = True
self.last_a = self.attempted_a = self.prior_a = None self.last_a = self.attempted_a = self.prior_a = None
if q.get("pressed"):
# EV-22 (DA1): the user's change came during this change: the
# charger is taken as it is, never held over that value.
self._took_as_is()
return
self.hold = self.other = True
_LOG.info("Something else raised the charger's current during a " _LOG.info("Something else raised the charger's current during a "
"phase change, so the phases were not touched.") "phase change, so the phases were not touched.")
return return
if self._other_stands():
# EV-22 (C7): another writer's value stands (its count runs, or
# it is held): no select, no restore, no closing current over it.
return
if q["stage"] == "zero": if q["stage"] == "zero":
# A power reading decides; only without one does mode3 (not C, # A power reading decides; only without one does mode3 (not C,
# not D) say the car is quiet. Still drawing at the timeout: no # not D) say the car is quiet. Still drawing at the timeout: no
@@ -486,6 +544,7 @@ class ManualWriter:
self.last_switch = now self.last_switch = now
self.log.append(("phases", q["n"], now, ok)) self.log.append(("phases", q["n"], now, ok))
q["stage"], q["t1"] = "settle", self.last_done # from its return q["stage"], q["t1"] = "settle", self.last_done # from its return
self._select_try(q["n"], bool(ok))
if not ok: if not ok:
q["failed"] = True # EV-15: no grace for the alarm q["failed"] = True # EV-15: no grace for the alarm
# The charger did not take it: the car gets its current back # The charger did not take it: the car gets its current back
@@ -506,6 +565,7 @@ class ManualWriter:
# on whether the phases changed); Manual a number, as before. # on whether the phases changed); Manual a number, as before.
want = want_a(q) if callable(want_a) else want_a want = want_a(q) if callable(want_a) else want_a
a = min(max(float(want), CH.MIN_A), hi) a = min(max(float(want), CH.MIN_A), hi)
q.setdefault("own", []).append(a) # EV-22: a value we tried is ours
if await self._write(drv, a, 0.0, now, tracker, if await self._write(drv, a, 0.0, now, tracker,
why=self._close_why(q), why=self._close_why(q),
n=q["n"] if q.get("sel_ok") else None): n=q["n"] if q.get("sel_ok") else None):
@@ -907,6 +967,13 @@ class SolarWriter(ManualWriter):
self.sent_cut = False # `sent_a` went out as a cut try self.sent_cut = False # `sent_a` went out as a cut try
self.refused_cut = None # a cut value the charger did not take self.refused_cut = None # a cut value the charger did not take
self._cap_end = False # EV-60: a capped close ended the change self._cap_end = False # EV-60: a capped close ended the change
# EV-22 (D4): the phases Solar itself chose. `_own_n`: the last it
# TOOK (or the start state); `_sel_n` and `_win_end`: its latest
# select try and the SETTLE_S after that try returned, in which a
# read-back is not judged.
self._own_n = None
self._sel_n = None
self._win_end = None
def owe_start(self) -> None: def owe_start(self) -> None:
"""C1: the add-on starts in Off while an exit 0 A of its own was still """C1: the add-on starts in Off while an exit 0 A of its own was still
@@ -1009,10 +1076,16 @@ class SolarWriter(ManualWriter):
"""The user PRESSED SOLAR: another writer's hold is lifted and Solar """The user PRESSED SOLAR: another writer's hold is lifted and Solar
takes the charger as it is (its value is no longer a difference); takes the charger as it is (its value is no longer a difference);
Solar's own value is decided and written afresh.""" Solar's own value is decided and written afresh."""
held = self.hold or self.mismatch_since is not None held = self._other_stands()
super().user_changed() had_seq = self.seq is not None
super().user_changed() # EV-22 (DA1): ends a change it lifts
self.gave_up, self.fails, self.fail_at = False, 0, None self.gave_up, self.fails, self.fail_at = False, 0, None
self._stuck_end() self._stuck_end()
# EV-22: the phases are taken afresh (the start state again); an own
# select's window stays.
self._own_n, self._ph_diff = None, False
if held and had_seq:
self.plan.end_switch(False)
if held: if held:
self.last_a = None self.last_a = None
self.sent_a, self.taken = None, True self.sent_a, self.taken = None, True
@@ -1266,9 +1339,50 @@ class SolarWriter(ManualWriter):
if self.live and not self.hold: if self.live and not self.hold:
await self._put(drv, 0.0, cur, now, tracker, stuck, out=True) await self._put(drv, 0.0, cur, now, tracker, stuck, out=True)
def _watch(self, cur, now) -> None: def _took_as_is(self) -> None:
self.sent_a, self.taken = None, True
self.refused_cut = None
def _reset_phases(self, window=True) -> None:
"""EV-22: the phases Solar judges start afresh (entering Solar, the
charger's return, a press). The window of an own select goes too
unless it is kept."""
self._own_n, self._ph_diff = None, False
if window:
self._sel_n = self._win_end = None
def _select_try(self, n, ok) -> None:
"""EV-22 (DA3): our own select try returned. SETTLE_S from now a
read-back is not judged (A7: from its return, not from its send); a
taken select is our phases at once, one the charger did not confirm
becomes ours if a read inside the window shows it."""
self._sel_n = n
self._win_end = float(self.last_done) + SETTLE_S
if ok:
self._own_n, self._ph_diff = n, False
def _judge_phases(self, r, now) -> None:
"""EV-22 (D4): the read-back phases against the phases Solar itself
chose (never the plan's adopted `n`). Unknown phases and reads inside
a select's window start nothing and lift nothing."""
p = getattr(r, "phases_allowed", None)
if p not in (1, 3):
return
if self._win_end is not None:
if now <= self._win_end:
if p == self._sel_n:
self._own_n, self._ph_diff = p, False # the take
return
self._sel_n = self._win_end = None
if self._own_n is None:
self._own_n, self._ph_diff = p, False # the start state
return
self._ph_diff = p != self._own_n
def _watch(self, cur, now, judge=True) -> None:
was = self.hold was = self.hold
super()._watch(cur, now) self._judge_phases(self._r, now)
super()._watch(cur, now, judge)
if self.hold and not was: if self.hold and not was:
_LOG.warning("Something else changes the charger, so the add-on " _LOG.warning("Something else changes the charger, so the add-on "
"stops writing to it until you press Solar: " "stops writing to it until you press Solar: "
@@ -1306,6 +1420,7 @@ class SolarWriter(ManualWriter):
self.out, self.fault = False, None self.out, self.fault = False, None
self.restart = True self.restart = True
self.mismatch_since = None self.mismatch_since = None
self._reset_phases()
self.plan.reset(self.plan.n) self.plan.reset(self.plan.n)
def _gap_ok(self, now) -> bool: def _gap_ok(self, now) -> bool:
@@ -1383,7 +1498,7 @@ class SolarWriter(ManualWriter):
self.plan.end_switch(False) self.plan.end_switch(False)
return return
self.seq = {"stage": "zero", "t0": now, "n": n, "tries": 0, self.seq = {"stage": "zero", "t0": now, "n": n, "tries": 0,
"prev": None, "from": r.phases_allowed} "prev": None, "from": r.phases_allowed, "own": [0.0]}
# ------------------------------------------------------------- step # ------------------------------------------------------------- step
async def held_pause(self, drv, r, *, sun, now, tracker) -> None: async def held_pause(self, drv, r, *, sun, now, tracker) -> None:
@@ -1432,6 +1547,7 @@ class SolarWriter(ManualWriter):
# notice. The quarter's try count stays (Q5). # notice. The quarter's try count stays (Q5).
self.refused_cut, self.sent_cut, self.cut_warned = None, False, \ self.refused_cut, self.sent_cut, self.cut_warned = None, False, \
False False
self._reset_phases() # EV-22: a fresh entry starts clean
if not self.engaged: if not self.engaged:
return return
if sun is not None: if sun is not None:
@@ -1463,6 +1579,8 @@ class SolarWriter(ManualWriter):
self.startup_zero = self.boot and not self._returned self.startup_zero = self.boot and not self._returned
self.fresh_start = self.restart = True self.fresh_start = self.restart = True
self.mismatch_since = None self.mismatch_since = None
if not self.hold:
self._reset_phases(window=False) # EV-22: start state again
self.last_a = self.attempted_a = self.prior_a = None self.last_a = self.attempted_a = self.prior_a = None
self._rec_a = None # EV-56 (G2): logged again self._rec_a = None # EV-56 (G2): logged again
cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a
@@ -1497,8 +1615,11 @@ class SolarWriter(ManualWriter):
# owed, then nothing. The watch goes on (another writer is held # owed, then nothing. The watch goes on (another writer is held
# for every reader) and so does the plan, for the card. # for every reader) and so does the plan, for the card.
self.out = True self.out = True
n_log = len(self.log)
await self._zero(drv, cur, now, tracker, stuck) await self._zero(drv, cur, now, tracker, stuck)
self._watch(cur, now) # EV-22 (DA2): `cur` is from before our own 0 A of this step:
# the current is not judged then (the phases are).
self._watch(cur, now, judge=len(self.log) == n_log)
self._shadow_plan(sun, now, clamp, n_now) self._shadow_plan(sun, now, clamp, n_now)
self.restart = True self.restart = True
return return
@@ -1571,8 +1692,8 @@ class SolarWriter(ManualWriter):
if self.drop_ready(cur, stuck): if self.drop_ready(cur, stuck):
# EV-54 (drop rule): the refused cut value is not sent again. # EV-54 (drop rule): the refused cut value is not sent again.
self._drop(cur, now) self._drop(cur, now)
self._watch(cur, now) # EV-22 (C7): inside a change too
if self.seq is None: if self.seq is None:
self._watch(cur, now)
if self.hold or self.mismatch_since is not None: if self.hold or self.mismatch_since is not None:
# Another writer's value, held or not yet: nothing is written # Another writer's value, held or not yet: nothing is written
# over it; the plan goes on for the card. # over it; the plan goes on for the card.
+27 -17
View File
@@ -217,23 +217,33 @@ check(f"T46: Solar starts on 1 phase (select at the start), then another "
f"phase, Expected 5) ({[(x[0], x[2]) for x in s46]})", f"phase, Expected 5) ({[(x[0], x[2]) for x in s46]})",
s46[:1] and s46[0][2] == 1 s46[:1] and s46[0][2] == 1
and not [x for x in s46 if 140 < x[0] < 700]) and not [x for x in s46 if 140 < x[0] < 700])
low = [x for x in w46 if 140 < x[0] < 700] # EV-22 (PM ruling v3, D4): another writer's phase switch is a mismatch from
# EV-21: with both batteries at the cut-out, the other writer's 3 phases # its first cycle, like a foreign current. Solar writes nothing after it (no
# take the period over the aim, so Solar's peak cut lowers the car first, # cut, no 6 A hold, no pause: it does not cut a car it does not control) and
# within 1 cycle and at 690 W/A (EV-21 T34 (ii)); the 6 A hold and the pause # holds after WRITER_S with one CHARGER_OTHER; the guard's alarm path is the
# follow. Every write in the stretch lowers; none waits for PHASE_GAP_S. # one it has with the car in Off (`car_solar_can_cut` False), which is the
six = [x for x in low if x[1] == 6.0] # alarm. Before (EV-21 T34 (ii) via EV-05): the cut, the 6 A hold and the
check(f"T46 (a)(b): the arithmetic uses the 3 phases the car draws on, and a " # pause were written within the 30 s rule, a 4140 W x 302 s import.
f"lower current (EV-21's cut, the 6 A hold, the pause) is written " n46 = r46["_log"]
f"within the 30 s rule, never blocked by PHASE_GAP_S ({w46})", hold46 = next((x["t"] for x in r46["trace"] if x["hold"]), None)
low and six and six[0][0] <= 171 and low[0][0] <= 171 other46 = [m for m in LOG.since(n46, "WARNING") if "CHARGER_OTHER" in m]
and all(b[1] < a[1] for a, b in zip(low, low[1:])) check(f"T46 (a)(b): no Solar write after another writer's 3 phases at 140 "
and [a for _, a, _ in low][-1:] == [0.0]) f"({[x for x in w46 if x[0] > 140]}), the hold at {hold46} (170), "
imp46 = sum(max(0.0, x["grid"]) for x in r46["trace"] f"CHARGER_OTHER once ({len(other46)})",
if x["t"] > 140 and x["sp"] > 0) not [x for x in w46 if x[0] > 140]
check(f"T46 (c): the car's grid import only within the hold rule " and hold46 is not None and 170 <= hold46 <= 171 and len(other46) == 1)
f"(<= 300 s of 6 A on 3 phases) ({imp46 / 3600:.0f} Wh)", off46 = run("T46 Off", S.drive, step_fn((300, 700.0), (600, 900.0), base=500.0),
imp46 <= 4140.0 * 302.0) const(3500.0), dur=900, first="car", phases=1, mode="off",
sim=SimCharger(setpoint_a=12), socs={"a": 10.0, "b": 10.0},
rows=True, events={140: lambda p, c: p.ch.set_phases(3)})
al_s = [t for t, _n in S.ids(r46, *S.ALARMS)][:1]
al_o = [t for t, _n in S.ids(off46, *S.ALARMS)][:1]
ex_s = [(x["explains"], x["red"]) for x in r46["trace"] if x["t"] >= 142]
ex_o = [(x["explains"], x["red"]) for x in off46["trace"] if x["t"] >= 142]
check(f"T46 (c): the alarm path is the one with the car in Off: the alarm "
f"within 2 s of the Off twin's ({al_s} / {al_o}), car_explains and the "
f"red rows equal in every cycle from 142 s",
al_s and al_o and abs(al_s[0] - al_o[0]) <= 2.0 and ex_s == ex_o)
r46h = std(900, sun=const(3500.0), phases=3, r46h = std(900, sun=const(3500.0), phases=3,
events={200: lambda p, c: p.ch.set_current(16), events={200: lambda p, c: p.ch.set_current(16),
300: lambda p, c: p.ch.set_phases(3)}) 300: lambda p, c: p.ch.set_phases(3)})
File diff suppressed because it is too large Load Diff
+467
View File
@@ -0,0 +1,467 @@
"""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_end", 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()
+1 -4
View File
@@ -44,7 +44,6 @@ REF_S = "until you press Solar: CHARGER_REFUSED."
Q3W = "tries again next quarter: CHARGER_REFUSED." Q3W = "tries again next quarter: CHARGER_REFUSED."
CUTDBG = "The peak cut write failed" CUTDBG = "The peak cut write failed"
REC = "The car charger step failed" REC = "The car charger step failed"
MANUAL_SHA = "284ce1a94bfb7a6335f224a29bddc4e0b80c36af78b5c7907031c511a6a9eaa8"
class Cap(logging.Handler): class Cap(logging.Handler):
@@ -1075,9 +1074,7 @@ check("N5: no select while the car drew (0 A not taken), over every run",
check("N9: no exception out of a step or release in any run (every run " 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)", "completed), and no ERROR record on a cut try (G1)",
not [e for r in CUT_ONLY for e in r.errs]) not [e for r in CUT_ONLY for e in r.errs])
check("T13/N7: ManualWriter's source is 2e09622's, byte for byte", # T13/N7: EV-60 review-time pin; retired by EV-22, which changes ManualWriter by design (C7, DA1)
hashlib.sha256(inspect.getsource(CM.ManualWriter).encode())
.hexdigest() == MANUAL_SHA)
def tsrc(name): def tsrc(name):