EV-21 fix round 2 (review): a cut during Solar's own phase change ends it; wait cap in watts
infra-pin / fresh (pull_request) Waiting to run
checks / unit (pull_request) In progress

PM R1: a cut due while Solar's own phase change is under way (seq set or plan.switch) is 0 A at once and ends the change at its 0 A; the 15 s wait cap is held in watts and converted with the phases at the write. test_ev21_fix2.py: T34 (iv) red at 5759e9d, T34 (v) 3->1, N6/P27 refused close red with seq_uncapped, N9 standing cap red with stale_drop. test_ev21_fix1.py: C18 now R1; C16 and Q1 accepted as coded (R5).

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
ems-agent
2026-11-28 18:27:18 +01:00
co-authored by Claude
parent 5759e9dc9f
commit 83e5b9c51f
4 changed files with 252 additions and 19 deletions
@@ -68,8 +68,12 @@ the failure catalogue it answers.
- **A lowering on its way** (`CUT_SENT_S`, 2 s) counts as Solar's own for
grading, once per value (PM Q1): a re-send of the same value, a retry
included, gets no new grace; after it, not read back is not cut.
- **While the 15 s wait runs** the cap is the current Solar has then (C4: no
raise while due).
- **While the 15 s wait runs** the cap is the power Solar gives the car then
(C4: no raise while due), held in watts and turned into amps with the
phases Solar writes on (PM R1).
- **A cut due during Solar's own phase change ends the change** at its 0 A,
at once (PM R1, C12): no select after it and no closing current. The
read-back may still show the old phases, so a cut is never sized there.
- **Under a cut the plan may lower** (formal C10), by its own 30 s rule.
- **The cut's own ramp-down.** The trusted car figure is capped by the new,
lower read-back, so for one corroboration window (60 s) after a cut the
+28 -7
View File
@@ -13,6 +13,7 @@ import asyncio
import copy
import dataclasses
import logging
import math
from datetime import timezone
from . import carmode, chargers, messages, packshare, peakguard
@@ -299,7 +300,8 @@ class CarMixin:
if key is None or target_w is None or blind \
or not self._car_cut_meter_fresh():
# N9: nothing sized from a stale projection; what stands stays.
w.cut_a = st["cap"] if st["cap"] is not None else st["wait"]
w.cut_a = st["cap"] if st["cap"] is not None \
else self._car_wait_a(st)
return
ex = peakguard.excess_w(real_proj, target_w)
left = QUARTER_S - float(real_proj.elapsed_s)
@@ -319,9 +321,15 @@ class CarMixin:
# charge only counts as headroom for the 15 s wait.
due = ex > 0.0 and running and (drawing or seq_on)
n = self._car_cut_n()
# PM R1 (review r1): a cut due while Solar's own phase change is
# under way (its 0 A sent, or the plan decided it) ends the change at
# its 0 A, at once: never sized on phases the read-back may not show.
change_on = w.seq is not None or w.plan.switch
if st["cap"] is not None:
# A cut stands: deeper only if the excess grows (OQ7); the
# restart rule lifts it.
if due and change_on and st["cap"] > 0.0:
st["cap"] = 0.0
if due and ex > st["ex"]:
st["ex"] = ex
a = carmode.cut_amps(st["car0"], ex, n, st["base"])
@@ -355,17 +363,30 @@ class CarMixin:
room = self._car_cut_headroom(guard)
now_ = (room is None or room <= 0.0 or ex > room
or not self.car_cover or left <= CUT_NEAR_END_S)
if now_ or mono - st["since"] >= CUT_WAIT_S:
a = carmode.cut_amps(st["car0"], st["ex"], n, st["base"])
if now_ or change_on or mono - st["since"] >= CUT_WAIT_S:
a = 0.0 if change_on else carmode.cut_amps(
st["car0"], st["ex"], n, st["base"])
st["cap"] = 0.0 if a is None else a
st["cuts"] += 1
st["wait"], st["at"] = None, mono
w.cut_a = st["cap"]
return
# C4: due and waiting: no raise meanwhile.
st["wait"] = w.plan.a if st["wait"] is None \
else min(st["wait"], w.plan.a)
w.cut_a = st["wait"]
# C4: due and waiting: no raise meanwhile. PM R1: held in watts (the
# plan's current on its phases), turned into amps with the phases at
# the write.
p = w.plan
now_w = float(p.a) * carmode.VOLTS * (p.n if p.n in (1, 3) else n)
st["wait"] = now_w if st["wait"] is None else min(st["wait"], now_w)
w.cut_a = self._car_wait_a(st)
def _car_wait_a(self, st):
"""PM R1: the 15 s wait's cap, held in watts, as amps on the phases
Solar writes on now (the plan's), rounded down. None: no wait."""
if st["wait"] is None:
return None
n = self.car_solar.plan.n
n = n if n in (1, 3) else self._car_cut_n()
return float(math.floor(st["wait"] / (carmode.VOLTS * n) + 1e-9))
@property
def car_cover(self) -> bool:
+11 -10
View File
@@ -122,7 +122,7 @@ und = [x for x in rows if x["t"] > 1200 and x["under"] is not None]
u = und[0] if und else {}
left = 900.0 - (u.get("t", 0) - 900.0)
full = (u.get("proj") or 0) + 4140.0 * left / 900.0
check(f"C16 (pinned, not a ruling): a partial cut to "
check(f"C16 (accepted as coded, PM R5): a partial cut to "
f"{part[0]['cap'] if part else None} A; the restart clock starts at "
f"{u.get('t')} with the projection {u.get('proj') or 0:.0f} W under "
f"the aim while the car still draws {u.get('car')} W; with a full 6 A "
@@ -148,15 +148,16 @@ r = drive(step_fn((tb + 1, 9280.0 + 3400.0 + 1500.0), base=900.0),
rows = r["rec"].rows
wait = [x for x in rows if x["t"] >= tb + 1 and x["wait"] is not None]
close = [(t, a) for t, a, _ in after(r, tb + 1) if a > 0.0]
caps = [(x["t"], x["cap"]) for x in rows if x["t"] >= tb + 1
and x["cap"] is not None]
sel = [(x[0], x[2]) for x in r["sim"].log if x[1] == "phases"
and x[0] >= tb]
caps = [x["t"] for x in rows if x["t"] >= tb + 1 and x["cap"] is not None]
check(f"C18 (pinned, not a ruling): Solar's change began at {tb}; the cut "
f"due at {wait[0]['t'] if wait else None} waits (cap "
f"{wait[0]['wait'] if wait else None} A); during the wait the change "
f"selects {sel} and closes at {close[:1]}; the cut at {caps[:1]}",
bool(wait) and bool(close) and close[0][1] <= wait[0]["wait"]
and (not caps or close[0][0] <= caps[0]))
and caps and x[0] > caps[0][0]]
check(f"C18 (PM R1, ruled): Solar's change began at {tb}; a cut due during "
f"it does not wait (wait rows {[x['t'] for x in wait][:2]}): it ends "
f"the change at its 0 A at once (cut {caps[:1]}); no select after it "
f"({sel[:1]}), no closing current ({close[:1]})",
not wait and bool(caps) and caps[0][1] == 0.0
and caps[0][0] <= tb + 2 and not sel and not close)
# Q1 (other writer): another writer raises the current inside the 2 s grace
# of Solar's lowering. Pinned: until the next writer step marks the
@@ -171,7 +172,7 @@ c.car.reading = dataclasses.replace(rd, allowed_a=16.0, setpoint_a=16.0)
in_grace = c.car_solar_can_cut()
w.mismatch_since = c.car_now()
marked = c.car_solar_can_cut()
check(f"Q1 other writer (pinned, not a ruling): Solar sent 0 A, another "
check(f"Q1 other writer (accepted as coded, PM R5): Solar sent 0 A, another "
f"writer shows 16 A inside the 2 s grace: can-cut {in_grace} until the "
f"difference is marked, then {marked}", in_grace is True
and marked is False)
+207
View File
@@ -0,0 +1,207 @@
"""EV-21 fix round 2 (review of 5759e9d, PM rulings R1-R5).
`python3 -B test_ev21_fix2.py`
- T34 (iv), R1: the reviewer's repro. Solar's own 1 -> 3 change has sent
its 0 A, the read-back is 4 s late (still 16 A on 1 phase), the house
heads the period over with no battery headroom. A cut due during Solar's
own change ENDS the change at its 0 A: no select after it, no closing
current, the car never draws more than before the cut.
- T34 (v), R1: the same for a change from 3 phases to 1.
- N6 / P27, R2: a refused closing write retried under a cut that came in
between is never above the cut's cap (the `_seq_want` cap).
- N9: a standing cap survives a cycle with a blind guard or a stale meter.
The real Controller on `tools/ev20_sun.py` through `tools/ev21_kit.py`, and
for the N6/P27 row the real `SolarWriter` on a stub charger.
Mutating a module this file grades? Read MUTATION.md first (purge __pycache__).
"""
import asyncio
import dataclasses
import os
import sys
from datetime import datetime, timezone
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, "tools"))
from app import carmode, chargers as CH # noqa: E402
from ev20_kit import LOG, check, fails, const, step_fn # noqa: E402
from ev21_kit import AIM, after, drive, both, _mode, shape, never # noqa: E402
n_log0 = LOG.mark()
def lag(s):
def f(p, c):
p.ch.lag_s = s
return f
def own_change_run(sun, kw, house_w, find):
"""Run once to find Solar's own change (`find(log)` gives the second of
its 0 A), then again with the house at `house_w` from one second
later. Both batteries switched off in battery modes (no headroom), the
read-back 4 s late, the write beside the cycle."""
ev = {0: both(lag(4.0), _mode("ab", False))}
r0 = drive(const(900.0), sun, **dict(kw, events=ev))
tb = find(r0["c"].car_solar.log)
kw = dict(kw, dur=(tb or 400) + 120)
r = drive(step_fn(((tb or 400) + 1, house_w), base=900.0), sun,
**dict(kw, events=ev))
return tb, r
def zero_before_select(log, n_to):
"""The 0 A that began Solar's change to `n_to` phases."""
sel = [t for k, a, t, ok in log if k == "phases" and a == n_to]
z = [t for k, a, t, ok in log if k == "current" and a == 0.0
and sel and t <= sel[0]]
return int(z[-1]) if z else None
def judge(name, tb, r):
rows = r["rec"].rows
t1 = (tb or 0) + 1
pre = [x["car"] for x in rows if x["t"] == t1 - 1]
car_pre = pre[0] if pre else None
first = next((x for x in rows if x["t"] >= t1 and x["cap"] is not None),
{})
nz = [(t, a) for t, a, _ in after(r, t1) if a > 0.0]
sel = [(x[0], x[2]) for x in r["sim"].log
if x[1] == "phases" and x[0] > first.get("t", 1e9)]
more = [(x["t"], x["car"], round(x["proj"] or 0)) for x in rows
if x["t"] > t1 and x["cap"] is not None
and x["car"] > (car_pre or 0.0) + 50.0]
check(f"{name}: Solar's change began at {tb}; the house heads over at "
f"{t1}; the cut at {first.get('t')} is {first.get('cap')} A (the "
f"change ends at its 0 A); no select after it ({sel[:2]}), no "
f"non-zero write ({nz[:3]}), the car never above its "
f"{car_pre} W before the cut ({more[:3]})",
tb is not None and first.get("cap") == 0.0
and first.get("t", 1e9) <= t1 + 1 and not sel and not nz
and not more)
never(name, r)
# =========================================================================== #
print("\n1. T34 (iv), (v): A CUT DURING SOLAR'S OWN CHANGE ENDS IT (PM R1)")
# =========================================================================== #
# (iv) 1 -> 3: the reviewer's repro (review of 5759e9d, Major 1).
kw = dict(dur=700, first="car", phases=1, socs={"a": 10.0, "b": 10.0},
opts={"ev_phases": "auto"}, beside=True)
tb, r = own_change_run(const(9280.0), kw, 11500.0,
lambda log: zero_before_select(log, 3))
judge("T34 (iv) 1 -> 3, late 0 A read-back", tb, r)
# (v) 3 -> 1: Solar runs 3 phases (up at about 300 s), the sun falls to a
# target under 4 kW at 700 s, the change down comes after the 300 s dwell
# and the 600 s phase gap; the house heads over during it.
sun5 = step_fn((700, 900.0 + 3500.0 + 100.0), base=9280.0)
kw = dict(dur=1200, first="car", phases=1, socs={"a": 10.0, "b": 10.0},
opts={"ev_phases": "auto"}, beside=True)
tb, r = own_change_run(sun5, kw, 11500.0,
lambda log: zero_before_select(log, 1))
judge("T34 (v) 3 -> 1, late 0 A read-back", tb, r)
# =========================================================================== #
print("\n2. N6 / P27: A REFUSED CLOSE RETRIED UNDER A CUT (PM R2)")
# =========================================================================== #
UTC = datetime(2026, 11, 23, 12, 0, tzinfo=timezone.utc)
class Drv:
"""A charger whose read-back follows at once; `refuse` makes it refuse a
current write."""
polls = ()
def __init__(self):
self.a, self.n, self.refuse = 0.0, 1, False
async def write_current(self, a, **kw):
if self.refuse:
return False
self.a = float(a)
return True
async def write_phases(self, n):
self.n = n
return True
def rd(a, n, e):
return CH.ChargerReading(
available=True, state="C" if a > 0 else "B", connected=True,
charging=a > 0, power_w=a * 230.0 * n, energy_kwh=e,
current_a=tuple(a if i < n else 0.0 for i in range(3)),
setpoint_a=a, allowed_a=a, phases_allowed=n)
async def refused_close(cap):
"""Solar's own 1 -> 3 change; its closing write is refused; then a cut
of `cap` A comes before the retry 5 s later. Returns (the refused
close, the writes after the cut)."""
w, tr, drv = carmode.SolarWriter(), CH.CarTracker(), Drv()
e = [4000.0]
sun = carmode.SunInputs(target_w=9180.0, auto=True, spare_w=9280.0,
margin_w=100.0)
refused, t = None, 0.0
async def step(t, cut=None):
r = rd(drv.a, drv.n, e[0])
e[0] += drv.a * 230.0 * drv.n / 3.6e6
tr.observe(r, t, UTC, "2026-11-23")
w.cut_a = cut
await w.step(drv, r, mode=carmode.SOLAR, sun=sun, clamp=16.0, now=t,
tracker=tr, writing=True, status=CH.CHARGING,
clock=lambda: t)
while t < 900.0 and refused is None:
q = w.seq
drv.refuse = bool(q is not None and q.get("stage") == "settle"
and drv.n == 3)
n0 = len(w.log)
await step(t)
bad = [x for x in w.log[n0:] if x[0] == "current" and not x[3]
and x[1] > 0.0]
if bad:
refused = bad[0]
t += 1.0
drv.refuse = False
n1 = len(w.log)
for _ in range(12):
await step(t, cut=cap)
t += 1.0
return refused, [(x[2], x[1]) for x in w.log[n1:] if x[0] == "current"]
refused, later = asyncio.run(refused_close(6.0))
check(f"N6/P27: Solar's closing write {refused} is refused; a cut to 6 A "
f"comes before its retry: the retry is never above 6 A ({later})",
refused is not None and refused[1] > 6.0 and bool(later)
and all(a <= 6.0 for _t, a in later))
# =========================================================================== #
print("\n3. N9: A STANDING CUT SURVIVES A STALE CYCLE")
# =========================================================================== #
r = shape("C", dur=1000)
c = r["c"]
st = c._cut
cap0 = st.get("cap")
t = c.car_now()
blind = dataclasses.replace(c.peak_guard, blind="meter gap")
c.car_solar.cut_a = None
c._car_cut_tick(c._peak_proj_real, blind, AIM, t)
a_blind = c.car_solar.cut_a
c.car_solar.cut_a = None
c._car_cut_meter_fresh = lambda: False
c._car_cut_tick(c._peak_proj_real, c.peak_guard, AIM, t)
a_stale = c.car_solar.cut_a
check(f"N9: a cut of {cap0} A stands; a cycle with a blind guard gives the "
f"writer {a_blind} A, one with a stale meter {a_stale} A: the cap "
f"stays", cap0 is not None and a_blind == cap0 and a_stale == cap0)
tb_ = LOG.tracebacks(n_log0)
check(f"N11: no traceback in this file's runs ({tb_[:1]})", not tb_)
print(f"\n{'FAILED: ' + str(len(fails)) if fails else 'ALL PASSED'}")
sys.exit(1 if fails else 0)