Compare commits

...
27 Commits
Author SHA1 Message Date
admin 0c7e786ed5 Merge pull request 'SAFETY-25: record the owner's decision - Option A, with ALLOC-01 as the revisit trigger' (#39) from SAFETY-25-decision into release/1.0 2026-09-02 00:58:15 +02:00
glenn schrooyenandClaude Opus 5 ab6fbe2f9e SAFETY-25: record the owner's decision - option a, with alloc-01 as the revisit trigger
checks / unit (pull_request) Successful in 3m43s
The product owner answered SAFETY-25's §1 on 2026-09-02: OPTION A. The BMS
cut-out is the DELIBERATE and only backstop for demand-driven discharge on the
grid-following loop, and Option B - a loop-side reserve floor - is DEFERRED
rather than rejected.

Option A is the shipped behaviour, so this is a recording, not a change. `app/`
is touched in exactly two places and both are comments that claimed the question
was still open (freeze.py's finding, peakguard.py's point 2). No setpoint, no
claim, no option, no default moved. The 17-suite run is green on the same
numbers as before.

WHY DEFERRING IS THE SAFE DIRECTION. Option B's proof - bms_soc_floor <
loop_soc_floor <= peak_soc_floor, run through the real arbiter in
test_peakguard.py part 10d - has an unstated premise: the reserve predicate and
discharge_permitted() read the SAME state of charge. With two packs they read
different numbers. The reserve binds on the emptier pack and files hi = 0; the
peak guard, reading the other pack or an average, files lo = excess > 0; lo > hi
is arbiter clause 3 and the answer is 0 W - the battery parked in the billed
quarter, which is the failure the memo itself marks fatal. And no config
validator can catch it: it is a runtime divergence between two readings, not a
config ordering, so CFG-01's shape of check passes on the exact tree that parks
the battery. Option A's cost is energy; Option B's cost built too early is the
one quarter of the month that sets the bill.

THE REVISIT TRIGGER IS ALLOC-01, recorded in §0c. Under ARCH-01's host-side
allocator the two claims stop sharing a list: the loop floor becomes a
per-inverter `hi` consumed as an INTERVAL at stage A, while the peak floor stays
a site `lo` at stage B. Different claim lists, different stages, structurally
unable to cross - a stronger argument than the ordering rule, because it makes
the crossing unreachable rather than harmless. That is the shape in which Option
B becomes safe to build.

WHAT HAS TO BE RE-EARNED AT N=2 is stated plainly in §0d rather than left for
someone to discover. SAFETY-27 now names five floors across two packs, so "the
SoC" stops being a scalar the config can bound. And part 10f - the pin that made
SAFETY-25 mergeable - CANNOT EXPRESS TWO PACKS: its dynamic half is a scalar
0-100 % SoC sweep against a single-series capture, and a two-pack exposure lives
in the DIFFERENCE between two readings, which that sweep visits at no
resolution. Its static half, the AST scan pinning the eight claim sources, still
bites at N=2; the dynamic half goes silent. Merging a two-pack reserve on 10f's
current green would be merging on a check that cannot see the failure.

The options analysis is kept intact on purpose - §1-§7 stand exactly as written,
including §5's "(recommended)" on Option B and §6's recommendation, with a new
§0 saying what was decided and §6 marked as answered. A memo that recorded the
verdict and deleted the reasoning is the failure this DECISIONS/ directory
exists to prevent.

Part 10e's check moved with the memo: it used to pin the honest "Status: OPEN"
line and now pins that the memo names the option, the date and the trigger AND
still carries both options and the recommendation. The tripwire itself stays -
a ninth claim source in Controller.cycle() still takes 10f red on the line it is
written, and "deferred" is precisely the state in which someone builds Option B
by accident.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-02 00:46:54 +02:00
admin 1c59cfeaf5 Merge pull request 'TEST-13: grade record_block()'s policy argument, and the two import spellings SAFETY-20's check could not see' (#38) from TEST-13 into release/1.0 2026-09-01 09:16:37 +02:00
glenn schrooyenandClaude Opus 5 acbdf41248 TEST-13: grade record_block()'s policy argument, and the two import spellings SAFETY-20's check could not see
checks / unit (pull_request) Successful in 3m55s
Two survivors from TARIFF-01's review, closed in test_tariff.py only. app/ is
untouched and no shipped behaviour changes. Two further items on the card were
already closed in shipped code and are struck rather than re-implemented.

ITEM 1 - the per-phase reduction's PLUMBING was unobservable.

  Mutating PeakStore.record_block()'s `billed_w(block, policy)` to
  `billed_w(block, POLICY_NET)` (+4 B) leaves all 17 suites green. Measured
  three times now: by TARIFF-01's reviewer, re-run through TEST-15's purge
  harness this session, and re-run again here on a clean uncontended tree.

  The product code is correct - tariff.py:363 really is
  `def record_block(self, block, policy: str = POLICY_NET)` and it really does
  forward the argument. What was missing is any check that could tell that
  apart from a hardcoded call, and the reason is the third instance of one
  shape: A STIMULUS EVALUATED WHERE THE QUANTITY IT GRADES IS DEGENERATE, after
  WITNESS-02's span normalisation and TARIFF-01's own DST window.

  billed_w() short-circuits to block.offtake_avg_w whenever
  per_phase_offtake_avg_w is absent. Every block reaching a store anywhere in
  the suite was single-phase or built as _CB(..., None) - so NET, SUM and MAX
  collapsed onto one number and the argument could not be observed at the call
  site. Section 7 grades the FUNCTION on an unbalanced fixture and says nothing
  about its CALLER.

  So section 7's own (3000, 500, -200) W block - whose three reductions are
  3300 / 3500 / 3000 W, asserted distinct three lines above - is now
  round-tripped THROUGH the store under each policy and read back from both
  tables (peak() and recompute_month(), so both writes in that single
  transaction are graded). record_block() with no policy is checked to bank the
  NET figure. An anti-degeneracy pin is stated over the three BANKED numbers,
  not over vals, because it is the banked ones this triple is made of.

  Direction, which is why this is worth plumbing-testing: NET is the SMALLEST
  of the three here, because the exporting phase nets off. A store that quietly
  billed NET while asked for MAX would UNDER-record the month's peak, and an
  under-recorded peak is maximum headroom for SAFETY-07 - the same
  under-guarding direction as the getattr(..., 0.0) default SAFETY-07 already
  removed from project().

ITEM 2 - the SAFETY-20 import grader claimed more than it checked.

  It collected `m.module for m in walk(tree) if isinstance(m, ImportFrom)` and
  matched a literal list of six spellings. That is blind to two of Python's
  three import forms:

    * `from . import arbiter as _ab` is an ImportFrom whose .module is None -
      the dots are in .level and the module name is in .names - so it collected
      "" and matched nothing;
    * `import app.arbiter` is an ast.Import node the walk filtered out entirely.

  Both were added to app/tariff.py and the shipped suite stayed GREEN, with the
  _names half not firing either (an alias import creates no Name node). Low
  severity: any USE of either alias still produces an Attribute the _names half
  catches. But the printed sentence "it imports nothing from arbiter, clamp or
  control" was false for two forms out of three, and a check that overclaims is
  worse than one that claims less, because the next reader stops looking.

  _imported_modules() now walks Import as well as ImportFrom and joins
  `from . import X` onto its base. _forbidden_imports() matches per dotted
  SEGMENT, not by substring: `app.arbiter` must not hide behind a package
  prefix, and `clamps` / `arbiters` / `controller` must not be falsely flagged -
  `controller` is not hypothetical, this package is goodwe_controller. Five
  evasion spellings and eight innocent ones grade the grader itself, and both
  the name half and the import half are shown non-vacuous against main.py,
  which carries all three import forms and really does import all three modules.

ITEMS 3 AND 4 - ALREADY CLOSED. STRUCK, NOT RE-IMPLEMENTED.

  Item 3: app/tariff.py:266-267 is `def is_observed(self): return self.state ==
  OBSERVED`, already false for NO_RECORD. Nothing to do.

  Item 4: app/tariff.py:672-680 reads `held = max(averager.held_net_w, 0.0)`
  with NO getattr default, and carries a comment naming TEST-13 item 4. Fixed
  by SAFETY-07 in 616b62d; held_net_w is a documented public property on
  QuarterAverager (p1.py:290), so a rename raises AttributeError on the first
  cycle instead of crediting 0 W held. A projection crediting 0 W held reads
  LOW, which is the under-guarding direction for SAFETY-07's floor. Restoring
  a default would re-open a money guard.

  And the recorded NON-finding stays a non-finding: removing clear_partial()
  is still green and that is a PASS. quarter_start is the PRIMARY KEY and the
  upsert carries `ON CONFLICT ... WHERE excluded.offtake_avg_w >
  quarter_blocks.offtake_avg_w`, so a replay is a structural no-op. That
  demonstrates TARIFF-01's "double counting is answered structurally, not by
  care" claim rather than contradicting it.

EVIDENCE - all through tools/mutation_run.sh (recursive __pycache__ purge,
python3 -B, tree re-read from disk, mutated line grepped off disk, byte delta
recorded), in the goodwe-addon-ci image against a :ro mount.

  baseline, 17 suites, before any edit ............................ 17 PASS
  baseline, 17 suites, final tree ................................. 17 PASS

  A1  billed_w(block, policy) -> billed_w(block, POLICY_NET)   +4 B  5 RED
      the 'sum' and 'max' round-trips, both tiers, and the distinctness pin
  A2  billed_w(block, policy) -> billed_w(block, POLICY_MAX)   +4 B  6 RED
      the 'net' and 'sum' round-trips, both tiers, the default, and the pin
  B1  add `from . import arbiter as _ab` to app/tariff.py     +29 B  1 RED
      the import sentence. SHIPPED suite on the same tree: GREEN - the hole.
  B2  add `import app.arbiter` to app/tariff.py               +19 B  1 RED
      the import sentence. SHIPPED suite on the same tree: GREEN - the hole.
  B3  add `from .control import compute` (the form the OLD grader DID
      catch, as a regression control)                                1 RED
  C1  delete the ast.Import branch from _imported_modules()          1 RED
      names the two spellings it MISSED, so the grader-grader is live
  C2  segment match -> substring match (`any(f in m for f in ...)`)  1 RED
      names clamps / arbiters / controller as falsely flagged

  CONTROL, and the point of the whole ticket: A1 graded by the SHIPPED
  test_tariff.py is green, and A1 graded by all 17 SHIPPED suites on a clean
  uncontended run is 17 PASS, rc=0. The survivor is real and it is now closed.

ONE THING THE REVIEWER SHOULD KNOW. During the first (contended - two docker
containers at once) run of that 17-suite survivor sweep, test_peakguard.py
reported FAIL once. It has passed 8 times since on the identical tree,
including three concurrent runs and one clean uncontended full sweep, and its
tail was lost to a grep so I cannot say which check it was. I believe it is a
timing-sensitive check under CPU contention and NOT related to this change -
this commit touches no product code and no peakguard fixture - but I could not
reproduce it, so I am recording it rather than asserting it away.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-01 08:40:09 +02:00
admin 950472662e Merge pull request 'TEST-16: pin the two one-sided arbitrage rungs, and un-mask them from each other' (#37) from TEST-16 into release/1.0 2026-09-01 08:02:57 +02:00
glenn schrooyen 6ea84a46f6 Merge remote-tracking branch 'origin/release/1.0' into TEST-16
checks / unit (pull_request) Successful in 3m41s
# Conflicts:
#	goodwe_controller/CHANGELOG.md
2026-09-01 07:54:52 +02:00
admin 48cd5f31ca Merge pull request 'TEST-11: pin the clamp guard to the write it reads' (#36) from TEST-11 into release/1.0 2026-09-01 07:45:15 +02:00
glenn schrooyenandClaude Opus 5 20f9f4969d TEST-16: pin the two one-sided arbitrage rungs, and un-mask them from each other
checks / unit (pull_request) Successful in 3m51s
SAFETY-26's AC4 gave the same tolerance mutation to every price and quantity
boundary in arbitrage.py and static_tariff.py. Everything in arbitrage.py went
red - `price < 0`, `soc <= floor_pct`, `soc >= ceiling_pct` are each red under
+/-5. Two survived, both in static_tariff.py, and this card closes them.

  D  `spread == 0.0` (:912) weakened to `spread <= 0.001` SURVIVED at +2 B.
  F  `len(firm) < 2` (:901) weakened to `len(firm) < 1` SURVIVED at +0 B - the
     delta MUTATION.md names as the risky one.

THE DEFECT IS NOT EITHER ROW, IT IS THE INTERACTION. D and F MASK EACH OTHER. A
single firm hour also has a spread of 0.0, so with F weakened the flat rung
refuses the stimulus anyway; with D weakened the small-but-real spread is still
refused, only for a lie. Each rung's failure is absorbed by the other, so BOTH
can be weakened together and a suite grading `kind == "refused"` reports
nothing. That is structurally invisible to single-mutation testing, which is how
this pair came through four rounds of review on TARIFF-03 and FCST-03 - and it
is the arrangement in which the next edit to either rung opens a real hole with
nothing to report it.

D is not cosmetic either. With the tolerance in place a series priced 0.20000 /
0.20050 - a REAL 0.0005 EUR/kWh spread - flips ALLOWED to REFUSED at
min_spread_eur_kwh=0.0, a value arbitrage()'s own docstring documents ("pass 0.0
to mean any positive spread, explicitly") and its validator at :861 accepts on
purpose. At a shipped threshold the outcome does not move, but the operator
reads the false sentence "the tariff is flat - every one of the 2 firm hours
costs 0.2000 EUR/kWh" about a tariff that is not flat.

WHAT WAS ADDED. test_static_tariff.py section 9, and the shape of it is the
argument:

  * THE REASON IS GRADED, NOT THE VERDICT. The masked case refuses CORRECTLY
    while reporting the wrong sentence, so a check asserting only "refused"
    passes on a broken tree. A `rung9()` helper names which refusal answered,
    from the sentence the operator would read; an unrecognised refusal reports
    itself as UNATTRIBUTED rather than quietly matching nothing.
  * EACH RUNG IS GIVEN A STIMULUS THE OTHER CANNOT ABSORB, or the pinning is
    circular. The flat rung gets a THREE-firm-hour flat series, which no
    `len(firm) < N` a person would write can reach. The firm-pair rung gets a
    ONE-FIRM-HOUR series, which the flat rung CAN reach - so its attribution is
    the whole check, and that is why it is written as a rung name rather than a
    verdict.
  * AC1 is a sweep of small-but-real spreads (0.0005 down to 0.000001) all
    ALLOWED at min_spread_eur_kwh=0.0, with the exactly flat series on the other
    side still refused BY THE FLAT RUNG - without that mirror the sweep would
    also pass for a rung deleted outright. 1e-6 is the floor because the shipped
    line rounds the spread to 6 decimals; that quantisation is graded in the
    open as its own row rather than left unstated.
  * AC3 is a five-row table graded on rung attribution, which denies the masking
    from both sides at once.
  * The firm-pair count is also pinned from ABOVE (`< 3`) and BELOW (`< 0`),
    which the criteria do not ask for but which is what stops this section being
    one-sided in exactly the way it was written to fix.

EVIDENCE. Eight rounds through TEST-15's tools/mutation_run.sh, used UNCHANGED:
recursive __pycache__ purge before each run, python3 -B, the tree re-copied FROM
DISK between rounds, the mutated line grepped out of the file before the run,
byte delta printed, test_static_tariff.py and test_arbitrage.py graded each
time. Baseline green.

  baseline, shipped                            +0 B  PASS
  D1  `spread == 0.0` -> `<= 0.001`            +2 B  RED, 3 checks
  D2  `spread == 0.0` -> `<= 0.000001`         +5 B  RED, AC1 alone
  D3  `spread == 0.0` -> `< 0.0`  (rung gone)  +0 B  RED (section 2 as well)
  F1  `len(firm) < 2` -> `< 1`                 +0 B  RED, 3 checks
  F2  `len(firm) < 2` -> `< 3`                 +0 B  RED, 6 checks
  F3  `len(firm) < 2` -> `< 0`  (rung gone)    +0 B  RED (ValueError)
  D1+F1  BOTH AT ONCE - THE TICKET             +2 B  RED, 5 checks

Four of the seven are +0 B, the delta MUTATION.md names as the one stale
bytecode can hide. All are REDS, the direction that defect cannot fabricate -
but they were run under the purge anyway, because "it went red so the cache
cannot have lied" is a conclusion and not a procedure.

NO SHIPPED BEHAVIOUR CHANGED. app/ is untouched; both rungs were correct all
along, and the card is explicit that a rung found actually wrong is a stop-and-
report rather than an edit. Also updated: MUTATION.md gains a short section on
masking as a SECOND way a survivor lies, with the two rules that fall out of it
(grade the reason, and mutate suspected pairs together); and test_arbitrage.py's
SAFETY-26 AC4 note is marked closed rather than left reading as an open finding.

UNSURE ABOUT. The 5e-7 row asserts the shipped `round(spread, 6)` quantisation.
That is a real property of the line and worth stating, but it does pin a
rounding the ticket never named - if a reviewer would rather that stayed
unpinned, it is one check to drop and nothing else depends on it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-01 07:37:19 +02:00
Claude b68f288fef TEST-11: pin the clamp guard to the write it reads
checks / unit (pull_request) Successful in 3m40s
check_output_clamp() sits one line below `await self.write_setpoint(self.target)`
in cycle(), and moving it above the write left test_clamp.py, test_freeze.py and
test_loop.py ALL GREEN. Measured on the move itself before this commit; measured
again after, where test_clamp.py part 6 goes red and the other two are still
green - the gap was real and it was only ever in this file.

WHAT IS ACTUALLY LOST. The guard has two evidence sources. `self.loop_clamped`
is set from the Decision well above the write and survives the move, and on the
10.3 runaway replay it is the source of every engagement the alarm reports (0
write-path engagements against 2 loop-side ones) - which is exactly what makes
the move nearly invisible. `self.clamp_last` is assigned by write_setpoint() and
by nothing else, is None until it has run, and is what `engaged_write` reads at
main.py:856. Moved above the write, that consumer goes quietly false and a
DEVICE-bound clamp - max_w above the inverter's own rating, SAFETY-20's install -
is reported by nothing. A guard whose second evidence source can be silently
disconnected is one refactor from being half a guard.

WHAT THE CHECK PINS, AND WHAT IT DELIBERATELY DOES NOT. Not the position: the
comment at that line warns against tidying SAFETY-03's ordering and SAFETY-18's
into one rule, and a check a rename breaks is worse than none. It pins the
CONSEQUENCE - what `self.clamp_last` held each time the guard consulted the
watchdog - using a spy subclassed from the shipped ClampWatchdog over a
slew-limited ramp where every cycle's command is a different number, so "this
cycle's evidence" and "last cycle's" are distinguishable at all. The spy hooks
`clamp_wd.note()`, the consumer, rather than the guard's name: that is what
keeps a rename legitimate. The same assertions are re-run through a controller
whose guard is renamed and whose write lives in a helper, and were verified
against main.py itself - renaming the method throughout AND moving both calls
into a new `_emit_and_guard()` helper keeps part 6 green; swapping the two calls
turns it red on a line that names clamp_last.

WHY AC 3 NEEDED A NEW STIMULUS, AND WHY IT IS NOT DRIVEN THROUGH cycle().
Through the real cycle() the write-path half cannot engage: the arbiter files
the device range and max_w as P_SAFETY LIMIT claims, so resolution.target_w is
already inside both bounds before write_setpoint() re-applies them. That
duplication is deliberate defence in depth; part 6 now MEASURES the zero
engagements rather than leaving it as a claim in a comment, and then drives the
write path directly at max_w 5000 against a +-2500 W device - the wire carries
2500 W, every loop-side flag stays clean, and the alarm fires on clamp_last
alone. With the two calls swapped the same stimulus clamps the same value and
the alarm is silent, which is the ticket in one pair of runs.

main.py gains one comment sentence naming the check, mirroring the one
SAFETY-18's block already carries for test_freeze.py part 5. No behaviour
changes.

Full suite: 17/17 green in goodwe-addon-ci.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-01 07:31:26 +02:00
admin e8fb596b99 Merge pull request 'TEST-10: pin max_w beside the meter_freeze_s key TEST-06 already pinned' (#35) from TEST-10 into release/1.0 2026-09-01 07:00:03 +02:00
glenn schrooyenandClaude Opus 5 d0b053b150 TEST-10: pin max_w beside the meter_freeze_s key TEST-06 already pinned
checks / unit (pull_request) Successful in 3m43s
max_w and the LIVE_MAX_W literal beside it were the two survivors left
after TEST-06 pinned meter_freeze_s: changing max_w 2000 -> 4500 in
config.yaml passed every check in test_freeze.py and test_tariff.py
GREEN, and LIVE_MAX_W = 5000.0 was a bare literal that silently
disagreed with the shipped max_w (2000) with nothing in the file
saying so. For contrast, deadband_w 15 -> 5 already went RED 2 + 1,
so the pinning technique was known to work - it just was not applied
to the key either side of it.

Three changes, each measured:

1. test_freeze.py gains a check comparing Tuning()'s code default
   (control.py, 2000.0) against SHIPPED_MAX_W, read from config.yaml
   by extending the file's existing _cfg_default() regex reader
   rather than reimplementing test_arbitrage.py's _shipped. Broken
   and confirmed red: max_w: 2000 -> 4500 in config.yaml now fails
   exactly "the code default and the shipped default agree on max_w
   too" and nothing else in either file; reverting returns both files
   to all-green. (AC 1, AC 4)

2. LIVE_MAX_W is renamed LIVE_INSTALL_MAX_W in both test_freeze.py
   and test_tariff.py, each with a comment stating plainly that 5000
   is the live install's own override, not config.yaml's shipped
   max_w (2000) - the defect was a literal that could be misread as
   the shipped default, not the number itself. (AC 2)

3. test_freeze.py states PINNED_KEYS = ("meter_freeze_s", "deadband_w",
   "max_w") in one place as the complete set of config keys this
   suite pins. Deliberately excludes maintenance_* - CFG-03 (merged
   into release/1.0 since this branch started, merged in here) gave
   those keys a separate single source of truth in app/maintenance.py
   and this ticket has no reason to duplicate that pin. Not every key
   in config.yaml is pinned here on purpose: meter_freeze_s,
   deadband_w and max_w are the three this file's mutual-exclusion
   arithmetic (section 2b) actually reasons about together. (AC 3)

Full 17-file suite run green under goodwe-addon-ci after the merge
with release/1.0 (f630ed9, CFG-03). CHANGELOG.md updated under
Unreleased.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-01 06:48:05 +02:00
admin f630ed949b Merge pull request 'CFG-03: give maintenance option defaults one source of truth' (#34) from CFG-03 into release/1.0 2026-09-01 06:28:57 +02:00
glenn schrooyenandClaude Opus 5 d5b1ef19b3 CFG-03: give maintenance option defaults one source of truth
checks / unit (pull_request) Successful in 3m44s
Option defaults for the maintenance cycle were declared in three places that
could disagree, and MAINT-04 proved they already did. config.yaml shipped
`maintenance_charge_w: 2000`; main.py carried TWO `opts.get(..., 2500)`
fallbacks; MaintConfig's dataclass carried a third `2500.0`. So an options dict
with the key ABSENT was ACCEPTED by validate.py's rule 6 - which read 2000 -
and then built by main.py at 2500, against a 2000 W ceiling:

    options dict with maintenance_charge_w ABSENT, max_w=2000
      validate_startup_config  ->  []  (accepted, no problems)
      MaintConfig().charge_w   ->  2500.0
      arbiter.resolve()        ->  0.0 W, contradiction=True

That is the bug rule 6 exists to refuse, passing rule 6. It is unreachable on a
Supervisor install, which always supplies every key from config.yaml, and fully
reachable from sim/inject.py and from the test suite - which is where anyone
debugging maintenance actually works.

MAINT-04 shipped a TRIPWIRE and said so: test_validate.py pinned all three
literals and asserted the consequence through the real arbiter, so the
divergence could not silently widen or be half-closed. Its PASSING CONDITION
WAS THE BUG. Both it and validate.py's comment said to delete each other when
the divergence was closed. It is closed, so both are deleted.

THE DIVERGENCE WAS WIDER THAN ONE KEY. `maintenance_discharge_w` had the
identical three-way split (config.yaml 2000, MaintConfig 2500) and the card
named only the charge side. Closing one and leaving its twin would have
satisfied the numbers and left three sources of truth one line down, which is
the state that produced the bug. Both are closed, and so is the whole family:
all eight `maintenance_*` keys go through the same mechanism.

WHAT THE SINGLE SOURCE IS. config.yaml's `options:` block - it is what the
Supervisor reads and what the operator edits, so it wins by definition. There
is now exactly one in-code copy, `maintenance.MAINT_OPTION_DEFAULTS`, which is
TARIFF-02's `PRICE_OPTION_DEFAULTS` and SAFETY-24's `PEAK_OPTION_DEFAULTS`
pattern applied to the family that named the card - validate.py's rule 8 comment
already called that "CFG-03 read as a rule rather than as a complaint", so this
makes the rule hold where it was first broken rather than inventing a fourth
mechanism for one option family.

A MIRROR RATHER THAN A RUNTIME READ, and the reason is mechanical: the
Dockerfile copies `app/` and `run.sh` into the image and NOT config.yaml. The
running add-on cannot open the file it is configured by, so there is nothing to
read at 03:00 on a client's Pi, and a YAML-subset parser that could fail at
import is a new way for the add-on not to start. What makes the copy safe is
that test_maintenance.py pins every entry by READING the shipped file - drift is
a CI failure, not a comment.

EVERY OTHER SITE NOW DERIVES FROM IT OR HAS CEASED TO EXIST:

  * MaintConfig's eight dataclass defaults are indexed out of the mirror. No
    numeric literal survives in the class that held the third opinion.
  * `MaintConfig.from_options()` is the ONLY place in the add-on that reads a
    `maintenance_*` option. main.py's eight inline `opts.get(key, <literal>)`
    calls are gone: moving the read next to the mirror means the fallback cannot
    be anything but the mirror, because there is no literal in sight of it to
    disagree with. It uses `key in opts` rather than truthiness, so a shipped
    `false` or `0` is honoured instead of being quietly replaced by the default
    - this card's own bug in a different costume.
  * main.py's SECOND fallback site - the cheap-window charge floor at the
    P_MAINT_SHAPE claim - reads `self.maint.cfg.charge_w` instead of re-opening
    the options dict with its own literal. The Controller had already parsed
    this once in __init__; asking the object that owns it cannot drift from it,
    and the rate the shaping asks for can no longer be a different number from
    the rate the state machine drains at on the same install.
  * validate.py's rule 6 and its `maintenance_discharge_w` warning take their
    fallbacks from the mirror.

WHERE THE RANGE LIVES, STATED AND CHECKED. config.yaml's `schema:` block carries
`maintenance_charge_w: int(500,5000)` - a fourth declaration site of a different
kind. It is a BOUND, not a default, so it is not this bug; but leaving the
question open is how a fifth site arrives. The decision recorded in config.yaml
and in maintenance.py is: bounds live in the schema block ONLY, because the
Supervisor is what enforces them and the Supervisor reads only that file, so a
Python copy of `int(500,5000)` would be a place to disagree and nothing else.
test_maintenance.py checks both halves of that: every mirrored key must have a
schema entry - without one the Supervisor drops the option and the add-on
silently runs on the mirror instead of the operator's value - and every shipped
default must lie INSIDE its own range, since a default the schema rejects is a
config that cannot be re-entered once it is edited. What the schema grammar
cannot express is a relation BETWEEN keys (`maintenance_charge_w` against
`max_w`), which is exactly why rule 6 is written in Python and why it does not
belong in the mirror either.

THE REPLACEMENT CHECKS, AND HOW THEY WERE VERIFIED. test_validate.py's new
section exercises the same four consumers the defect ran through, the same way:
the validator ACCEPTS a dict with every maintenance key missing; a REAL
Controller built from that same dict holds 2000 W (through main.py, not through
a regex over its source); `MaintConfig()` answers 2000 W with no dict at all;
and the real arbiter emits `-2000 W, limited by supervised(max_w)` instead of
`0 W, contradiction=True`. test_maintenance.py pins the mirror to config.yaml in
both directions - equal values, and full coverage of every `maintenance_*` key
the file ships, so a ninth key cannot arrive unmirrored - and asserts the
consumers move as a RELATION rather than against numbers, reading MaintConfig's
defaults back out of `dataclasses.fields()`.

Each new check was verified by BREAKING the thing it watches and observing red,
this project's rule:

  1. config.yaml -> 1500, mirror left at 2000:  test_maintenance 1 FAILED,
     test_validate 4 FAILED.
  2. config.yaml AND the mirror -> 1500: green again, and every consumer moved
     together - MaintConfig() 1500 W, the Controller 1500 W, and the arbiter
     `-1500 W, limited by maintenance(cheap-window charge)` where it had said
     `-2000 W, limited by supervised(max_w)`. That is AC4: change the single
     source and watch the consumers follow.
  3. `charge_w: float = 2500.0` retyped into the dataclass: 2 FAILED in each of
     the two files.
  4. `opts.get("maintenance_charge_w", 2500)` restored in main.py: 1 FAILED,
     naming the file and the literal it found.
  5. `maintenance_hold_min` deleted from config.yaml's options block: 3 FAILED.

Full suite 17/17 in goodwe-addon-ci, twice, once under parallel load.

Stale prose that asserted the now-closed divergence as current is corrected in
app/watchdog.py, test_watchdog.py and test_peakguard.py - watchdog.py's example
still uses 1500 W, but because the point of the example is a charge strictly
inside the ceiling, not because 2500 is what ships.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-01 06:16:54 +02:00
admin b7267eb51a Merge pull request 'SAFETY-25: say what peak_soc_floor bounds, and measure what it does not' (#31) from SAFETY-25 into release/1.0 2026-09-01 05:23:38 +02:00
glenn schrooyenandClaude Opus 5 e498dd4c1c SAFETY-25: pin the claim-source set, so the tripwire is one
checks / unit (pull_request) Successful in 3m53s
The durability claim this PR shipped was FALSE, and the reviewer of #31
disproved it by building the fix. Part 10 said, in four committed places,
that it "goes RED the day a loop-side floor is built, so the exposure
cannot change size under a green suite". The reviewer implemented the
memo's own recommended Option B in main.py - a
`Claim.limit("reserve", P_LOOP, hi=0.0)` filed under a `loop_soc_floor` -
and the ENTIRE SUITE STAYED GREEN. Part 10 green. Mutation 13 went on
printing "NOTHING PREVENTS IT, ON PURPOSE" and the same 21 % -> 10.0 %,
on a tree where something DID prevent it. Pushed to an absurd
always-binding 95 % reserve it was caught only by SAFETY-24's pre-existing
part 7 wiring checks; part 10 was still green.

THE CAUSE IS STRUCTURAL, not a missing assertion. `replay_loop()`
hand-builds main.py's claim list as a literal
`[supervised, loop, peakguard.claim(...)]`, so it is blind to any claim
main.py ADDS - which is exactly where AC 2 would be built. That is this
repository's named failure mode: a check that observed something other
than what it claimed to observe, shipped as a guarantee inside the
document that recommends the change.

THE FIX IS 10f: THE CLAIM-SOURCE SET, PINNED, two ways because the two
fail differently.

  * STATICALLY, over `Controller.cycle()`'s own AST. Every
    `claims.append(...)` in it must be one the scan can read - an
    unreadable append FAILS rather than counting as nothing, which is how
    a scan like this goes quietly vacuous - and the sources it can file
    must be exactly {device, supervised, failsafe, safety, peak,
    arbitrage, maintenance, loop}. A ninth takes part 10 red on the line
    it is written, in every configuration, whether or not any fixture
    here reaches the state that files it.
  * DYNAMICALLY, through REAL `Controller.cycle()`s with main.py's OWN
    `resolve` spied - not a list this file built and hoped matched -
    swept over the WHOLE 0..100 % SoC range in the two states 10a-10c
    replay. Idle: exactly {device, supervised, loop}. Floor-limited:
    exactly {device, supervised, loop, peak}. A claim conditioned on a
    low pack, which is the shape a loop-side floor has, cannot hide from
    a sweep that visits 0 %.

And the fold is checked rather than assumed: main.py's two P_SAFETY
rating limits are both symmetric LIMITs, so replay_loop() modelling them
as one `supervised` claim at the tighter bound is exact.

MEASURED AGAINST THE COUNTEREXAMPLE. Reproduced first on the unfixed
tree (green, as reported). On this tree the reviewer's Option B at its
recommended default takes part 10 RED on 3 checks, and the 95 % variant
on 6. Nine mutations were run in all, each against a freshly copied tree
with no `__pycache__` present, mounted `:ro`; all nine red, no survivors,
no `+0 B` delta. MUTATION.md records why a second round was needed: the
first round's mutations were all aimed at DISARMING the guard, while the
claim part 10 actually made was about the guard being FIXED.

The four false sentences are replaced with what is now true, and each
says WHICH half catches WHICH shape - 10f for an arbiter claim
(Options B and C), 10a-10c for a clamp inside control.compute() or the
guard (Option D), which the replay drives directly.

AC 2 IS STILL OPEN AND NOTHING HERE BUILDS IT. The loop-side floor was a
test mutant, reverted before commit. The memo still says "Status: OPEN.
This is a memo, not a decision."

Also, non-blocking, from the same review: the NOT READY banner had
inherited the new scope sentence and become a ~550-character paragraph
that the row three lines below repeated verbatim. A checks() row may now
carry an optional short `banner` form; the floor-limited row does, and
`status_payload()` prefers it. THE ROW IS UNCHANGED - shortening that
would have been weakening AC 3 - and rows without the key are
unaffected. Graded, and mutated: dropping the short form goes red.

Merged origin/release/1.0 first (CI-02), keeping both tickets' CHANGELOG
entries.

Full suite green: 17/17 in goodwe-addon-ci (test_ci_gate.py needs `git`,
which CI-02 added to .gitea/ci/Dockerfile but the local image lacks; run
with it installed and it passes).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-01 05:04:22 +02:00
glenn schrooyen 3cb9d3b7d9 Merge origin/release/1.0 into SAFETY-25
CI-02 landed on release/1.0 after this branch was opened and both tickets
add a block under `## Unreleased`, so CHANGELOG.md collided. Both entries
are kept, newest-first: SAFETY-25's, then CI-02's, then SAFETY-20's.
Nothing else conflicted.
2026-09-01 04:38:46 +02:00
admin 99321892cb Merge pull request 'CI-02: grade the merge, and stop a cancelled run reading as a test failure' (#30) from CI-02 into release/1.0 2026-09-01 04:06:26 +02:00
adminandClaude Opus 5 182102eeaf SAFETY-25: say what peak_soc_floor bounds, and measure what it does not
checks / unit (pull_request) Successful in 3m41s
peak_soc_floor reads like a pack-wide reserve and is not one. The
grid-following loop has no SoC guard of any kind, so on a sustained-load
evening it discharges straight past that number and keeps going until the
pack's own BMS cut-out stops it.

The gap has now been written down four times without being filed -
SAFETY-18's finding (freeze.py:18), SAFETY-24's module note, its PR body,
and its honestly-uncaught 13th mutation - and never once measured. It is
measured here, on the committed 2026-08-20 capture, driving the SHIPPED
control.compute(), peakguard.decide(), peakguard.claim() and the real
arbiter.resolve() in main.py's order:

    19:00-22:00 UTC, 830 W mean, minimum 701 W, zero export in the window
    reference pack (300 Ah x 51.2 V x DoD 90) started at 21 %, one point
    above peak_soc_floor

      ends at 10.0 %  -  the bms_soc_floor cut-out
      1525 Wh delivered by the LOOP over 587 cycles
      549 cycles below peak_soc_floor, 343 of them still discharging
      0 cycles on which the peak guard filed any floor at all

AND IT IS A BEHAVIOUR, NOT A CONFIG VALUE. The same evening ends at
9.9715 % at peak_soc_floor = 5, 11, 20 and 60 - the shipped value and both
ends of the schema range - identical to four decimal places. The option an
operator would reach for cannot move the number by any amount at all. On
the same day's high-load block the two states coexist: 49 cycles reporting
PEAK GUARD FLOOR-LIMITED and, on all 49 of them, the arbiter simultaneously
granting the loop up to 2000 W of discharge.

WHY SAFETY-24 COULD NOT CLOSE IT. The peak guard files a `lo` limit - a
LOWER bound on the setpoint. That asymmetry is exactly what makes it
trustworthy: a reviewer proved across 19,800 combinations that it can never
lower a target, cap a discharge or contradict the arbiter. The same property
makes it structurally incapable of stopping a discharge the loop itself
wants. A floor on the guard cannot become a floor on the pack by being
raised, and the sweep above is that sentence measured.

WHAT THIS COMMIT CHANGES IS THE HONESTY, on the four surfaces an operator
actually reads. That half is required whichever way the open question is
answered, and it is the real misstatement on the live system today:

  * config.yaml, beside the option itself - it BOUNDS THE PEAK GUARD ONLY
    and is NOT A PACK-WIDE RESERVE, with the replayed evening and the sweep;
  * DOCS.md, in the options table and in a new section carrying the figures;
  * the STATUS-PAGE ROW for a floor-limited guard. This is the one line a
    human reads at the moment the guard stops discharging, and read alone it
    says "the battery is being held at peak_soc_floor" - which the replay
    shows is false in every cycle that row is rendered;
  * the PERSISTENT NOTIFICATION, which outlives the page. It now names what
    has stopped (the guard buying a lower bill) and what has not (the pack
    being spent).

peakguard.py and freeze.py carry the measurement beside the findings they
already recorded, so the next reader does not have to take the caveat on
trust.

THE PRODUCT DECISION IS NOT TAKEN HERE, and must not be. Whether the loop
gets a reserve floor of its own decides whether this house's battery may
discharge to the BMS floor on a heavy evening; that moves real energy and it
is the owner's call. DECISIONS/SAFETY-25-loop-soc-floor.md is the memo AC 1
asks for: the options, what each costs, what each protects, weighed against
MAINT-01 (a pack repeatedly at the BMS floor is the SoC-drift condition the
maintenance cycle exists to correct, and an over-tight reserve fights it from
the other side) and against the fact that this would be the FIFTH SoC key -
OPT-04's arbitrage_soc_floor fired SAFETY-24's "revisit if a third floor
appears" trigger unremarked, so SAFETY-27's naming decision should land
first. It carries a recommendation and says plainly that it is not a
decision.

It also records a trap found while writing it, and now CHECKED through the
real arbiter rather than described: the obvious shape of a loop-side floor
is a `hi` limit at P_LOOP, and filed while the peak guard is asking for a
positive floor that is `lo > hi` - which arbiter.py resolves to a
CONTRADICTION at 0 W, the battery PARKED in the one quarter of the month
that sets the bill. It is the same crossing-limits hazard
shaping_suspended() already exists to avoid. The ordering
`bms_soc_floor < loop_soc_floor <= peak_soc_floor` removes it provably,
because wherever the reserve binds the guard is already floor-limited and
files lo = 0; both halves are run in part 10d.

test_peakguard.py part 10 is a TRIPWIRE, not a guarantee. It records a
defect and goes RED the day somebody builds a loop-side floor, so the
exposure cannot change size under a green suite and closing it has to be
deliberate. Part 11's mutation 13 stays honestly NOT CAUGHT - nothing
prevents the loop discharging past this floor - but it now reports a number
instead of a sentence.

Verified: 16/16 suites green in the CI image. Eight mutations, each against
a tree copied fresh with __pycache__ excluded and mounted :ro, so no .pyc
existed to go stale (MUTATION.md's structural immunity, the same one it
records for CI); byte deltas +61, -8, -465, -430, -1088, -46, file deleted,
and -95; none is +0 B. All eight go red on the named check:

  M1 peakguard.claim() also files hi=floor_w        -> 7 red, incl. 10c
  M2 control.compute() gain forced to 0             -> 6 red, incl. 10a/10b
  M3 scope sentence removed from the status row     -> 10e red
  M4 scope sentence removed from the notification   -> 10e red
  M5 scope paragraph removed from config.yaml       -> 10e red
  M6 scope bullet weakened in DOCS.md               -> 10e red
  M7 the decision memo deleted                      -> 10e red
  M8 arbiter clamps crossing limits instead of
     reporting a contradiction                      -> 5 red, incl. 10d

AC 2 is left explicitly OPEN, pending the owner's answer.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-01 03:46:43 +02:00
adminandClaude Opus 5 1e4bad8aa7 CI-02: grade the merge, and stop a cancelled run reading as a test failure
checks / unit (pull_request) Successful in 3m44s
Two things a green from `checks / unit (pull_request)` was claiming without
having observed. Both were measured on a deliberately conflicted throwaway pull
request (#29, now closed and its branch deleted) rather than read off the
workflow, because the Actions log endpoints 404 on this Gitea and a step's own
conclusion is the only channel out of a job.

CASE 1, AND THE TICKET'S MECHANISM IS WRONG IN A WAY THAT MAKES IT WORSE.
The card says a conflicted pull request loses its merge ref, so that

    git fetch -q --depth 1 origin "$GITHUB_REF" \
      || git fetch -q --depth 1 origin "$GITHUB_SHA"

falls through to the second half and quietly grades the bare branch head. The
symptom is real - PR #14 reported success while `mergeable: false` - but that
is not how. Asking one question per step on the conflicted probe (runs 558,
559):

    GITHUB_REF == refs/pull/<n>/head          P01 passed
    GITHUB_REF != refs/pull/<n>/merge         P02 failed
    GITHUB_SHA == the pull request head sha   P03 passed
    fetching GITHUB_REF succeeds              P04 passed  <- even conflicted
    ...and it lands on the bare head          P05 passed
    refs/pull/<n>/merge does not exist        P06 failed

`git ls-remote origin 'refs/pull/*'` on this server advertises only `/head`, for
open and closed pull requests alike. There are no merge refs here at all. The
first fetch has therefore always succeeded and the fallback has never fired
once; both halves name the same commit anyway. So the gate did not lose merged
content on conflicted pull requests - it has never had merged content, on any
pull request in this repository's history. Green has meant "this branch passed
on its own", and with `block_on_outdated_branch` off on release/1.0 the base has
usually moved underneath it.

Reproduced end to end on one pull request, same conflict, gate swapped:

    run 567  the ORIGINAL gate   -> success, "Successful in 3m38s"
    run 566  the gate below      -> failure in 2s, merge step red,
                                    both test steps `skipped`

The checkout now fetches the base tip and the pull request head, merges them,
and refuses if the merge does not apply - as its own NAMED step, because
/actions/runs/<id>/jobs carries a per-step conclusion and that is what lets a
reader tell "nothing was tested" from "the tests spoke". `--depth 1` is gone: a
merge needs a merge base, and a full fetch of this repository measured 6.8 MB
and 1.1 s. The fallback survives only on the workflow_dispatch path, which has
no pull request to merge and now announces which bare ref it took.

CASE 2, AND `cancel-in-progress` IS NOT THE KNOB.
Runs 531 and 533 on PR #14 were cancelled at 0s, each at the exact second the
next run on that pull request was created:

    531  created 17:08:19 `Waiting to run`, cancelled 17:10:44 = 532's creation
    533  created 17:45:11 `Waiting to run`, cancelled 18:11:22 = 534's creation

Both have `started_at` at the Unix epoch. A cancelled run posts `failure` on the
required context, described `Canceled after 0s`; branch protection compares
state, not description, so "nothing ran" and "your tests are broken" arrive as
the same red wanting opposite responses. Three settings were measured, each with
one run holding the single runner slot and two further pushes behind it:

    no concurrency block at all   runs 561 and 562 both queued, both executed
    group, cancel-in-progress:false
                                  run 564 sat `Blocked by required conditions`
                                  and was cancelled at 0s the second 565 existed

A shared group cancels a run that has not started regardless of that flag -
GitHub documents it and Gitea 1.27 implements it. Having no group is the only
configuration measured to leave a queued run alive, so the block is gone and the
measurement is written above it. The cost is stated in the file: a developer who
pushes four times occupies the shared runner four times. That is CI-01's own
trade written the other way round - a delayed verdict, never a destroyed one -
and a destroyed verdict is worse here because it is indistinguishable from a
real failure. A sha-keyed group was considered and rejected: the only
cancellations it still permits are same-sha ones, whose red lands on a commit
that IS still the head.

WHAT IS NOT ESTABLISHED, SAID PLAINLY. Nothing here makes a cancelled run
distinguishable at the gate BY STATE; that is Gitea posting the status, not this
workflow, and no edit to this file can change it. What ships removes the cause
instead of relabelling the symptom. And a commit that never had a run carries an
empty `/statuses/<sha>` list, while a queued one carries `pending / Waiting to
run` within seconds and a concurrency-held one `pending / Blocked by required
conditions` - those were already distinguishable at the API. `/actions/tasks`,
which is what was polled when this was first reported, lists only tasks that
started and cannot answer the question at all.

test_ci_gate.py grades the gate by RUNNING it. It extracts the checkout and
merge steps out of checks.yml and executes the shipped commands against two
throwaway local repositories it builds - one whose pull request merges, one
whose does not - and pins that the old one-liner exits 0 on the unmergeable one
while the new steps refuse and say nothing was tested. Part 1 pins the two
tokens that assemble `checks / unit (pull_request)`: renaming `name:` or the
`unit:` job key would leave every open and future pull request waiting forever
on a context that never arrives, with no error anywhere in that sequence, and
admin override blocked. Seven mutations of checks.yml were each confirmed red,
including both renames and a restored `--depth 1`. .gitea/ci/Dockerfile gains
`git` for it; the fixtures are local paths and no network is touched.

17/17 green in the checks image.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-01 03:42:54 +02:00
admin 6ea79f1043 Merge pull request 'SAFETY-20: measure the freeze rail against the reachable ceiling, not max_w' (#28) from SAFETY-20 into release/1.0 2026-09-01 02:57:58 +02:00
glenn schrooyen 29fa39eda7 Merge origin/release/1.0 into SAFETY-20
checks / unit (pull_request) Successful in 3m36s
# Conflicts:
#	goodwe_controller/CHANGELOG.md
2026-09-01 02:43:08 +02:00
admin d64790b3e2 Merge pull request 'TEST-15: purge the bytecode cache before a mutation run, not after' (#27) from TEST-15 into release/1.0 2026-09-01 02:22:15 +02:00
adminandClaude Opus 5 83911ed637 SAFETY-20: measure the freeze rail against the reachable ceiling, not max_w
checks / unit (pull_request) Successful in 3m37s
SAFETY-18's conjunction needs `abs(commanded_w) >= 0.95 * max_w`, but the
emitted command is clipped to the setpoint device's own [dev_min, dev_max]
range as well as to max_w - in clamp_to_rating()'s second stage and again as
the arbiter's `device` P_SAFETY limit claim. Measured on the shipped predicate
at the ticket's numbers, max_w 5000 on a +-4700 W inverter:

    looks_frozen(unchanged_s=3600, commanded_w=4700, max_w=5000)  ->  False

The command is pinned at the hardware's rail, the meter has been frozen for an
hour, and term 2 is unsatisfiable by construction because 4700 < 4750. Any
device rating at or below 0.95 * max_w disarms the conjunction outright, and
the status page then printed `armed (... command is over 4750 W)` - a guard
that cannot fire, advertising that it can, which is the failure SAFETY-15,
SAFETY-19 and validate.py rule 5 all exist to prevent.

The rail is now measured against min(max_w, |dev_min|, |dev_max|), through a
new `rail_ceiling_w()` threaded into looks_frozen(), FreezeWatchdog.evaluate()
and both call sites in main.py. An unread rating leaves the old behaviour
exactly, and correctly: hass.limits() returns None whenever ESPHome is not up,
and on that path no device clamp is applied either, so max_w really is the
ceiling. A rating larger than max_w cannot raise the rail - this is a min(),
not a swap.

THE DELIBERATE CHOICE, since SAFETY-03 has landed. The arithmetic was kept
rather than substituting Decision.i_clamped / Decision.clamped. i_clamped is
the integrator bound (control.py:208, `bounded != i_w`), not "the command is
at the device rating", and `clamped` is the max_w output bound, unreachable on
a default install - neither is the device rail. More decisively, both answer
"did the LOOP ask for more than a bound", while the rail term asks "is the
command standing at the ceiling", and those coincide only when the loop is the
claimer that won. A maintenance SET or a peak-guard floor reaches the ceiling
through arbiter LIMIT claims with no clamp engaging at all, so a boolean rail
would go False exactly during a maintenance phase running against a frozen
meter - which freeze.py's own docstring names as the same fault with a worse
actuator behind it. The predicate is also public with two call sites that pass
DIFFERENT command values (self.target, and `standing` = last_write); a
per-cycle boolean cannot be passed per call site, so substituting it would
have silently decided the pre-clamp-versus-wire question that PM recorded as
still open. AC 1 governs, and it is satisfied literally.

The smaller of the two device bounds, not a per-sign pair. A per-sign rail is
tighter and is not wrong, but it is two rails needing two coverage verdicts on
a status row that carries one number, and the only configuration that
distinguishes them is refused at startup anyway. The symmetric ceiling can only
lower the rail, which widens term 2 rather than disarming it; term 1 carries
the whole no-false-positive argument and is untouched.

A ceiling of 0 W is NOT COVERED, not "armed at 0 W". A device that can command
nothing in one direction would make `abs(command) >= 0` true of every command
including a parked one - term 2 degenerately TRUE, collapsing the conjunction
into the bare unchanged_s > N threshold TEL-05 refused for false-tripping at
this controller's own operating point. rail_unreachable() returns the reason,
looks_frozen() stays silent, and the page uses the NOT COVERED row the
unsupported-transport case already has - a second reason to use that surface,
not a new mechanism.

AC 4, decided rather than assumed: NO NEW validate.py RULE. The configuration
is max_w above the device rating, which rule 2 (CFG-01) already refuses on the
identical predicate, re-run by run_control() once the real rating is known:

    validate_startup_config({... max_w: 5000}, -4700, 4700)
      -> ['max_w is 5000 W but number.sp accepts at most 4700 W - THE DEVICE
          WINS ...']

A rail-specific rule would fire on a strict subset of that (0.95 * max_w >
dev_max implies max_w > dev_max) and could never be the rule that stopped a
start. The residue is the state where hass.limits() answered (None, None) -
ESPHome not up at boot, range checks skipped rather than guessed at, rating
never re-read - and there is nothing to refuse there by construction, which is
why the answer is a runtime row. Recorded in validate.py's "deliberately not
refused" list and pinned by four checks in test_validate.py, so the decision's
premise goes red if rule 2 is ever softened back to a warning.

HOW REACHABLE THIS IS, stated rather than glossed. Because rule 2 refuses the
configuration whenever the rating is known, min(max_w, dev_max) IS max_w on
every install that reaches the control loop with a rating it could read, and
this change is arithmetically dead there. That is clamp.py's argument for its
own second stage word for word: the case where it bites is the case where the
startup gate did not run or no longer holds, and a guard that quietly assumes
the gate ran is a guard that reports armed in exactly the state it cannot fire
in.

Verified by breaking it, per this project's rule. Reverting rail_w() to bare
max_w fails nine checks; deleting the NOT COVERED handling fails five. The one
that mattered: shipping the corrected predicate while NOT passing the rating
from check_meter_frozen() left the entire suite green, because nothing graded
the caller - so test_freeze.py part 5b now drives the real cycle() on a +-4700 W
device and asserts on the notification that leaves the process, and the
unwiring mutation fails three checks there. The peak-guard call site's wiring
is still ungraded (behind p1_enabled, needs a fed averager for `frozen` to have
any observable consequence) and that gap is named in the file rather than
implied.

Full suite: 15/15 in goodwe-addon-ci.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-01 02:14:07 +02:00
glenn schrooyenandClaude Opus 5 7b4877d56d TEST-15: purge the bytecode cache before a mutation run, not after
checks / unit (pull_request) Successful in 3m35s
FCST-03's developer reverted `self.provisional` to `here.provisional`, re-ran,
and reported the mutation as a survivor. It was not one. CPython validates a
cached `.pyc` on (source size, source mtime truncated to whole seconds), and
that edit moved neither number - same length, same second - so the interpreter
loaded the bytecode it already had. Disassembly settled it at the time: the
source read `here`, the running code loaded `self`. A mutation run had graded
code that was not there, with no error and exit status 0.

This does not make the results already on the record wrong. It makes them
UNVERIFIED, and that distinction is the whole card - so nothing here re-runs a
campaign and nothing here quietly assumes the old numbers hold.

REPRODUCED, THEN CLOSED. test_bytecode.py builds a real package whose two
return values are the same length, imports it in a real subprocess, rewrites it
inside the same second (retrying until both writes land in one whole second -
milliseconds, no sleep) and reads back which value ran. Part 1 shows the
interpreter running SELF off a file that says HERE.

AND THE TWO OBVIOUS MITIGATIONS DO NOT WORK. Measured, not read off
documentation: `python3 -B` and PYTHONDONTWRITEBYTECODE=1 are write-side only.
Neither stops an EXISTING stale .pyc being read, and a mutation run always has
one, because the previous run wrote it. Part 2 grades both still running the old
code. The advice in test_control.py's coverage audit led with `-B`; it is
corrected here - the purge is the half that works, and `-B` earns its place by
keeping THIS run from leaving a cache for the NEXT edit to inherit.

NO SLEEP ANYWHERE. One-second mtime resolution is the mechanism, not the enemy.
Waiting it out would slow every run down and would still only cover the edit
somebody remembered to slow down.

THE HARNESS. tools/mutation_run.sh purges, prints a sha256/byte fingerprint of
every app/*.py it is about to grade - so a mutation report can say WHICH source
produced it, which is the reviewer's addition to this card - runs each suite
under `python3 -B`, refuses a tree with no test_*.py (CI-01's rule, for CI-01's
reason), and fails if a cache appears during the run. It takes the tree as an
argument so the infra repo's replay harnesses can call it without being moved.

WHERE IT IS SAID (AC 2). MUTATION.md carries the mechanism, the measurement,
the reporting rules and the survey, and every one of the 16 suites now points at
it from its docstring. That list is DERIVED FROM THE TREE by test_bytecode.py
part 5, so a new suite that joins this directory without the pointer is red -
the same failure shape CI-01's file glob exists to prevent.

CI WAS ALREADY IMMUNE, AND IS DESCRIBED THAT WAY (AC 4). Verified rather than
reasoned: with the checkout bind mounted `-v "$WS:/w:ro"` the interpreter writes
no __pycache__ into the tree at all, and it fails SILENTLY - no error, exit
status 0 - while the same probe on a writable mount produces one. Each job also
rm -rf's its workspace and clones afresh, so nothing crosses between jobs on the
shared runner. PYTHONDONTWRITEBYTECODE=1 is added as belt and braces only: the
`:ro` is one character wide and the next person debugging a write will be
tempted by it. Part 6 grades both ON THE DOCKER COMMAND LINE rather than on the
file - the first draft searched the whole workflow and stayed green after the
flag was deleted, because the comment explaining it still named it.

THE SHIPPED ADD-ON IS NOT AFFECTED and the question is closed:
goodwe_controller/Dockerfile has set PYTHONDONTWRITEBYTECODE=1 since it was
written. There is no deploy-side finding.

THE SURVEY (AC 3), in MUTATION.md, scoped BY THE PROPERTY. The defect is
one-directional - a mutation that never took leaves the suite green, so stale
bytecode manufactures SURVIVORS and cannot manufacture a red - which puts every
"all red, no survivors" claim in the window out of scope, along with mutations
executed in-process (SAFETY-07's B1/B2/B3, test_peakguard parts 7 and 10, where
no source file is edited) and everything run after the purge discipline landed
on 2026-08-31 (SAFETY-24, SAFETY-26, OPT-04, FCST-03's re-run). What is left is
the recorded SURVIVORS from source-edit runs before that date. Two were re-run
here under the harness and both still stand: TARIFF-01's record_block() ignoring
its policy argument, and SAFETY-03's abs() on the clamp limit - 15 suites green
each, on the tree as it stood. The rest are labelled still-unverified rather
than assumed or re-run; each is one harness run to close, and the moment to
spend it is when somebody next touches that module.

OUT OF SCOPE AND RECORDED: the infra repo's sim/ replay harnesses import the
add-on and write bytecode into both trees (goodwe/sim/__pycache__ exists today),
so SAFETY-02's headline replay carries the same exposure. mutation_run.sh takes
a tree argument for exactly that, but the change belongs in that repo and some
of those harnesses want the rig.

RED AND GREEN. Every new check was broken and watched fail: the purge commented
out of the harness turns part 4 red (and its non-vacuity probe already proves
the fixture would mis-grade without it); one docstring pointer removed turns
part 5 red naming the file; `:ro` and the `-e` flag removed from the workflow
turn part 6 red. Full suite green, 16 files, in the CI image on a read-only
mount - the shape the runner uses.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-01 02:07:09 +02:00
admin 358fbb0172 Merge pull request 'TEST-17: grade the status page's peak row at a stated month, not at today's' (#26) from TEST-17 into release/1.0 2026-09-01 01:32:44 +02:00
glenn schrooyenandClaude Opus 5 504e8daac3 TEST-17: grade the status page's peak row at a stated month, not at today's
checks / unit (pull_request) Successful in 3m35s
release/1.0 went red at 00:00 on 2026-09-01 on a commit nobody had
touched. `Controller.checks()` read the capacity-tariff peak with
`self.peak.peak()` - no argument - so tariff.py resolved the month from
`datetime.now()`, while test_tariff.py section 10 banks its quarter at
the fixed fixture 2026-08-30. From 1 September the page was correctly
asked for September, correctly answered NO_RECORD, and the row read "no
completed quarter recorded yet" - a string containing no "peak", which
the section's own filter required. Four checks failed.

ISOLATED BY MOVING ONLY THE CLOCK. Same commit, same shipped-deps image,
libfaketime: green at 2026-08-30, four failures at 2026-09-01. Identical
at f4914a1, 04292c4~1 and 04292c4, so this is the calendar and not a
regression. It has been latent since TARIFF-01 merged on 2026-08-30, and
every PR that ever ran this suite ran it in August.

THE PRODUCT IS RIGHT AND THE TEST WAS WRONG, so the live page is
unchanged. Section 5 of this same file calls NO_RECORD "a normal state
on the 1st of the month" and a capacity tariff is billed monthly, so a
page showing the current month is correct. `checks()` now takes
`when: datetime | None = None` and threads it into peak() and
warning_frac() - the convention PeakStore.peak(), PeakTracker.peak(),
headroom_w() and warning_frac() all already follow. The one production
caller passes nothing and still means today.

AND THE DEFECT IS NOW DETECTABLE RATHER THAN SEASONAL. Three checks:
the same controller read at two different reference months must produce
two different rows, which no clock can satisfy; the later month must
read NO_RECORD and stay distinguishable from both an observed peak and
an unreadable store; and checks() with no argument must still mean
today. Verified by mutation - a checks() that drops `when` is red at
every clock tried, where the old section went green in August. The first
draft of these checks was itself wrong in the same way and reproduced
the bug: it selected rows on "peak", which the NO_RECORD row does not
contain, so it dropped the row and then graded its absence. They select
on "quarter(s) banked" instead.

Full suite green, 15 files, at the real clock and at faked clocks in
2026-08, 2026-12, 2027-02 and 2027-03.

Left alone deliberately: only the UNREADABLE branch prefixes its row
with "capacity-tariff peak:". The NO_RECORD row carries neither that
phrase nor the word "peak". That asymmetry is what made the original
filter brittle and what broke the first draft above; it is product text
with other suites reading it, so it is reported rather than changed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BwRLw7eKYj2byVdwB6kbjU
2026-09-01 00:58:20 +02:00
admin f6ecd5ff03 DATA-01: thirty days of the real meter, and what AC 3 actually measures (#25)
Thirty days of the house's own P1 meter, exported from HA's recorder with a committed exporter, closing the dataset gap that made TARIFF-01's and SAFETY-07's AC 3 unmeetable. 2879 closed quarters, 485841 samples, 99.950 % covered, 13 gaps over 30 s and nothing interpolated.

Reviewed independently. The re-export is byte-for-byte identical after decompression on both previously committed days (865024 B / 15600 samples and 894387 B / 16351 samples), verified by decompressing and comparing rather than by reading --verify; the only difference is the gzip mtime field, and writing 0 rather than a wall clock makes this exporter reproducible where the 2026-08-25 one-off was not. The committed CRLF is reproduced rather than tidied because reproducing it IS the verification, and .gitattributes marks *.gz binary so git can never drift it - confirmed with git check-attr. All 30 manifest sha256s match.

replay_ac3.py --expect 189/190 reproduces test_peakguard part 6 exactly: 5029.8 -> 3485.3 W, 189/190, 878 Wh, 110 graded + 5 blind - every one a figure the reviewer had already derived independently on a different harness while reviewing TARIFF-01 and SAFETY-07.

AND THE RESULT IS A FINDING ABOUT THE CRITERION. Over the month the guard takes the peak from 5029.8 W to 4107.3 W (-18.3 %, still over the 3500 W soft limit) while moving the interval count from 98.89 % to 98.99 %. The UNCONTROLLED month already passes the 95 % bar, with 112 quarters of slack, and the guard contributes 3 - a signal-to-threshold ratio of 0.021. The criterion counts intervals while the capacity tariff bills the month's maximum, so it cannot separate a working guard from an absent one. AC 3 is met on the letter and uninformative on the substance; it should not be read as evidence the guard works, and if rewritten it should be on the monthly peak.

The failed-read discipline was verified by producing all three states: a typo'd entity and an unreachable recorder both exit 1 having written nothing, and a day whose read fails is recorded FAILED with file null, no .gz, days_failed 2 and empty_days [] - so an empty response cannot look like a quiet hour. The 30 days sit in a subdirectory and are glob-invisible to both suites' non-recursive scenarios/p1-net-*.jsonl.gz; neither suite had a check added, removed or altered. Full suite green, 15 files.
2026-08-31 11:35:45 +02:00
34 changed files with 4934 additions and 269 deletions
+13 -1
View File
@@ -18,5 +18,17 @@
# python3, no aiohttp, no pip (`No module named pip`; checked on the box, not
# assumed). An image is not gold-plating here, it is the only option that does
# not mutate a shared long-lived runner.
# ⚠️ `git` IS A TEST DEPENDENCY, NOT A CONVENIENCE (CI-02). test_ci_gate.py
# grades the gate's own checkout by EXTRACTING the shell out of
# .gitea/workflows/checks.yml and RUNNING it - against two throwaway local
# repositories it builds itself, one whose pull request merges and one whose
# does not. Reading those commands as a string would be the thing this
# repository keeps finding: a check that never observed its subject. Running
# them needs git in the image the checks run in.
#
# It costs one apk package and no network at test time: the fixtures are local
# paths, and the token substitution in the workflow's `git remote add` is a
# no-op on a path with no `://` in it, which is exactly why the test can use
# the shipped line verbatim instead of a paraphrase of it.
FROM alpine:3
RUN apk add --no-cache python3 py3-aiohttp py3-paho-mqtt
RUN apk add --no-cache python3 py3-aiohttp py3-paho-mqtt git
+179 -14
View File
@@ -18,7 +18,9 @@
# so it QUEUES behind a rig campaign - a delayed verdict, never a destroyed one.
#
# NO JS ACTIONS: the runner image has no node, so `actions/checkout` cannot run.
# Checkout is seven lines of git below.
# Checkout is plain git below - and since CI-02 it is a checkout of the MERGE of
# the pull request into its base, not of the branch tip. See the long note on
# that step; a green from this workflow is a claim about content that can land.
name: checks
on:
@@ -26,15 +28,53 @@ on:
branches: [release/1.0, master]
workflow_dispatch:
concurrency:
# ⚠️ PER PULL REQUEST, NOT A BARE NAME. A shared group holds one running and
# one pending run, so a bare name lets a second PR supersede a first PR's run
# before any runner has picked it up - which is exactly what happened to the
# other repo's run 521 (four jobs, `started_at` at the Unix epoch,
# `runner_id: 0`, concluded `cancelled`, and the PR merged anyway). Do not
# replace this with a constant.
group: addon-checks-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
# ⚠️ NO `concurrency:` BLOCK, AND ITS ABSENCE IS AS LOAD-BEARING AS THE MISSING
# `paths:` FILTER ABOVE. CI-01 put one here - `group: addon-checks-<pr number>`,
# `cancel-in-progress: true` - to stop a second pull request superseding a
# first one's run. It did stop that. It also did this, twice, on PR #14:
#
# run 531 created 17:08:19 `pending / Waiting to run`
# cancelled 17:10:44 <- the exact second run 532 was created
# run 533 created 17:45:11 `pending / Waiting to run`
# cancelled 18:11:22 <- the exact second run 534 was created
#
# Both cancelled runs have `started_at` at the Unix epoch: they never executed.
# A cancelled run posts `failure` on the required context, described
# `Canceled after 0s`. Branch protection compares STATE, not description, so
# "nothing ran" and "your tests are broken" arrive at the gate as the same red,
# and the correct operator response to each is the opposite of the other.
#
# CI-02 MEASURED THE THREE CANDIDATE SETTINGS ON A THROWAWAY PR (#29) RATHER
# THAN READING THE DOCS, because the docs and this Gitea disagree about which
# knob does it. In each trial one run was made to hold the single slot and two
# further pushes followed:
#
# trial 1, NO concurrency block - runs 561 and 562 both sat queued together
# and both executed. Nothing was cancelled.
# trial 2, group kept, cancel-in-progress: FALSE
# - run 564 sat `pending / Blocked by required
# conditions` and was cancelled at 0s the
# second run 565 was created.
#
# So `cancel-in-progress` IS NOT THE KNOB. A shared group cancels a run that has
# not started no matter what that flag says - GitHub documents this ("any
# previously pending run in the group will be cancelled") and Gitea 1.27
# implements it. The only configuration that leaves a queued run alive is having
# no group at all, which is what is written here.
#
# ⚠️ DO NOT REPLACE THIS WITH A SHA-KEYED GROUP as a compromise. It looks
# tempting - two runs on different commits could never share a group, so nothing
# would be cancelled - but the only cancellations it still permits are the
# same-sha ones, and those are precisely the dangerous half: a red for a run
# that never started, landing on a commit that IS still the head. It
# concentrates the failure instead of removing it.
#
# WHAT THIS COSTS, stated honestly: the runner is `capacity: 1` and shared with
# the other repo's rig, so a developer who pushes four times in a minute now
# occupies it four times instead of once. That is CI-01's own trade written the
# other way round - it accepted "a delayed verdict, never a destroyed one" for
# the rig, and this accepts the same for pushes. A destroyed verdict here is
# worse than a slow one, because it is indistinguishable from a real failure.
jobs:
unit:
@@ -58,19 +98,132 @@ jobs:
# exist, so the test dies on `IndexError: 1` before its first assertion.
# Measured during CI-01; the flat layout was tried first and did exactly
# that. $WS/goodwe-addon/goodwe_controller gives parents[1] == $WS.
- name: checkout into a path the host shares (git; no node for actions/checkout)
#
# ⚠️ WHAT THIS CHECKS OUT IS THE MERGE, NOT THE BRANCH, AND THAT IS THE
# WHOLE OF CI-02. What was here before was one line:
#
# git fetch -q --depth 1 origin "$GITHUB_REF" \
# || git fetch -q --depth 1 origin "$GITHUB_SHA"
#
# CI-02 measured what those two names actually are on this Gitea, on a
# deliberately conflicted throwaway PR (#29, runs 558 and 559), by asking
# one question per STEP - the Actions log endpoints 404 here, so a step's
# own conclusion is the only channel out of a job. The answers:
#
# GITHUB_REF == refs/pull/<n>/head (step P01 passed)
# GITHUB_REF != refs/pull/<n>/merge (step P02 failed)
# GITHUB_SHA == the pull request head sha (step P03 passed)
# fetching GITHUB_REF succeeds (step P04 passed)
# ...and lands on the bare head (step P05 passed)
# refs/pull/<n>/merge does not exist (step P06 failed)
#
# ⚠️ SO THE FALLBACK NEVER FIRED, AND THE DEFECT IS WORSE THAN THE ONE
# REPORTED. The ticket says a conflicted PR loses its merge ref and the
# `||` quietly grades the bare head instead. It does not: this Gitea has
# no merge refs at all - `git ls-remote origin 'refs/pull/*'` advertises
# only `/head`, for open and closed pull requests alike - so the FIRST
# half always succeeds, and both halves name the same commit anyway
# (GITHUB_REF resolves to GITHUB_SHA). The gate has never once graded
# merged content, on any pull request in this repository's history. Green
# has meant "this branch passed on its own", which on a base that has
# moved - and `block_on_outdated_branch` is off here, so it usually has -
# is not the content that lands. PR #14 reporting success while
# `mergeable: false` was not the fallback misfiring; it was the gate
# working exactly as written.
#
# A fallback that cannot fire cannot be "kept for the case it was for", so
# it is gone from this path and kept, ANNOUNCED, on the one path that has
# no pull request to merge (workflow_dispatch, below).
#
# ⚠️ NOT `--depth 1` ANY MORE. A merge needs the merge base, and a shallow
# pair does not have one. Measured before changing it: a full fetch of
# this repository is 6.8 MB and 1.1 s against this server, over 95
# commits. The depth flag was buying nothing worth a wrong verdict.
#
# ⚠️ THE WORKFLOW AND THE CONTENT NOW COME FROM DIFFERENT TREES. Gitea
# picks the workflow file from refs/pull/<n>/head, so THIS file is always
# the branch's; the tree graded below - including .gitea/ci/Dockerfile -
# is the merge. That is the right way round (a pull request must not be
# able to grade itself with a gate the base has not seen) but it means a
# change to this file is tested by the branch it is on, which is how you
# are reading this.
- name: check out the base branch and the pull request head (git; no node for actions/checkout)
env:
URL: ${{ github.server_url }}/${{ github.repository }}.git
TOKEN: ${{ secrets.GITHUB_TOKEN }}
PRNUM: ${{ github.event.pull_request.number }}
BASEREF: ${{ github.base_ref }}
run: |
set -eu
rm -rf "$WS" && mkdir -p "$WS/goodwe-addon" && cd "$WS/goodwe-addon"
git init -q .
git remote add origin "$(echo "$URL" | sed "s#://#://x-access-token:${TOKEN}@#")"
git fetch -q --depth 1 origin "$GITHUB_REF" || git fetch -q --depth 1 origin "$GITHUB_SHA"
git checkout -qf FETCH_HEAD
if [ -n "$PRNUM" ]; then
# Two fetches, not one, so that a failure to reach either ref fails
# HERE with the ref in the message, rather than inside the merge
# step where it would read as a conflict. `github.base_ref` being
# populated at all was checked on the probe PR too (step Q01).
git fetch -q origin "+refs/heads/$BASEREF:refs/remotes/origin/base"
git fetch -q origin "+refs/pull/$PRNUM/head:refs/remotes/origin/pr"
git checkout -qf refs/remotes/origin/base
echo "base $BASEREF $(git rev-parse refs/remotes/origin/base)"
echo "head refs/pull/$PRNUM/head $(git rev-parse refs/remotes/origin/pr)"
else
# NO PULL REQUEST (workflow_dispatch). There is nothing to merge
# into, so this path grades a bare ref and SAYS SO - which is all
# the old `||` ever needed to do. It is kept here because a branch
# can be deleted or renamed between the dispatch and the fetch, and
# unlike the pull_request path that is a case nobody has ruled out.
if git fetch -q origin "$GITHUB_REF"; then
echo "GRADED: the bare ref $GITHUB_REF - NOT merged content (no pull request in this event)."
else
git fetch -q origin "$GITHUB_SHA"
echo "GRADED: the bare commit $GITHUB_SHA - NOT merged content, and NOT $GITHUB_REF either, which would not fetch."
fi
git checkout -qf FETCH_HEAD
fi
echo "checked out $(git log --oneline -1)"
# ⚠️ THIS STEP IS THE ONE THAT MAKES A GREEN MEAN SOMETHING. It exists as
# its OWN step rather than as three lines of the checkout because the
# Actions log endpoints 404 on this Gitea and
# /api/v1/repos/.../actions/runs/<id>/jobs - which carries a per-step
# conclusion - is the only machine-readable account of what a run did. A
# reader who sees this step red knows the pull request does not apply and
# that NO TEST RAN; a reader who sees the next two red knows the tests ran
# and spoke. Collapse them back together and that distinction is gone
# again, which is the shape of defect this whole ticket is about.
#
# The refusal is a FAILURE rather than a skip on purpose. "Reports
# nothing" would leave the required context pending forever, which this
# file's own header explains is unmergeable-forever; and a conflicted pull
# request cannot be merged by Gitea anyway, so the red blocks nothing that
# was not already blocked. What it does is stop a green being posted about
# content that cannot land.
- name: grade the merge, not the branch - refuse a pull request that does not apply
env:
PRNUM: ${{ github.event.pull_request.number }}
BASEREF: ${{ github.base_ref }}
run: |
set -eu
cd "$WS/goodwe-addon"
if [ -z "$PRNUM" ]; then
echo "no pull request in this event - nothing to merge, and the previous step said what it graded."
exit 0
fi
if git -c user.email=checks@localhost -c user.name=checks \
merge --no-edit refs/remotes/origin/pr; then
echo "GRADED: refs/pull/$PRNUM/head merged into $BASEREF"
echo " result $(git rev-parse HEAD)"
echo " tree $(git rev-parse 'HEAD^{tree}')"
else
git merge --abort 2>/dev/null || true
echo "REFUSED: refs/pull/$PRNUM/head does not merge into $BASEREF."
echo " NOTHING HAS BEEN TESTED. This is not a test failure - no test ran."
echo " Rebase or merge $BASEREF into the branch and push again."
exit 1
fi
- name: build the test image (shipped deps, from apk - see .gitea/ci/Dockerfile)
run: |
set -eu
@@ -101,10 +254,22 @@ jobs:
# hwsim section was skipped - so "test_freeze.py: PASS" below is a weaker
# claim than it looks. That belongs to whoever owns test_freeze.py next;
# naming it here is the least this gate can do about it.
# ⚠️ PYTHONDONTWRITEBYTECODE=1 IS BELT AND BRACES, NOT A FIX FOR A LIVE
# HOLE. TEST-15 measured this runner's actual exposure and found none: the
# checkout below is bind mounted `:ro`, so the interpreter physically
# cannot write a __pycache__ into the tree it is grading - it fails
# SILENTLY, no error and exit status 0 - and every job `rm -rf`s $WS and
# clones afresh, so nothing survives from a previous job on this shared
# runner either. The variable is here because the `:ro` is the load-bearing
# part and it is one character wide: delete it while debugging a write and
# the gate quietly starts caching bytecode across a rebuild again. Note
# what it does NOT do, per TEST-15 part 2 - it stops bytecode being
# WRITTEN, never a stale one being READ. It is not a substitute for the
# purge in goodwe_controller/tools/mutation_run.sh.
- name: the add-on's own tests
run: |
set -eu
docker run --rm -v "$WS:/w:ro" goodwe-addon-checks:1 sh -eu -c '
docker run --rm -e PYTHONDONTWRITEBYTECODE=1 -v "$WS:/w:ro" goodwe-addon-checks:1 sh -eu -c '
cd /w/goodwe-addon/goodwe_controller
set -- test_*.py
if [ "$1" = "test_*.py" ]; then
+13
View File
@@ -57,6 +57,14 @@ python3 test_control.py && python3 test_maintenance.py && python3 test_arbiter.p
&& python3 test_loop.py
```
⚠️ **Mutating a module to prove a check bites? Read `goodwe_controller/
MUTATION.md` first, and run `goodwe_controller/tools/mutation_run.sh`.** A
same-size edit reverted inside one second changes neither the file size nor the
whole-second mtime, so CPython reuses the bytecode it already compiled and the
suite grades code that is not there - once already, reported as a survivor and
disproved by disassembly (TEST-15). `python3 -B` does **not** save you: it stops
bytecode being written, not a stale `.pyc` being read. The purge is the fix.
`test_watchdog.py` covers SAFETY-02's logic, its arming gate (derived from the
real arbiter, not passed in), its trip path, and the fact that the latch survives
an add-on restart. Its headline validation is not here at all: `sim/replay_sign.py`
@@ -165,6 +173,11 @@ Each of these was found the expensive way. They are in the code comments too.
`timestamp` attribute.
- **Alpine ships paho-mqtt 1.x**, which has no `CallbackAPIVersion`, and musl has
no aiohttp wheel — install from apk, not pip.
- **A mutation run can grade code that is not there.** CPython validates a
`.pyc` on (source size, source mtime in whole seconds), so a same-size edit
reverted within one second is invisible to it and the old bytecode runs. It
manufactures *survivors*, never reds. Purge `__pycache__` -
`tools/mutation_run.sh` does - and see `goodwe_controller/MUTATION.md`.
- **The inverter holds its last command forever.** It has no meter-timeout. Every
failsafe here exists because of that one fact, and anything in doubt commands
**0 W** rather than holding.
+8 -1
View File
@@ -19,6 +19,8 @@ goodwe_controller/ the add-on
test_control.py runnable checks — no framework needed
test_maintenance.py runnable checks — walks a full cycle in fake time
DOCS.md the add-on's documentation tab
MUTATION.md how to run a mutation so the result means something
tools/mutation_run.sh the mutation harness - purges bytecode, then grades
firmware/goodwe-master.yaml ESPHome config for the T-CAN485
estop/rs485_log.py optional RS485 e-stop / bus witness
docs/GoodWe-RS485-Field-Guide.pdf the guide techs carry (10pp, A4)
@@ -82,7 +84,12 @@ python3 test_control.py
python3 test_maintenance.py
```
Both must pass before shipping any change. They are not unit-test theatre —
Both must pass before shipping any change. To prove a check *bites* - the way
almost every claim in this repository was established - mutate the module and
run `tools/mutation_run.sh`, which clears `__pycache__` first. It is not
optional: a same-size edit reverted inside one second leaves CPython reusing the
old bytecode, and the run grades code that is not there. `goodwe_controller/MUTATION.md`
has the mechanism, the measurement, and what the flags do not do. They are not unit-test theatre —
each assertion corresponds to a rule whose absence produced an observed failure
on real hardware, and the comments in `control.py` say which.
+591
View File
@@ -2,6 +2,597 @@
## Unreleased
**SAFETY-25's open question is ANSWERED: the BMS cut-out is the DELIBERATE and
only backstop for demand-driven discharge, and a loop-side reserve floor is
DEFERRED to `ALLOC-01` rather than rejected (SAFETY-25).** Decided by the
product owner on 2026-09-02. **Option A is the shipped behaviour, so `app/`
changed only where a comment claimed the question was still open** - no
setpoint, no claim, no option, no default moved, and the 17-suite run is green
on the same numbers as before.
* **Why deferring is the safe direction, and it is a property of the shape
rather than a preference.** Option B's proof - `bms_soc_floor <
loop_soc_floor <= peak_soc_floor`, verified through the real arbiter in
`test_peakguard.py` part 10d - has an unstated premise: the reserve predicate
and `discharge_permitted()` read the **same** state of charge. With two packs
they read different numbers. The reserve binds on the emptier pack and files
`hi = 0` while the peak guard, reading the other pack or an average, files
`lo = excess > 0`; `lo > hi` is arbiter clause 3 and the answer is **0 W, the
battery parked in the billed quarter** - the failure the memo itself marks
fatal. **No config-ordering validator can catch it**, because it is a runtime
divergence between two readings and not a config ordering, so CFG-01's shape
of check would pass on the exact tree that parks the battery. Option A's cost
is energy; Option B's cost built too early is a parked battery in the one
quarter of the month that sets the bill.
* **The revisit trigger is recorded explicitly, and it is `ALLOC-01`.** Under
`ARCH-01`'s host-side allocator the two claims stop sharing a list: the loop
floor becomes a **per-inverter `hi` consumed as an interval at stage A**,
while the peak floor stays a **site `lo` at stage B**. Different claim lists,
different stages, **structurally unable to cross** - which is a stronger
argument than the ordering rule, because it makes the crossing unreachable
rather than harmless. That is the shape in which Option B becomes safe to
build, and the memo says so at the point a future reader will look.
* **What will have to be RE-EARNED at N=2 is stated plainly rather than left
for someone to discover.** `SAFETY-27` now names **five floors across two
packs**, so "the SoC" stops being a scalar the config can bound. And
`test_peakguard.py` **part 10f - the pin that made SAFETY-25 mergeable** -
**cannot express two packs**: its dynamic half is a scalar 0-100 % SoC sweep
against a single-series capture, and a two-pack exposure lives in the
*difference* between two readings, which that sweep visits at no resolution.
Its static half (the AST scan pinning the eight claim sources) still bites at
N=2; the dynamic half goes silent. Merging a two-pack reserve on 10f's
current green would be merging on a check that cannot see the failure.
* **The options analysis is kept intact on purpose.** A memo that recorded the
verdict and deleted the reasoning is the failure mode this `DECISIONS/`
directory exists to prevent, so §1-§7 stand exactly as written - including
§5's *"(recommended)"* on Option B and §6's recommendation - with the new §0
saying what was decided and §6 marked as answered. Part 10e's check moved
with the memo: it used to pin the honest `Status: OPEN` line and now pins
that the memo names the option, the date and the trigger **and still carries
both options and the recommendation**.
* **The tripwire stays, and "deferred" is why it stays.** Part 10 and mutation
13 are unchanged in substance: a ninth claim source in `Controller.cycle()`
still takes 10f red on the line it is written. Deferred, not rejected, is
precisely the state in which someone builds Option B by accident.
Operator-facing surfaces follow the decision and nothing else changed on them:
`DOCS.md`'s SAFETY-25 section now says a choice was made and points at the
trigger, and `app/freeze.py`'s finding and `app/peakguard.py`'s point 2 say
"decided, on purpose" where they said "open".
**`PeakStore.record_block()` now has its POLICY ARGUMENT graded, and the
SAFETY-20 import check now looks at all three ways of writing an import
(TEST-13).** Two survivors from TARIFF-01's review, both closed in
`test_tariff.py` only - `app/` is untouched and no shipped behaviour changed.
* **The plumbing of the per-phase reduction was unobservable.** Mutating
`record_block()`'s `billed_w(block, policy)` to `billed_w(block, POLICY_NET)`
left all 17 suites green (+4 B; recorded by TARIFF-01's reviewer, re-run
through the purge harness for TEST-15, and re-run again here). The cause is
the third instance of the same shape as WITNESS-02's span normalisation and
TARIFF-01's own DST window: **a stimulus evaluated where the quantity it
grades is degenerate.** `billed_w()` short-circuits to `block.offtake_avg_w`
whenever `per_phase_offtake_avg_w` is absent, and every block that reached a
store anywhere in the suite was single-phase or built with
`per_phase_offtake_avg_w=None` - so NET, SUM and MAX collapsed onto one
number and the argument could not be seen. Section 7 already owns an
UNBALANCED fixture, `(3000, 500, -200) W`, whose three reductions are 3300 /
3500 / 3000 W; that block is now round-tripped **through the store** under
each policy and read back from both tables. NET is the smallest of the three
here, so a store that quietly billed NET while asked for MAX would
under-record the month's peak - maximum headroom for SAFETY-07, the same
under-guarding direction as the `getattr(..., 0.0)` default SAFETY-07 already
removed from `project()`.
* **The import half of the SAFETY-20 grader made a claim it did not check.** It
collected `ImportFrom.module` only, which is blind to two of Python's three
import spellings: `from . import arbiter as _ab` is an `ImportFrom` whose
`.module` is **None** (the module name is in `.names`), and `import
app.arbiter` is an `ast.Import` node the walk never visited. Both were added
to `app/tariff.py` and the shipped suite stayed **green**. Never a live
exposure - the `_names` half still catches any USE of either alias - but the
printed sentence "it imports nothing from arbiter, clamp or control" was
false for two forms out of three, which is worse than claiming less. The
grader now walks `Import` as well, joins `from . import X` onto its base, and
matches per dotted SEGMENT so `app.arbiter` cannot hide behind a package
prefix while `clamps` / `arbiters` / `controller` are not falsely flagged.
Both graders are also now shown non-vacuous against `main.py`, which really
does import all three modules.
* **Two items on the card were already closed and are struck, not
re-implemented.** `PeakReading.is_observed` is `self.state == OBSERVED`
(`app/tariff.py:266`), already false for `NO_RECORD`; and `project()`'s
`held` read is `max(averager.held_net_w, 0.0)` with **no** `getattr` default,
fixed by SAFETY-07 in 616b62d with a comment naming TEST-13 item 4. Restoring
a default there would re-open a money guard. Removing `clear_partial()` also
stays green and that remains a **PASS**: the `quarter_start` PRIMARY KEY plus
`ON CONFLICT ... WHERE excluded > existing` makes a replay a structural
no-op, which is TARIFF-01's claim rather than a hole in it.
Verified through `tools/mutation_run.sh` (purge, `python3 -B`, tree re-read from
disk, mutated line grepped off disk, byte delta recorded): 7 mutations, all red
on the named checks, plus green baselines before and after and a control run
showing the shipped suite passing every one of them.
**The two `arbitrage()` rungs SAFETY-26's AC4 sweep found pinned from ONE SIDE
ONLY are now pinned from both - and, the actual finding, are pinned so they stop
MASKING EACH OTHER (TEST-16).** `spread == 0.0` weakened to `<= 0.001` survived
the whole suite at +2 B, and `len(firm) < 2` weakened to `< 1` survived at
+0 B - the delta MUTATION.md names as the risky one. Neither was individually
live, and that was the problem: a single firm hour *also* has a spread of zero,
so each rung's failure was absorbed by the other and both could be weakened
together with nothing reporting it. That is invisible to single-mutation
testing, which is how the pair survived four rounds of review on TARIFF-03 and
FCST-03. `test_static_tariff.py` gains section 9, which grades WHICH RUNG
answered each stimulus rather than only whether it refused - the masked case
refuses correctly while reporting the false sentence "the tariff is flat" about
a series that is not flat, so a check asserting only "refused" passes on a
broken tree. The flat rung is swept with small-but-REAL spreads down to
0.000001 EUR/kWh at `min_spread_eur_kwh=0.0` (a value `arbitrage()`'s docstring
documents and its validator accepts on purpose), the firm-pair rung is probed
with a ONE-FIRM-HOUR series and graded on §8.3's sentence coming back rather
than the flat rung's, and a five-row table denies the masking on both sides.
Verified through TEST-15's `tools/mutation_run.sh` unchanged - recursive
`__pycache__` purge, `python3 -B`, tree re-copied from disk between rounds,
mutated line grepped off disk, byte delta printed: 7 mutations plus a green
baseline, 4 of them at +0 B, ALL RED, including both rungs weakened AT ONCE
(5 checks red). **No shipped behaviour changed - both rungs were correct all
along**; `app/` is untouched. `MUTATION.md` gains a section on masking as a
second way a survivor lies, and `test_arbitrage.py`'s SAFETY-26 AC4 note is
marked closed rather than left reading as an open finding.
**`check_output_clamp()` could be moved above `write_setpoint()` in `cycle()`
with test_clamp.py, test_freeze.py and test_loop.py all staying GREEN — the
guard's write-path evidence, `self.clamp_last`, had nothing watching it.**
Measured before the fix, on the move itself: all three suites green. The guard
has two evidence sources and only one of them was covered. `self.loop_clamped`
is set from the `Decision` well above the write, so it survives the move — and
on the §10.3 runaway replay it is the source of every engagement the alarm
reports (0 write-path engagements against 2 loop-side ones), which is precisely
what made the move nearly invisible. `self.clamp_last` is assigned by
`write_setpoint()` and by nothing else (`main.py`), is `None` until it has run,
and is what `engaged_write` reads; moved above the write, that consumer goes
quietly false and a DEVICE-bound clamp — `max_w` above the inverter's own
rating, SAFETY-20's install — stops being reported by anything.
test_clamp.py gains part 6, and it grades the CONSEQUENCE rather than the
position: a spy subclassed from the shipped `ClampWatchdog` records what
`self.clamp_last` held each time the guard consulted it, over a slew-limited
ramp where every cycle's command is a different number, and asserts the
evidence is always the write of THAT cycle. Hooking `clamp_wd.note()` rather
than the guard's name is what keeps a rename legitimate; the same assertions
are re-run through a controller whose guard is renamed and whose write lives in
a helper, and were verified against `main.py` itself — renaming the method
throughout and moving both calls into a new `_emit_and_guard()` helper keeps
part 6 green, while swapping the two calls turns it red on a line that names
`clamp_last`. AC 3 needed a stimulus of its own: through the real `cycle()` the
write-path half can never engage, because the arbiter files the device range
and `max_w` as P_SAFETY LIMIT claims and `resolution.target_w` is already
inside both bounds before `write_setpoint()` re-applies them — that duplication
is deliberate defence in depth, and part 6 now measures the 0 engagements
rather than leaving it as a claim in a comment. So the write path is driven
directly at `max_w` 5000 against a ±2500 W device: the wire carries 2500 W,
every loop-side flag stays clean, and the alarm fires on `clamp_last` alone —
with the two calls swapped, the same stimulus clamps the same value and the
alarm is silent. `main.py` gains one comment sentence pointing at the check,
mirroring the one SAFETY-18's block already carries for test_freeze.py part 5.
**`max_w` and the `LIVE_MAX_W` literal beside it were unpinned in test_freeze.py
and test_tariff.py, the same gap TEST-06 closed one key over for
`meter_freeze_s` (TEST-10).** Measured before the fix: `max_w: 2000 -> 4500`
in `config.yaml` left every check in both files GREEN, and `LIVE_MAX_W = 5000.0`
was a bare literal that silently disagreed with the shipped default (2000) with
nothing saying so — for contrast, `deadband_w: 15 -> 5` already went RED 2 + 1,
so the pinning technique itself was known to work, just not applied here.
Fixed three ways. First, `test_freeze.py` gained a check comparing `Tuning()`'s
code default (`control.py`, 2000.0) against `SHIPPED_MAX_W`, read from
`config.yaml` by extending the file's existing `_cfg_default()` regex reader
rather than reimplementing test_arbitrage.py's `_shipped`. Second, the literal
itself is renamed `LIVE_INSTALL_MAX_W` in both files, with a comment stating
plainly that 5000 is the live install's own override and not config.yaml's
shipped `max_w` — the defect was the silent literal, not the number. Third,
`test_freeze.py` now states `PINNED_KEYS = ("meter_freeze_s", "deadband_w",
"max_w")` in one place as the complete set of config keys this suite pins,
deliberately excluding `maintenance_*` (CFG-03 gave those a separate source of
truth in `app/maintenance.py`). Verified by breaking what the new check
watches: `max_w: 2000 -> 4500` in `config.yaml` now fails exactly
`"the code default and the shipped default agree on max_w too"` and nothing
else, and reverting returns the file to all-green.
**Maintenance option defaults lived in three places that had already disagreed,
and MAINT-04's tripwire was holding them apart rather than closing them
(CFG-03).** `config.yaml` shipped `maintenance_charge_w: 2000`, `main.py` carried
two `opts.get("maintenance_charge_w", 2500)` fallbacks, and `MaintConfig`'s
dataclass carried a third `2500.0`. An options dict with the key **absent** was
therefore accepted by `validate.py`'s rule 6 — which read 2000 — and then built
by `main.py` at 2500, against a 2000 W ceiling. Demonstrated through the shipped
code:
options dict with maintenance_charge_w ABSENT, max_w=2000
validate_startup_config -> [] (ACCEPTED, no problems)
MaintConfig().charge_w -> 2500.0
arbiter.resolve() -> 0.0 W, contradiction=True
That is the bug rule 6 exists to refuse, **passing rule 6**. Unreachable through
the Supervisor, which always supplies every key from `config.yaml`; fully
reachable from `sim/inject.py` and from the test suite, which is where anyone
debugging maintenance is.
**`maintenance_discharge_w` had the identical divergence** (`config.yaml` 2000,
`MaintConfig` 2500) and the card named only the charge side. Closing one key and
leaving its twin would have reproduced the defect one line down, so both are
closed.
**The single source of truth is `config.yaml`'s `options:` block** — the file the
Supervisor reads and the operator edits. There is now exactly **one** in-code
copy, `maintenance.MAINT_OPTION_DEFAULTS`, which is TARIFF-02's
`PRICE_OPTION_DEFAULTS` and SAFETY-24's `PEAK_OPTION_DEFAULTS` pattern applied to
the family that named the card. A mirror rather than a runtime read because the
`Dockerfile` copies `app/` and `run.sh` into the image and **not** `config.yaml`:
the running add-on cannot open the file it is configured by. `test_maintenance.py`
pins every entry by **reading** the shipped file, so a drift is a CI failure
rather than a comment. Every other declaration site now derives from it or has
ceased to exist:
- `MaintConfig`'s eight dataclass defaults are indexed out of the mirror — no
numeric literal survives in the class that held the third opinion;
- `MaintConfig.from_options()` is the **only** place in the add-on that reads a
`maintenance_*` option. `main.py`'s eight inline `opts.get(key, <literal>)`
calls are gone;
- `main.py`'s second fallback site (the cheap-window charge floor) reads
`self.maint.cfg.charge_w` instead of re-opening the options dict, so the rate
the shaping asks for and the rate the state machine drains at cannot be two
numbers from one install;
- `validate.py`'s rule 6 and its `maintenance_discharge_w` warning take their
fallbacks from the mirror.
**Where the RANGE lives is now stated and checked, so the next person does not
add a fifth site.** `maintenance_charge_w: int(500,5000)` in `config.yaml`'s
`schema:` block is a fourth declaration of a different kind — a bound, not a
default. Bounds live in the schema block **only**: the Supervisor enforces them
and reads only that file. `test_maintenance.py` asserts that every mirrored key
has a schema entry (or the Supervisor silently drops the option and the add-on
runs on the mirror instead of the operator's value) and that every shipped
default lies **inside** its own range. What the schema grammar cannot express is
a relation *between* keys — `maintenance_charge_w` against `max_w` — which is
why rule 6 is written in Python and does not belong in the mirror either.
**MAINT-04's tripwire in `test_validate.py` is DELETED, not left passing**, as it
and `validate.py`'s ⚠️ block both instructed each other to do. Its passing
condition *was* the bug. In its place, the same four consumers exercised the same
way and now agreeing: the validator accepts a dict with every `maintenance_*` key
missing, a **real `Controller`** built from that dict holds 2000 W, `MaintConfig()`
answers 2000 W with no dict at all, and the real arbiter emits `-2000 W, limited
by supervised(max_w)` instead of `0 W, contradiction=True`.
**Checked by breaking it, five ways, each observed red before being reverted:**
move `config.yaml` alone → the mirror pin fails; move `config.yaml` **and** the
mirror to 1500 → every consumer follows together (`MaintConfig()` 1500 W, the
`Controller` 1500 W, the arbiter `-1500 W, limited by maintenance(cheap-window
charge)`) and both suites go green again; retype `charge_w: float = 2500.0` into
the dataclass → red; restore `opts.get("maintenance_charge_w", 2500)` in
`main.py` → red; delete a key from `config.yaml`'s options block → red.
Stale prose that asserted the closed divergence as current is corrected in
`app/watchdog.py`, `test_watchdog.py` and `test_peakguard.py`.
**`peak_soc_floor` reads like a pack-wide reserve and is not one, and on a
sustained-load evening the grid-following loop discharges straight past it to
the BMS cut-out (SAFETY-25).** The gap has been written down four times without
being filed — SAFETY-18's finding (`freeze.py`), SAFETY-24's module note, its PR
body, and its honestly-uncaught 13th mutation — and never once measured. It is
measured now, on the committed 2026-08-20 capture, driving the shipped
`control.compute()`, `peakguard.decide()`, `peakguard.claim()` and the real
`arbiter.resolve()`:
19:00-22:00 UTC, 830 W mean, minimum 701 W, not one watt of export
reference pack (300 Ah x 51.2 V x DoD 90) started at 21 %, one point
above peak_soc_floor
ends at 10.0 % - the bms_soc_floor cut-out
1525 Wh delivered by the LOOP over 587 cycles
549 cycles below peak_soc_floor, 343 of them still discharging
0 cycles on which the peak guard filed any floor at all
**And it is a behaviour, not a config value.** The same evening ends at
`9.9715 %` at `peak_soc_floor` = 5, 11, 20 **and** 60 — the shipped value and
both ends of the schema range — identical to four decimal places. The option an
operator would reach for cannot move the number by any amount. On the same day's
high-load block the two states coexist: 49 cycles reporting `PEAK GUARD
FLOOR-LIMITED` and, on **all 49**, the arbiter simultaneously granting the loop
up to 2000 W of discharge.
**Why SAFETY-24 could not close it.** The peak guard files a `lo` limit — a
*lower* bound. That asymmetry is what makes it provably unable to lower a target,
cap a discharge or contradict the arbiter, and it is therefore equally unable to
stop a discharge the loop itself wants. A floor on the guard cannot become a
floor on the pack by being raised.
**What changed is the honesty, on four operator-facing surfaces**, because that
half is required whichever way the open question is answered and it is the actual
misstatement on the live system today:
- `config.yaml` says next to the option that it **bounds the peak guard only** and
is **not a pack-wide reserve**, with the replayed evening and the sweep;
- `DOCS.md` says it in the options table and in a new section carrying the
figures above;
- the **status-page row** for a floor-limited guard carries the scope sentence —
it is the one line a human reads at the moment the guard stops, and read alone
it implies a reserve the replay shows does not exist;
- the **persistent notification** says what has stopped (the guard buying a lower
bill) and what has not (the pack being spent).
`peakguard.py` and `freeze.py` carry the measurement beside the findings they
already recorded.
**The product decision is NOT taken here.** Whether the loop gets a reserve floor
of its own moves real energy on this house and belongs to the owner.
`DECISIONS/SAFETY-25-loop-soc-floor.md` records the options, what each costs and
protects, weighed against MAINT-01 and against the fact that this would be the
**fifth** SoC key (OPT-04's `arbitrage_soc_floor` fired SAFETY-24's "revisit if a
third floor appears" trigger unremarked), and a recommendation. It also records a
trap found while writing it and now checked through the real arbiter: the obvious
shape — a `hi` limit on the loop — crosses the peak guard's `lo` and resolves to a
**CONTRADICTION at 0 W**, the battery parked in the quarter that sets the bill,
unless `bms_soc_floor < loop_soc_floor <= peak_soc_floor` is enforced at startup.
**`test_peakguard.py` part 10 is a tripwire, not a guarantee, and part 10f is
what makes it one.** The replay half records the defect; on its own it could not
see the defect being FIXED, because `replay_loop()` hand-builds main.py's claim
list and is therefore blind to any claim main.py adds — which is exactly where a
loop-side floor would be built. PR #31's reviewer proved that by building the
memo's own Option B in `main.py` and watching the whole suite stay green. **10f
pins the claim-source set:** every `claims.append(...)` in `Controller.cycle()`
is read off its AST and must be one of eight named sources, and real
`Controller.cycle()`s — spied at main.py's own `resolve`, swept over the whole
0–100 % state-of-charge range in both the idle and the floor-limited state — must
hand the arbiter exactly `{device, supervised, loop}` and
`{device, supervised, loop, peak}`. A ninth source, at any state of charge, in
any configuration, takes part 10 red on the line it is written. A floor built
inside `control.compute()` or the guard instead moves 10a–10c's replayed numbers,
which the replay drives directly. So the exposure cannot change size under a
green suite.
**Nine mutations, re-run against the fixed tree**, each against a freshly copied
tree with no `__pycache__` present at all, mounted `:ro` — the same structural
immunity `MUTATION.md` records for CI. Six are the AC 3 and behaviour mutations
already on this ticket's record (the status row's scope sentence, the
notification's, `config.yaml`'s, the memo deleted, the loop's gain zeroed, the
guard's claim given a `hi`); two are the reviewer's, and are the ones that
motivated 10f — the memo's own Option B at its recommended default, **now three
checks red where it was fully green**, and an absurd always-binding 95 % reserve,
**six red**; one is new, against the banner short form below. All nine are red,
no survivors, and no byte delta is `+0 B`.
**The gate has never once graded the content a pull request would land, and a
run that never started reported as a test failure (CI-02).** Both halves were
measured on a deliberately conflicted throwaway pull request rather than read
off the workflow, because the Actions log endpoints 404 on this Gitea and a
step's own conclusion is the only channel out of a job.
**Case 1, and the ticket's mechanism was wrong in a way that made it worse.**
CI-02 was filed saying a conflicted pull request loses its merge ref, so that
`git fetch $GITHUB_REF || git fetch $GITHUB_SHA` falls through and grades the
bare branch head. The symptom was real — PR #14 reported `checks / unit ->
success` while `mergeable: false` — but the mechanism is not. On this server
`GITHUB_REF` **is** `refs/pull/<n>/head`, `GITHUB_SHA` is the same commit, and
`git ls-remote origin 'refs/pull/*'` advertises no `/merge` refs at all, for
open and closed pull requests alike. The first fetch has always succeeded; **the
fallback has never fired once.** So the gate did not lose merged content on
conflicted pull requests — it has never had merged content, on any pull request
in this repository's history. Green has meant "this branch passed on its own",
which on a base that has moved is not what lands, and `block_on_outdated_branch`
is off on release/1.0 so the base usually has moved.
**The checkout now fetches the base tip and the pull request head, merges them,
and refuses if the merge does not apply** — as its own named step, so
`/actions/runs/<id>/jobs` distinguishes "nothing was tested" from "the tests
spoke". Verified by producing it: with the fix on a conflicted pull request the
required context went `failure` in 2 s with the two test steps `skipped`. The
`--depth 1` is gone (a merge needs a merge base; a full fetch of this repository
is 6.8 MB and 1.1 s), and the fallback survives only on the `workflow_dispatch`
path, which has no pull request to merge and now says so in its output.
**Case 2: `concurrency:` is gone, and `cancel-in-progress` was never the knob.**
Runs 531 and 533 on PR #14 were cancelled at 0 s each at the exact second the
next run was created, having never started; a cancelled run posts `failure` on
the required context, described `Canceled after 0s`, and branch protection
compares state and not description — so "nothing ran" and "your tests are
broken" arrive at the gate as the same red, wanting opposite responses. Three
settings were measured with one run holding the single runner slot and two
pushes behind it: with **no block at all** both queued runs survived and
executed; with the group kept and **`cancel-in-progress: false`** the queued run
was still cancelled at 0 s. A shared group cancels a run that has not started
regardless of that flag. Having no group is the only configuration measured to
leave a queued run alive, and it is what ships. The cost — a developer who
pushes four times occupies the shared runner four times — is CI-01's own trade
written the other way round: a delayed verdict, never a destroyed one.
**`test_ci_gate.py` grades the gate by running it, not by reading it.** It
extracts the checkout and merge steps out of `checks.yml` and executes the
shipped commands against two throwaway local repositories it builds — one whose
pull request merges, one whose does not — and pins that the old one-liner exits
0 on the unmergeable one while the new steps refuse. It also pins the two tokens
that assemble `checks / unit (pull_request)`: renaming `name:` or the `unit:`
job key would leave every open and future pull request waiting forever on a
context that never arrives, with no error anywhere in that sequence. Seven
mutations of `checks.yml` were each confirmed red. `.gitea/ci/Dockerfile` gains
`git` for it.
**What was NOT established, stated so nobody reads more into this.** The
original report that "no run was ever created for `0942228d`" was already
corrected on the card — run 533 was created and cancelled — and this work
confirms that from the runs list and the per-commit status history. A commit
that never had a run carries an empty `/statuses/<sha>` list; a queued one
carries `pending / Waiting to run` within seconds, and a concurrency-held one
`pending / Blocked by required conditions`. Those are distinguishable at the
API. `/actions/tasks`, which is what was polled originally, lists only tasks
that started, and cannot answer the question at all.
**The NOT READY banner no longer repeats the row underneath it.**
`status_payload()` renders the first hard-failing check as the page headline, so
the scope sentence above turned the loudest element on the page into a
550-character paragraph that the checks list then repeated verbatim. A row may
now carry an optional short `banner` form; the floor-limited row does, and its
headline is the guard's own line plus a 68-character scope tag. **The row itself
is unchanged** — the checks list is where an operator reads what the floor does
and does not bound, and shortening that would have been weakening AC 3. Rows
without the key are unaffected, and the page still renders with `textContent`.
**A setpoint device smaller than `max_w` silently disarmed the frozen-meter
detector, and the status page reported it as armed (SAFETY-20).** SAFETY-18's
conjunction needs `abs(commanded_w) >= 0.95 * max_w`, but the emitted command is
clipped to the setpoint device's own `[dev_min, dev_max]` range as well as to
`max_w` — in `clamp_to_rating()` and again as the arbiter's `device` P_SAFETY
limit claim. Measured on the shipped predicate at the ticket's numbers,
`max_w: 5000` on a ±4700 W inverter:
looks_frozen(unchanged_s=3600, commanded_w=4700, max_w=5000) -> False
The command is pinned at the hardware's rail, the meter has been frozen for an
hour, and term 2 is unsatisfiable by construction because 4700 < 4750. Any
rating at or below `0.95 * max_w` disarms the conjunction outright. The page
then printed `armed (… command is over 4750 W)` — a guard that cannot fire,
advertising that it can, which is the failure SAFETY-15, SAFETY-19 and
validate.py rule 5 all exist to prevent.
**The rail is now measured against `min(max_w, |dev_min|, |dev_max|)`** —
`freeze.rail_ceiling_w()`, threaded through `looks_frozen()`,
`FreezeWatchdog.evaluate()` and both call sites in `main.py`. An unread rating
(`hass.limits()` returning `None` when ESPHome is not up) leaves the old
behaviour exactly, and correctly: on that path no device clamp is applied
either, so `max_w` really is the ceiling. A rating *larger* than `max_w` cannot
raise the rail — this is a `min()`, not a swap. The status row prints the rail
the predicate actually uses and names the device when the device is what capped
it; the log line and the HA notification do the same, since they outlive the
page.
**The smaller of the two device bounds, not a per-sign pair.** A per-sign rail
is tighter and is not wrong, but it is two rails needing two coverage verdicts
on a status row that carries one number, and the only configuration that
distinguishes them is refused at startup anyway. The symmetric ceiling can only
*lower* the rail, which widens term 2 rather than disarming it; term 1 carries
the no-false-positive argument and is untouched.
**A ceiling of 0 W is NOT COVERED, not "armed at 0 W".** A device that can
command nothing in one direction would make `abs(command) >= 0` true of every
command including a parked one — term 2 degenerately *true*, collapsing the
conjunction into the bare `unchanged_s > N` threshold TEL-05 refused for
false-tripping at this controller's own operating point. `rail_unreachable()`
returns the reason, `looks_frozen()` stays silent, and the page uses the NOT
COVERED row the unsupported-transport case already has — a second reason to use
that surface, not a new mechanism.
**AC4, decided rather than assumed: no new `validate.py` rule.** The
configuration is `max_w` above the device rating, which rule 2 (CFG-01) already
refuses on the identical predicate, re-run by `run_control()` once the real
rating is known. A rail-specific rule would fire on a strict subset of what rule
2 refuses (`0.95 * max_w > dev_max` implies `max_w > dev_max`) and could never
be the rule that stopped a start. The residue is the state where `hass.limits()`
answered `(None, None)` and the range checks were skipped — there is nothing to
refuse there, by construction, which is why the answer is a runtime row. Written
into validate.py's "deliberately not refused" list, and *pinned* by four checks
in `test_validate.py` so the decision's premise goes red if rule 2 is ever
softened back to a warning.
**And it was verified by breaking it.** Reverting `rail_w()` to bare `max_w`
fails nine checks; deleting the NOT COVERED handling fails five; and — the one
that mattered — shipping the corrected predicate while *not* passing the rating
from `check_meter_frozen()` originally left the whole suite green, because
nothing graded the caller. `test_freeze.py` part 5b now drives the real
`cycle()` on a ±4700 W device and asserts on the notification that leaves the
process; the unwiring mutation fails three checks there. The peak-guard call
site's wiring is still ungraded — it sits behind `p1_enabled` and needs a fed
averager to have any observable consequence — and that gap is named in the file
rather than implied.
**A mutation run could grade code that was not there, and the fix is a purge
rather than a flag (TEST-15).** FCST-03's developer reverted `self.provisional`
to `here.provisional`, re-ran, and reported a survivor; disassembly showed the
source read `here` while the running code loaded `self`. CPython validates a
`.pyc` on (source size, source mtime truncated to whole seconds), and a
size-preserving edit reverted inside one second moves neither number, so the
stale bytecode was reused. That does not make past results wrong - it made them
unverified, and the distinction is the whole card.
Reproduced rather than reasoned about. `test_bytecode.py` builds a real package
whose two return values are the same length, imports it in a real subprocess,
rewrites it inside the same second and reads back which value ran. Part 1 shows
the interpreter running `SELF` off a file that says `HERE`.
**And it shows the two obvious mitigations do not work.** `python3 -B` and
`PYTHONDONTWRITEBYTECODE=1` are write-side only: neither stops an EXISTING stale
`.pyc` being read, and a mutation run always has one because the previous run
wrote it. The advice already in `test_control.py`'s coverage audit led with `-B`
and is corrected here - the purge is the half that works, and `-B` earns its
place by protecting the NEXT edit rather than this one. No `sleep` anywhere:
one-second mtime resolution is the mechanism, and waiting it out would slow every
run down while still only covering the edit somebody remembered to slow.
`goodwe_controller/tools/mutation_run.sh` is the harness the house adopts: it
purges, prints a sha256/byte fingerprint of every `app/*.py` it is about to
grade - so a mutation report can say WHICH source produced it - runs each suite
under `python3 -B`, refuses a tree with no `test_*.py` (CI-01's rule), and fails
if a cache appears during the run. It takes the tree as an argument so the infra
repo's replay harnesses can call it.
`MUTATION.md` states the guarantee where a mutation gets written, and every one
of the 16 suites now points at it from its docstring - a list `test_bytecode.py`
derives from the tree, so a new suite joining without the pointer is red.
CI was already immune and is described that way rather than as a hole being
closed: `checks.yml` mounts the checkout `-v "$WS:/w:ro"`, and a read-only tree
cannot take a `__pycache__` at all - measured, and it fails silently, exit
status 0 - while each job `rm -rf`s its workspace and clones afresh.
`PYTHONDONTWRITEBYTECODE=1` is added as belt and braces, because the `:ro` is one
character wide. The shipped add-on was never affected: `Dockerfile` has set
`PYTHONDONTWRITEBYTECODE=1` since it was written.
**The survey of this week's mutation claims is in `MUTATION.md`, scoped by the
property rather than by re-running everything.** The defect is one-directional -
stale bytecode turns a red into a green survivor and never the reverse - so every
"all red, no survivors" result in the window is not at risk, and the exposure is
the recorded SURVIVORS from source-edit runs made before the purge discipline
landed on 2026-08-31. Two of them were re-run here under the harness and both
still stand (TARIFF-01's `record_block()` ignoring its `policy` argument;
SAFETY-03's `abs()` on the clamp limit). The rest are labelled still-unverified
rather than quietly assumed or noisily re-run.
Out of scope and recorded: the infra repo's `sim/` replay harnesses import the
add-on and write bytecode into both trees. Anyone mutating a module graded by a
replay must purge both by hand until that repo adopts the harness.
**`release/1.0` went red at midnight on a commit nobody had touched (TEST-17).**
`Controller.checks()` read the capacity-tariff peak with `self.peak.peak()` - no
argument - so `tariff.py` resolved the month from `datetime.now()`, while
`test_tariff.py` section 10 banks its quarter at the fixed fixture
`2026-08-30`. From 1 September the page was correctly asked for September,
correctly answered `NO_RECORD`, and the row read *"no completed quarter recorded
yet"* - a string containing no `"peak"`, which the section's filter required.
Four checks failed. The suite had been a latent time bomb since TARIFF-01
merged on 2026-08-30 and every PR that ran it ran in August.
Isolated by holding the commit and the image constant and moving only the clock
under `libfaketime`: green at 2026-08-30, four failures at 2026-09-01, identical
at `f4914a1`, `04292c4~1` and `04292c4`. The calendar, not a regression.
**The product was right and the test was wrong**, so the fix does not change what
the live page says. `checks()` takes `when: datetime | None = None` and threads
it into `peak()` and `warning_frac()` - the convention every other peak query in
`tariff.py` already follows. The single production caller passes nothing and
still means today. Section 10 now grades at its own fixture's month.
Three new checks make the defect detectable rather than seasonal: the same
controller read at two different reference months must produce two different
rows, which no clock can satisfy; the later month must read `NO_RECORD` and stay
distinguishable from both an observed peak and an unreadable store; and calling
`checks()` with no argument must still mean today. Verified by mutation - a
`checks()` that drops `when` is now red at every clock tried, where the old
section went green in August. Full suite green, 15 files, at the real clock and
at faked clocks in four other months.
One thing left alone deliberately: only the UNREADABLE branch prefixes its row
with `capacity-tariff peak:`. The `NO_RECORD` row carries neither that phrase
nor the word `peak`, which is what made the original filter brittle and what
broke the first draft of the new checks too. It is product text with other
suites reading it, so it is noted here rather than changed.
**Thirty days of the real meter, and the acceptance criterion three cards
deferred is now a number (DATA-01).** TARIFF-01 and SAFETY-07 both merged with
AC 3 - *"monthly peak held under the soft limit in >= 95 % of intervals over a
@@ -0,0 +1,417 @@
# SAFETY-25 — does the grid-following loop get a reserve floor?
**Status: DECIDED 2026-09-02 — Option A.** The product owner has answered §1:
**the BMS cut-out stays the only backstop for demand-driven discharge on the
grid-following loop.** **Option B — a loop-side reserve floor — is DEFERRED**,
not rejected, with an explicit revisit trigger recorded in §0c: **`ALLOC-01`**.
Option A **is the shipped behaviour**, so recording this decision changed no
code. The honesty half of SAFETY-25 — `peak_soc_floor`'s scope made true in the
config, in `DOCS.md` and on the status page — had already shipped and was
required under every option. What was missing was the answer, and the answer is
now here rather than in a Trello card that scrolls away.
**Everything from §1 down is the memo exactly as it was written before the
decision, and is deliberately left intact.** It is the record of *why*, and a
future reader arriving at the revisit trigger needs the options analysis, the
costs, the measured replay and the trap in Option B's obvious shape — not a
one-line verdict. §5 still labels Option B *"(recommended)"* and §6 still says
"Option B is what I would build"; those were the engineering recommendation put
to the owner, they are preserved as written, and **§0 is what was decided.**
Filed with SAFETY-25. Card 6a94b2b98b73123d520e69f2. The other half of that
ticket — making `peak_soc_floor`'s scope honest in the config, the docs and on
the status page — **shipped in SAFETY-25's own PR** and did not wait on this,
because it was required whichever way the answer went.
*This directory exists so a recorded decision has somewhere to live that is not a
comment in a source file nobody reads and not a Trello card that scrolls away.
`SAFETY-27` asks for a second one (the naming of the floors); it belongs here
too, and §0d says what N=2 does to it.*
---
## 0. The decision
### 0a. What was decided, and the owner's reasoning
**Option A. The BMS remains the only backstop for demand-driven discharge on the
grid-following loop. Option B is deferred until `ALLOC-01` exists.**
The reasoning is not "Option B is wrong" — §5 and §6 still stand as engineering.
It is that **deferring is the safe direction, and building now is not.**
Option B's safety proof is the ordering constraint in §5:
bms_soc_floor < loop_soc_floor <= peak_soc_floor
That proof has an unstated premise: **the reserve predicate and
`discharge_permitted()` must read the SAME state of charge.** At N=1 they do,
which is why the proof reads as airtight, and why part 10d can run it through
the real arbiter and watch the contradiction disappear.
**With two packs they read different numbers.** The reserve binds on whichever
pack is emptier and files `hi = 0`; the peak guard, reading the other pack or an
average of the two, is *not* floor-limited and files `lo = excess > 0`. Then
`lo > hi`, arbiter clause 3 fires, and the result is **0 W — the battery parked,
in the billed quarter.** That is precisely the failure §5 marks *"⚠️ fatal if
missed"*, arriving by a route the ordering rule cannot close, because
`loop_soc_floor <= peak_soc_floor` is still perfectly satisfied while it happens.
**And no config-ordering validator can catch it.** The rule §5 proposes — refuse
the bad ordering at startup, in CFG-01's manner — grades *configuration*. This is
a **runtime divergence between two readings**, not a config ordering. The startup
check would pass, every time, on the exact tree that parks the battery.
So the shape of the risk decides the direction: **Option A's cost is energy
(§5, "every watt below the reserve becomes billed import" — inverted: the pack
may sit on its own cut-out). Option B's cost, built too early, is a parked
battery in the one quarter of the month that sets the bill.** One of those is a
tariff line; the other is the failure this memo already calls fatal. Take the
one that cannot park the battery, and build Option B when its proof holds again.
### 0b. What this decision does NOT say
- It does **not** say a loop-side reserve is a bad idea. §5's protection
argument — keeping the pack off its own cut-out, which is the `MAINT-01` drift
condition — is unchanged and still wanted.
- It does **not** close §4's fifth-key question. `SAFETY-27` still owns the
naming of the floors, and any future `loop_soc_floor` still lands after it.
- It does **not** weaken §6 item 3: **the tripwire in `test_peakguard.py`
part 10 stays.** A deferred option needs its tripwire more than an open one
does, because "deferred" is exactly the state in which someone builds it by
accident. Part 10f still takes red on the line a ninth claim source is
written. Do not remove it.
### 0c. The revisit trigger: `ALLOC-01`
**`ALLOC-01` is the trigger, and it is a trigger because it changes the SHAPE of
the two claims, not because it changes anyone's mind.**
`ARCH-01` decided that the site grid target is **allocated host-side, above the
driver seam**: one integrator on P1, a sum-invariant split into per-inverter
shares, and each inverter told a function of **its own share** only. It also
decided that **per-inverter constraints are consumed by the allocator as
INTERVALS, never filed as site-level claims** — which is the structural fix for
the cross-inverter `lo > hi -> 0 W` contradiction.
Under the allocator, the two claims that collide in §0a stop sharing a claim
list at all:
| | today (N=1, no allocator) | under `ALLOC-01` |
|---|---|---|
| the loop reserve | a site `hi` at `P_LOOP` | a **per-inverter `hi`**, consumed at **stage A** as that unit's interval |
| the peak floor | a site `lo` at `P_PEAK` | still a **site `lo`**, filed at **stage B** against the site target |
**Different claim lists, evaluated at different stages, structurally unable to
cross.** The reserve bounds one inverter's share; the peak floor bounds the site
sum. There is no arbiter resolution in which one is the other's `lo` and `hi`,
so §0a's failure cannot be constructed — not "is guarded against", *cannot be
constructed*. That is the same class of argument as §5's ordering rule but a
stronger one: §5 makes the crossing harmless, `ALLOC-01` makes it unreachable.
**That is the shape in which Option B becomes safe to build.** When `ALLOC-01`
exists, reopen this memo at §5 Option B, restate the reserve as a stage-A
per-inverter interval, and the ordering rule becomes an implementation
convenience rather than the load-bearing proof.
### 0d. What has to be RE-EARNED at N=2, stated plainly
Two things this decision leans on do not survive a second pack, and saying so is
part of the decision rather than a footnote to it.
**1. `SAFETY-27` now names FIVE floors across TWO packs.** §4's table already
carries four keys plus "the loop"; two of them ship the same default of 20 from
different cards. At N=2 each of those is a floor *per pack*, and "the SoC" stops
being a scalar the config can bound — which is the same divergence that makes
§0a's contradiction possible. `SAFETY-27` inherits a harder question than the
one it was filed with.
**2. `test_peakguard.py` part 10f — the guarantee that made SAFETY-25 mergeable —
CANNOT EXPRESS TWO PACKS, and will not cover the two-pack case.** Say it flatly,
because it is the load-bearing pin (§6 item 3: PR #31 shipped this section
claiming a tripwire it did not have, and the reviewer disproved the claim by
building Option B under a green suite):
- 10f's dynamic half is a **scalar 0–100 % SoC sweep** — one number swept over
one range, in the idle and floor-limited states — against a **single-series
capture** (§7: the fixtures carry signed net power at the meter and nothing
else; the pack is modelled, and one pack is modelled).
- A two-pack exposure lives in the **difference** between two SoC readings. A
sweep over one scalar visits no point of that space, at any resolution. It
cannot fail on the divergence because it cannot represent it.
- 10f's **static** half — the AST scan pinning the eight claim sources in
`Controller.cycle()` — survives, and is the half that keeps working: a ninth
source still goes red on the line it is written, at N=2 as at N=1. It is the
*dynamic* half, the one that proves the named sources actually reach the
arbiter across the whole state space, that goes silent.
So: **10f remains a valid tripwire against building Option B today, and is not a
guarantee about N=2.** Whoever reaches the `ALLOC-01` revisit inherits the job of
re-earning it — a two-pack fixture with two SoC series, or a claim-shape argument
at stage A that does not need one. Merging a two-pack reserve on 10f's current
green is merging on a check that cannot see the failure.
---
## 1. The question
> Does the grid-following (self-consumption) loop get an SoC floor of its own, or
> is the BMS cut-out **deliberately** the only backstop under demand-driven
> discharge?
Either answer is defensible. What is not defensible is the state we have been in
for four tickets: **silence, plus a config key called `peak_soc_floor` that reads
like the answer is "yes".**
## 2. What is actually exposed — replayed, not argued
The exposure was written down three times (SAFETY-18's finding, SAFETY-24's
module note and PR body, and SAFETY-24's honestly-uncaught 13th mutation) and
never measured. SAFETY-25 measured it. The replay is `test_peakguard.py` part 10;
it drives the **shipped** `control.compute()`, `peakguard.decide()`,
`peakguard.claim()` and `arbiter.resolve()` over the committed capture
`scenarios/p1-net-2026-08-20.jsonl.gz`, with the battery and the state of charge
modelled (the captures carry meter power only — see §7).
### 2a. A sustained-load evening takes the pack to the BMS cut-out
19:00–22:00 UTC on 2026-08-20 — three hours of house load after the sun has gone,
**830 W mean, minimum 701 W, maximum 1223 W, not one watt of export in the whole
window.** The pack is the 13.8 kWh reference pack (300 Ah × 51.2 V × DoD 90),
started at **21 %** — one point above the shipped `peak_soc_floor`.
| | |
|---|---|
| pack at the start of the evening | **21.0 %** |
| pack three hours later | **10.0 %** — `bms_soc_floor` |
| energy the loop delivered | **1525 Wh** |
| control cycles with the pack below `peak_soc_floor` | **549 of 587** |
| …of those, cycles still delivering discharge | **343** |
| cycles on which the peak guard filed *any* floor | **0** |
### 2b. It is a behaviour, not a config value
The same replay, same pack, same evening, with `peak_soc_floor` set to **5, 11,
20 and 60** — the shipped value and both ends of the schema range:
peak_soc_floor = 5 -> ends at 9.9715 %, 1524.58 Wh out
peak_soc_floor = 11 -> ends at 9.9715 %, 1524.58 Wh out
peak_soc_floor = 20 -> ends at 9.9715 %, 1524.58 Wh out
peak_soc_floor = 60 -> ends at 9.9715 %, 1524.58 Wh out
Identical to four decimal places. **Raising the option does nothing, because the
guard it bounds is not the thing doing the discharging.**
### 2c. The two states coexist in the same cycle
On the same day's high-load block (15:00–17:00 UTC), with the pack started one
point *below* the floor, the guard reports `PEAK GUARD FLOOR-LIMITED` —
*"commanding no forced discharge"* — on **49 cycles**, and on **all 49** the
arbiter simultaneously grants the loop a discharge of up to **2000 W**. The
status page tells the operator the truth about the guard while the pack empties.
### 2d. Stated fairly, because overstating it is how a real finding gets ignored
This is **not** a runaway. Self-consumption discharge is demand-driven and
self-limiting: it stops when the house stops drawing, and every watt of it is
serving load that would otherwise have been imported. It is not SAFETY-18's
frozen-meter rail, and nothing here is spending the pack for a reason of its own.
What it means is narrower and still real:
- the **depth** the pack reaches on a heavy evening is set by the house, not by
anything an operator can configure; and
- `peak_soc_floor` **reads like a system-wide guarantee it is not.** A floor that
binds one consumer and not the other is worse than no floor if its name does
not say so — which is precisely what SAFETY-25's other half fixed.
## 3. Why SAFETY-24's floor cannot be extended to cover this
The peak guard files a `lo` limit — a **lower** bound on the setpoint. That
asymmetry is what makes the guard trustworthy: a reviewer proved across 19,800
combinations that it can never lower a target, never cap a discharge, never
contradict the arbiter, and never file a negative floor. `peakguard.claim()`
leaves `hi` at `+inf` as a fact about the object rather than a rule someone has
to remember.
**A `lo` limit is structurally incapable of stopping a discharge the loop itself
wants.** So the same property that makes the guard safe makes it useless here.
Raising `peak_soc_floor` cannot become the answer; §2b is that statement
measured.
## 4. The floors we already have — and this would be the fifth key
SAFETY-24 recorded a decision to keep `maintenance_soc_floor` separate with an
explicit revisit trigger: *"if a third floor appears."* **The trigger has already
fired, unremarked**, when OPT-04 shipped `arbitrage_soc_floor`.
| option | default | bounds | priority of the consumer |
|---|---|---|---|
| `maintenance_soc_floor` | 11 | the monthly recalibration's **drain target** | `P_MAINTENANCE` 60 |
| `peak_soc_floor` | 20 | the peak guard's forced discharge | `P_PEAK` 50 (a `lo` limit) |
| `bms_soc_floor` | 10 | *nothing* — it describes the pack, so rule 8 can refuse a floor that cannot bind | — |
| `arbitrage_soc_floor` | 20 | arbitrage discharge | `P_ARBITRAGE` 30 |
| **the loop** | — | **nothing** | `P_LOOP` 10 |
Two of them ship the same default (20) from different cards for different
reasons, which is how a value that looks deliberate becomes a coincidence nobody
dares change. **`SAFETY-27` owns the naming question and this memo does not
pre-empt it** — but any answer to §1 that adds a fifth key should land *after*
SAFETY-27's decision, or it adds a fifth accreted name to four.
## 5. The options
### Option A — record the BMS as the deliberate backstop; add nothing
Say plainly, in `DOCS.md` and in `freeze.py`'s finding, that demand-driven
discharge is bounded by the pack's own cut-out on purpose, and close the
question.
- **Protects:** the whole point of the product. Every watt the loop discharges is
self-consumption the house would otherwise have imported; a reserve is
literally energy bought at the import tariff and held back.
- **Costs:** on a heavy evening the pack ends at the BMS cut-out with no EMS-side
record of why. That is the SoC-drift condition **MAINT-01** exists to correct,
and the first symptom — a battery that is never available when it is wanted —
is indistinguishable from a coulomb counter that has drifted. It also means the
morning's peak-guard capacity is whatever last night left, which the peak guard
cannot influence.
- **Cost of building it:** zero. It is already the shipped behaviour, and after
SAFETY-25's honesty half it is already documented.
### Option B — a `hi` limit at `P_LOOP`, with an enforced ordering *(recommended)*
A new option `loop_soc_floor`. While `soc <= loop_soc_floor`, `main.py` files
`Claim.limit("reserve", P_LOOP, hi=0.0)`. Zero forbids **discharge** and permits
charging, which is the mirror image of the guard's `lo = 0` and one-directional
in the safe direction.
**⚠️ This shape has one trap and it is fatal if missed.** `arbiter.resolve()`
applies **every** limit at or above the winning `set` claim's priority and takes
the most restrictive, *with no notion of one limit outranking another* — that is
deliberate and is what makes the safety bounds unconditional. So when the loop
wins at `P_LOOP`, a reserve `hi = 0` and the peak guard's `lo = excess > 0` are
**both** applied, `lo > hi`, and the arbiter resolves a **CONTRADICTION to 0 W**:
the battery parked, in the one quarter of the month that sets the bill. This is
the same crossing-limits hazard `shaping_suspended()` already exists to avoid for
the maintenance charge-only clamp.
**The fix is an ordering constraint, and it is provable:** require
bms_soc_floor < loop_soc_floor <= peak_soc_floor
Then whenever the reserve binds (`soc <= loop_soc_floor <= peak_soc_floor`) the
guard is *already* floor-limited and files `lo = 0.0`, so `lo == hi == 0` and the
result is 0 W with no contradiction. Refuse any other ordering at startup, in
CFG-01's manner and with rule 8's message shape. **A `loop_soc_floor` above
`peak_soc_floor` must not be merely discouraged; it is the parked-battery bug.**
- **Protects:** the pack from routinely sitting on its own cut-out, which is the
MAINT-01 drift condition; and it gives the operator one number that means what
its name says.
- **Costs:** a fifth SoC key (see §4), a validator rule, and — the real cost —
**every watt below the reserve becomes billed import.** Set too high it turns a
working battery into a smaller one.
- **What it does *not* touch, correctly:** a maintenance DRAIN sets at
`P_MAINTENANCE` 60 and arbitrage sets at `P_ARBITRAGE` 30, both above `P_LOOP`
10, so a limit filed at `P_LOOP` is not applied to either. The monthly
recalibration still drains to `maintenance_soc_floor`; arbitrage is still
bounded by its own key. That is the right answer and it falls out of the
priorities rather than needing a special case.
- **Recommended starting value if this option is taken:** a *low* one — three
points above `bms_soc_floor`, i.e. **13 %**, well under `peak_soc_floor`'s 20.
The purpose is to keep the pack off its own cut-out, **not** to reserve energy
for anything, and an over-tight reserve is the version of this that fights
MAINT-01 from the other side: it shrinks the band the pack actually cycles in,
which is the condition a coulomb counter drifts in. It does not matter that 13
sits above `maintenance_soc_floor`'s 11 — the maintenance drain sets at
`P_MAINTENANCE` 60 and a `P_LOOP` limit is not applied to it, so the two never
interact. **The number itself is part of the owner's answer**; what this memo
offers is the derivation and the ordering constraint that makes any number in
that range safe.
### Option C — a `set` claim above `P_PEAK`
File `Claim.set("reserve", 55, 0.0)` when the pack is under the reserve. Because
clause 2 applies only limits at or **above** the winner's priority, the guard's
`lo` at 50 would then be dropped and there is no contradiction to engineer
around.
- **Protects:** the same as B, without the ordering rule.
- **Costs:** it is a **stop**, not a bound. It parks the battery outright rather
than merely forbidding discharge, so it also blocks the charging that would end
the condition, and it silently outranks peak shaving in a way that is invisible
on the priority table. This project's rule is that a floor about **energy** is
not a stop of last resort (`peakguard.py`, point 1). **Not recommended.**
### Option D — clamp inside `control.compute()`
- **Costs:** it puts precedence back inside a strategy, which is the exact thing
`arbiter.py` was built to end, and it would be invisible to `explain()`. **Not
recommended.**
## 6. Recommendation
⚠️ **This section is the recommendation that was PUT to the owner, kept as
written. It was answered on 2026-09-02 — see §0. The owner took Option A and
deferred Option B to `ALLOC-01`; item 3 below (keep the part 10 tripwire)
was taken as written and still stands.**
**Option A is honest and cheap; Option B is what I would build.** Concretely:
1. **Now (shipped with SAFETY-25):** the honesty half. `peak_soc_floor`, its
documentation and the status page say plainly that it bounds the peak guard
only. This is required under every option and it is the actual dishonesty on
the live system today.
2. **Owner's call:** A or B. If B, take it **after `SAFETY-27`'s naming decision**
so the fifth key lands into a scheme rather than onto a pile, and **after
`MAINT-01`** has run one real cycle — until then nobody has observed what this
pack's SoC reading does over a full cycle, and picking a reserve against a
reading that has never been recalibrated is picking a number against an
instrument we have not checked.
3. **Whichever way:** the tripwire in `test_peakguard.py` part 10 stays until the
question is answered, so the day someone builds a loop-side floor it goes red
and has to be updated deliberately, rather than the exposure quietly changing
under a green suite. It has two halves and they cover the two places the floor
can land:
- **10f pins the claim-source set.** Every `claims.append(...)` in
`Controller.cycle()` is read off its AST and must be one of eight named
sources, and real cycles — spied at main.py's own `resolve`, swept over the
whole 0–100 % SoC range in both the idle and the floor-limited state — must
file exactly those. **Option B is a ninth source**, and so is **Option C**'s
`set` claim, so filing either takes part 10 red on the line it is written.
**Option A** files no claim at all — it is the honesty half already
shipped, and part 10 is the record it leaves behind.
- **10a–10c replay the shipped code**, so **Option D** — a clamp inside
`control.compute()` — moves the replayed numbers instead.
⚠️ **10f is load-bearing and was added late.** PR #31 shipped this section
claiming the tripwire without it, and the reviewer disproved the claim by
building Option B in `main.py`: the entire suite, part 10 included, stayed
green, and mutation 13 went on printing *"nothing prevents it, on purpose"* on
a tree where something did. Do not remove 10f while this question is open.
## 7. What the replay is and is not
The committed captures carry **one** series — signed net power at the meter — so
the pack is modelled, and the model is stated rather than hidden:
- the captured `w` is the load presented to the meter; the modelled battery's
delivered power is subtracted from it, one telegram late (an actuation delay);
- the loop's command is the **shipped** `control.compute()` at the shipped
tuning, resolved through the **shipped** `arbiter.resolve()` against the
**shipped** `peakguard.claim()`, at a `cycle_floor_s` tick;
- SoC falls by the delivered discharge integrated over the real telegram
timestamps, on a pack of 300 Ah × 51.2 V × DoD 90;
- the BMS is modelled as a hard cut: at or below `bms_soc_floor` the modelled
battery delivers 0 W whatever is asked of it. Without that the run would be
unphysical — the BMS really does stop the pack, and the whole finding is that
it is then the **only** thing that does;
- nothing recharges the pack inside the window. One evening, one direction.
**The fixtures cannot express a low pack on their own** — there is no battery or
SoC telemetry in them — so the starting state of charge is a fixture parameter,
not a measurement. It is chosen as *one point above `peak_soc_floor`*, which is
derived from the shipped option rather than picked. Everything downstream of that
one number is the real capture and the real code.
+80 -4
View File
@@ -430,7 +430,7 @@ help - see "Why the tuning is what it is".
|---|---|
| `peak_forecast_entity` | Quarter-hour demand forecast, for capacity-tariff markets. Empty = no cap |
| `peak_cap_w` | The site's capacity-tariff target |
| `peak_soc_floor` (20) | **The percent below which the capacity-peak guard will not discharge the battery.** Not optional and not the same thing as `maintenance_soc_floor` — see below |
| `peak_soc_floor` (20) | **The percent below which the capacity-peak guard will not discharge the battery.** ⚠️ It bounds **the peak guard only** — it is **not a pack-wide reserve**, and ordinary self-consumption discharges straight past it (SAFETY-25, see below). Not optional and not the same thing as `maintenance_soc_floor` |
| `bms_soc_floor` (10) | The pack's **own** cut-out percent, the number the BMS enforces whatever you set above. `peak_soc_floor` must be **strictly above** it or the add-on refuses to start |
| `price_now_entity`, `price_avg_entity` | Dynamic tariff. Empty = never force a paid grid top-up |
@@ -552,8 +552,13 @@ exactly like the SoC drift the monthly maintenance cycle exists to correct.
- **`peak_soc_floor` (20 %)** is where the forced discharge stops. Below it the
guard files a **0 W** floor instead of a sized one: charging stays blocked
(that can only ever lower your offtake), and no further discharge is asked for.
- **It does not stop the ordinary self-consumption loop.** That loop still has no
SoC guard of its own. This bounds what the *peak guard* spends for money.
- **⚠️ IT BOUNDS THE PEAK GUARD ONLY. IT IS NOT A PACK-WIDE RESERVE, AND THE NAME
READS LIKE ONE.** The ordinary self-consumption loop — the grid-following
control law that holds your meter at zero — has **no SoC floor of any kind**.
It will discharge straight past this number and keep going until the pack's own
BMS cut-out stops it. What you are promised by `peak_soc_floor: 20` is *"the
capacity-peak guard will not spend the pack for money below 20 %"*, and
**nothing more**. See below for what that costs on a real evening.
- **When it binds you are told**, once per episode, with notification
`goodwe_peak_soc_floor` and a status-page row reading `PEAK GUARD
FLOOR-LIMITED`: the quarter **will** go over the ceiling, so shedding load is
@@ -572,6 +577,59 @@ Why 20 %: the reference pack is 13.8 kWh usable, so 10 points of margin over the
BMS cut-out is about 1.6× the guard's worst measured day. If your pack is
smaller, or your quarters are worse, raise it.
#### ⚠️ What `peak_soc_floor` does **not** protect (SAFETY-25)
**On a sustained-load evening this add-on will take your battery to the BMS
cut-out, whatever `peak_soc_floor` says.** That is measured, not argued. Replayed
on the committed 2026-08-20 capture, 19:00–22:00 UTC — three hours of house load
after the sun has gone, 830 W average, not one watt of export in the window — with
the 13.8 kWh reference pack started at 21 %, one point above the shipped floor:
| | |
|---|---|
| pack at the start of the evening | **21 %** (one point above `peak_soc_floor`) |
| pack three hours later | **10.0 %** — the `bms_soc_floor` cut-out |
| energy the loop took out | **1525 Wh** |
| control cycles below `peak_soc_floor` | **549 of 587**, and **343** of those still delivering discharge |
| cycles on which the peak guard filed *any* floor | **0** |
| same replay at `peak_soc_floor` = 5, 11, 20, 60 | **the same 10.0 %, to four decimal places** |
That last row is the point: **this is a property of the control law, not a value
you can configure.** Raising `peak_soc_floor` to 60 % changes nothing at all,
because the guard it bounds is not the thing doing the discharging.
**And the two can happen in the same cycle.** On the high-load block of the same
day (15:00–17:00 UTC) with the pack below the floor, the guard reports
`PEAK GUARD FLOOR-LIMITED` — *"commanding no forced discharge"* — on 49 cycles,
and on **all 49 of them** the loop is simultaneously being granted a discharge of
up to 2000 W by the arbiter. The status page is telling you the truth about the
guard while the battery empties.
**Why it is built this way, and why SAFETY-24 could not fix it.** The peak guard
files a `lo` limit — a *lower* bound on the setpoint. That asymmetry is exactly
what makes the guard safe: it is provably incapable of lowering a target, capping
a discharge or contradicting the arbiter. The same property makes it incapable of
stopping a discharge the loop itself wants. A floor on the guard cannot become a
floor on the pack by being raised.
**Is this a runaway?** No. Self-consumption discharge is demand-driven and
self-limiting: it stops when the house stops drawing, and every watt of it is
serving load you would otherwise have imported. It is not SAFETY-18's frozen-meter
rail. What it means is that the *depth* your pack reaches on a heavy evening is
set by your house, not by any number in this file, and the BMS is the only thing
underneath it.
**This is now a recorded decision, not an open question.** On **2026-09-02** the
product owner took **Option A**: the BMS cut-out is **deliberately** the only
backstop for demand-driven discharge, and a loop-side reserve floor is
**deferred** rather than rejected. The options, their costs, the measured replay
and the reasoning are in
[`DECISIONS/SAFETY-25-loop-soc-floor.md`](DECISIONS/SAFETY-25-loop-soc-floor.md),
together with the revisit trigger (`ALLOC-01`, the host-side share allocator)
under which a reserve becomes safe to build. **Nothing about the behaviour above
changed** — Option A is what has always shipped. What changed is that this
section now describes a choice somebody made, and you can read why.
### The winding-loop alarm (the output clamp)
Every setpoint this add-on writes is clamped to `max_w` before it leaves the
@@ -640,7 +698,18 @@ The add-on alarms when **both** of these are true at once:
- the meter's own document (power figure *and* both kWh registers) has not
changed for `meter_freeze_s` — 300 s by default; **and**
- the command standing on the wire is at the rail, within 5 % of `max_w`.
- the command standing on the wire is at the rail, within 5 % of the ceiling
the command can actually reach.
**That ceiling is `min(max_w, the setpoint device's own rating)`, not `max_w`.**
The emitted command is clipped to the device's reported range as well as to
`max_w`, so on a 4700 W inverter configured with `max_w: 5000` a rail measured
at 4750 W is one the command can never stand at — the guard could not fire, and
the status page said `armed` anyway. It now measures the rail against the
smaller number and the page names it, saying *"below max_w because …"* when the
device is what capped it. (On an install that started, the two are equal: a
`max_w` above the device rating is refused at startup. This matters when the
rating could not be read at boot — see below.)
Neither half is usable alone. A bare "unchanged for N seconds" rule false-trips
at the exact operating point this controller aims for — at a converged −10 W a
@@ -666,6 +735,13 @@ that reads the meter's own document; on `ha_dsmr`, `mqtt_p1`, `ha_signed` and
`off` there is no signal to threshold and the status page says **NOT COVERED**
rather than pretending the guard is armed.
The same row appears for a second reason: a setpoint device that reports a range
from which no command magnitude is available in both directions leaves no rail
to measure at all, and a 0 W rail would be satisfied by *every* command. That is
reported as **NOT COVERED** too, and the detector stays silent rather than
degenerating into the bare "unchanged for N seconds" rule this design exists to
avoid.
| option | default | meaning |
|---|---|---|
| `meter_freeze_s` | 300 | Seconds of an unchanged measurement, *while the command is at the rail*, before the alarm |
+184
View File
@@ -0,0 +1,184 @@
# Mutation runs in this repository — and the one way they lie
Nearly every safety claim in this add-on was established the same way: change
the shipped module, run the suites, watch one go **red**, put the module back,
watch it go **green**. There is no coverage tool here and there is not meant to
be — the check that matters is whether a *check* notices when the behaviour it
names is removed.
That method has exactly one silent failure mode, and TEST-15 exists because we
walked into it.
## The defect
FCST-03's developer reverted `self.provisional` to `here.provisional`, re-ran,
and reported the mutation as a **survivor**. It was not. CPython decides a
cached `.pyc` is still valid from two numbers:
* the source file's **size in bytes**, and
* the source file's **mtime truncated to whole seconds**.
`self` and `here` are the same length, and the revert happened in the same
second as the edit. Neither number moved, so the interpreter loaded the
bytecode it already had. Confirmed at the time by disassembly: **the source read
`here`, the running code loaded `self`.** The suite had graded code that was not
there — no error, no warning, exit status 0.
The same collision, in the other direction, can leave a **red** standing on
correct source after a revert that never took.
### Which way it lies, and why that scopes everything
A mutation that never took effect leaves the suite **green**, and a green run of
a mutated tree is reported as a survivor. So stale bytecode **manufactures
survivors**; it cannot manufacture a red. The false-red case exists but
announces itself, because a developer chases a failure they cannot explain.
Two consequences, and both are used below:
* a recorded **"all red, no survivors"** result is not at risk from this defect;
* a recorded **survivor** — and a recorded *zero*, such as a coverage-audit
count of 0 — is exactly what this defect produces.
`test_control.py`'s coverage-audit table says the same thing in its own terms:
the error is one-directional, so every figure there is a lower bound at worst.
## The rule
**Purge `__pycache__` before every mutation run.** Not afterwards, not usually,
not when the edit looks big enough.
```sh
cd goodwe_controller
tools/mutation_run.sh # every test_*.py in this directory
tools/mutation_run.sh . test_tariff.py # or just the ones you are watching
tools/mutation_run.sh "$GOODWE_ADDON_REPO/goodwe_controller" # from elsewhere
```
The harness purges, prints a `sha256`/byte-count fingerprint of every `app/*.py`
it is about to grade, runs each suite under `python3 -B`, and fails if a cache
appeared during the run. Diff two fingerprints and the file you mutated is the
line that changed — which is also how a mutation report proves *which source*
produced it.
### What does **not** fix this
| | writes bytecode | reads a stale `.pyc` |
|---|---|---|
| `python3 -B` | no | **yes** |
| `PYTHONDONTWRITEBYTECODE=1` | no | **yes** |
| purging `__pycache__` | (unchanged) | **no — nothing to read** |
Both flags are *write-side only*. A mutation run always has a cache already,
because the previous run wrote it, so a harness that only adds `-B` closes
nothing. This is measured, not read off documentation: `test_bytecode.py`
part 2 arranges the collision and shows both flags still running the old code.
`-B` is still worth passing — it stops **this** run leaving a cache for the
**next** edit to inherit, which is the one nobody is thinking about three
mutations into a batch. Purge for this run, `-B` for the next one.
### And not a `sleep`
One-second mtime resolution is the *mechanism*, not the enemy. Waiting out the
clock would slow every run down, and would still only cover the edit somebody
remembered to slow down. Stop trusting mtime instead.
## Reporting a mutation
State the things a reviewer cannot reconstruct afterwards:
1. **the byte delta** of the mutated file (`+5 B`, `+0 B`). `+0 B` is the risky
one — say so;
2. **that the mutated line was on disk** when the run started (the harness
fingerprint, or a `grep` of the line);
3. **which suite went red, and on which named check** — "the suite is red" and
"the check that watches this is red" are different claims;
4. for a **survivor**, that the run was purged. An unpurged survivor is not a
result.
## The other thing a mutation sweep cannot see: masking (TEST-16)
Stale bytecode is not the only way a survivor lies. **Two guards can mask each
other**, and a sweep that mutates one line at a time is structurally blind to it.
TEST-16 is the worked example. `static_tariff.arbitrage()` refuses a
one-firm-hour series at `len(firm) < 2`, and refuses a flat series at
`spread == 0.0`. A single firm hour *also* has a spread of zero. So:
* weaken the firm-pair rung alone → the flat rung refuses the stimulus anyway;
* weaken the flat rung alone → the tiny-spread stimulus is still refused, just
for the wrong reason;
* and the suite, grading `kind == "refused"`, reports **nothing either way**.
Both rungs could then be weakened *together* and still nothing would report —
which is precisely the state in which the next edit to either one opens a real
hole. It survived four rounds of review on TARIFF-03 and FCST-03.
Two rules come out of it, and both are cheap:
1. **Grade the reason, not just the verdict.** "Refused" and "refused for the
right reason" are different claims, and a masked rung is the case where the
first is true and the second is false. A refusal sentence is what the
operator reads; it is also the only observable that moves when one rung
quietly absorbs another's work.
2. **When two rungs can answer the same stimulus, mutate them together.** One
extra run per suspected pair. If a sweep finds two survivors in the same
function, that pair is the first thing to try — TEST-16's two survivors were
adjacent lines in one function and neither was individually live.
## Where each surface stands
* **Local and dev-harness runs — the exposed one.** This is where FCST-03 hit
it. `goodwe_controller/__pycache__` and `app/__pycache__` are gitignored and
are sitting in most working trees right now. Use the harness.
* **CI — structurally immune, and it was before this card.** `.gitea/workflows/
checks.yml` bind mounts the checkout `-v "$WS:/w:ro"`, so the interpreter
cannot write a `__pycache__` into the tree under test at all; measured for
TEST-15, and it fails *silently* — no error, exit status 0. Each job also
`rm -rf`s its workspace and clones afresh, so nothing crosses between jobs on
the shared runner. `PYTHONDONTWRITEBYTECODE=1` is now set there too, as belt
and braces: the `:ro` is one character wide and the next person debugging a
write will be tempted by it.
* **The shipped add-on — not affected, and this is closed.**
`goodwe_controller/Dockerfile` has carried `PYTHONDONTWRITEBYTECODE=1` since
it was written. There is no deploy-side finding here; do not re-open it.
* **The infra repo's `sim/` harnesses — exposed, and NOT fixed by this card.**
`sim/replay_sign.py` and friends import the add-on out of
`$GOODWE_ADDON_REPO` and write `__pycache__` into *both* trees
(`goodwe/sim/__pycache__` exists today). SAFETY-02's headline validation is a
replay, not a suite, so a mutation graded through it carries the same
exposure. `tools/mutation_run.sh` takes the tree to purge as its first
argument precisely so that repo can call it, but the change belongs in that
repo and some of those harnesses want the rig. **Anyone mutating a module
graded by a replay must purge both trees by hand until then.**
## Survey — mutation claims of 2026-08-25 … 2026-09-01
Scoped **by the property, not by re-running everything**. A claim is at risk
only if a mutation could have preserved the file's byte count *and* been
reverted inside the same second, *and* the claim is of the kind stale bytecode
can fabricate (see "which way it lies"). Sources: `git log release/1.0` and the
commit and PR bodies.
| claim | verdict | why |
|---|---|---|
| **FCST-03** M9 `self.provisional`→`here.provisional` (dd40c56, 71cd784) | **re-verified** | this is the original false survivor. Re-run with the cache cleared, M9 is caught. The shipped source was correct throughout. |
| **FCST-03** X1, X6 degenerate stimuli (71cd784) | **not at risk** | run after the purge discipline landed in that branch. |
| **SAFETY-24** 11 author + 9 reviewer mutations (e709554, 4601682) | **not at risk** | the commit records them run under `python -B` with a purged `__pycache__` and real byte deltas. Its one survivor is an equivalent mutant, argued structurally rather than by a green run. |
| **SAFETY-26** tolerance sweep over `arbitrage.py` and `static_tariff.py`, 2 survivors (2b8b8cb) | **not at risk** | purge, printed `+5 B` delta, mutated line asserted present, tree re-read before each run. One survivor is explicitly recorded at `+0 B` — the risky delta — and was produced *under* the purge. **Both survivors are now closed by TEST-16** (`test_static_tariff.py` section 9), which also found that the two of them *masked each other* — each was individually non-live only because the other rung caught its stimulus, an arrangement single-mutation testing cannot see. Its own ledger is 7 mutations, 4 of them at `+0 B`, all red. |
| **OPT-04** mutations reported on PR #22 (bdd7f18) | **not at risk** | `test_arbitrage.py`'s header records the exact command: purge, then `python3 -B`. |
| **TEST-17** `checks()` dropping `when` (504e8da) | **not at risk** | a *red* claim, and dropping an argument changes the file length. Neither half of the collision is available. |
| **SAFETY-07** wiring mutations B1/B2/B3 and `test_peakguard.py` parts 7 and 10 (2d570d8, e7c95bf) | **not at risk** | those mutations are **executed in-process**, monkeypatched onto the imported module. No source file is edited, so no `.pyc` is consulted. |
| every **"all red, no survivors"** claim in the window — TARIFF-02 (24/0), TARIFF-03 (11), MAINT-04 (10), SAFETY-18 (6+4), SAFETY-03 (6), TEL-04 (10), TEL-05 (6) | **not at risk** | direction. Stale bytecode turns a red into a green survivor, never the reverse. A red is evidence that *something* changed under the check. |
| **TEST-06**'s deleted assertion, "no new notification while parked at 0 W" (c34b5a2) | **not at risk / superseded** | it was recorded as undecidable and then *falsified* — `test_freeze.py` records the one-line mutation that takes the file red 9 times. The stronger later claim is a red one. |
| **TARIFF-01** reviewer survivor: `record_block()` ignoring its `policy` argument (0dbd485) | **re-verified — still a survivor** | re-run here through `tools/mutation_run.sh` against the 15 suites that were on the record, all green with `billed_w(block, policy)` mutated to `billed_w(block, POLICY_NET)`. The recorded diagnosis holds: every block reaching the store is single-phase, where NET, SUM and MAX collapse. **Now CLOSED by TEST-13** (`test_tariff.py` section 7), which round-trips section 7's own unbalanced `(3000, 500, -200) W` block THROUGH the store under each policy - three distinct banked figures, so a hardcoded policy takes at least two of them red. Third instance of "a stimulus evaluated where the quantity it grades is degenerate", after WITNESS-02's span normalisation and TARIFF-01's own DST window. |
| **SAFETY-25** 8 mutations against `test_peakguard.py` part 10, then 9 more after review, all red | **not at risk** | each run against a tree copied fresh with `__pycache__` excluded and mounted `:ro`, so no `.pyc` existed to go stale - the same structural immunity recorded for CI above. Byte deltas recorded on the PR; none is `+0 B`. All are **reds**, which is the direction this defect cannot fabricate. ⚠️ The second round exists because the first round's mutations were all aimed at DISARMING the guard, and the claim part 10 actually made was about the guard being FIXED - the reviewer built the fix and the suite stayed green. Bytecode was never the issue there; an unaimed battery was. |
| **SAFETY-03** reviewer survivor: `abs()` dropped from `clamp_to_rating`'s limit (6aabb83) | **re-verified — still a survivor** | re-run the same way, all 15 green. Also as recorded: unreachable under the `int(100, 5000)` schema. |
| **TARIFF-01**'s other three survivors, **SAFETY-03**'s `describe()` survivor, **TARIFF-02**'s M3/M5/M7, **SAFETY-18**'s three | **still unverified** | recorded before the purge discipline, with no byte delta on the record, so a `+0 B` same-second revert cannot be excluded. All are survivors, which is the direction this defect fabricates. TARIFF-02's and SAFETY-18's were **closed by later commits whose claims are reds**, so what is unverified is the *diagnosis*, not the current state of the code. |
**Nothing here says a past result is wrong.** The two survivors re-run above
both stood. What changed is that they are now on the record as measured rather
than assumed, and the rest are labelled honestly. The still-unverified rows are
cheap to close — one harness run each — and the right moment is when somebody
next touches that module, not in a re-run campaign nobody will read.
+12 -2
View File
@@ -46,8 +46,18 @@ the validation did not run or no longer holds - `hass.limits()` returns
(None, None) whenever ESPHome is not up yet, and the range checks are skipped
rather than guessed at - and that is a louder fault than the first stage, not a
quieter one. It therefore alarms too, through the same channel, with the bound
named. This is NOT SAFETY-20; nothing here changes what `freeze.py` measures its
rail against.
named.
⚠️ SAFETY-20 UPDATED THE SECOND HALF OF THAT SENTENCE. It used to read "this is
NOT SAFETY-20; nothing here changes what `freeze.py` measures its rail against",
and that was true of this module and false of the system: this stage is exactly
what clips the emitted command below `RAIL_FRAC * max_w`, which is how a device
rating disarmed the freeze detector while the page said `armed`. `freeze.py` now
takes `dev_min`/`dev_max` and measures its rail against
`min(max_w, |dev_min|, |dev_max|)`. THE CLAMP ITSELF IS UNCHANGED - it still
clamps to `max_w` first and to the device range second, for the reasons above,
and it still does not `min()` the two. What changed is only that the detector
downstream now knows this stage exists.
------------------------------------------------------------------------------
WHERE THE WIND ACTUALLY SHOWS UP - READ THIS BEFORE "SIMPLIFYING" THE CALLER
+181 -15
View File
@@ -18,6 +18,17 @@ THE FAILURE NEEDS NO FAULT ANYWHERE ELSE. A frozen-but-talking meter is
- there is no SoC guard on the grid-following loop at all. `soc_floor` belongs
to the maintenance cycle; the BMS is the sole energy backstop.
⚠️ STILL TRUE, AND NOW FILED. SAFETY-24 added `peak_soc_floor` and
OPT-04 added `arbitrage_soc_floor`, so the sentence above is no longer
"there is one SoC floor and it is maintenance's" - but neither of the new
ones binds THIS loop, and `peak_soc_floor`'s name reads as though it does.
SAFETY-25 replayed the exposure (test_peakguard.py part 10) and recorded
the options in DECISIONS/SAFETY-25-loop-soc-floor.md. DECIDED 2026-09-02,
Option A: the BMS is the sole energy backstop for demand-driven discharge
ON PURPOSE. A loop-side reserve is DEFERRED, not rejected - its revisit
trigger is ALLOC-01. So the sentence above is a recorded decision, not an
oversight and no longer an open question.
The loop reads a constant error and integrates it. Time from freeze to the rail,
replaying the real `control.compute()` at 15 s cycles:
@@ -151,12 +162,77 @@ THE RAIL TERM, PRECISELY
reason SAFETY-02 uses the emitted value: the wire carries the emitted number.
RAIL_FRAC is 0.95 and is a constant rather than an option. The command is
quantised to `step_w` (max 100) and clamped to `max_w` (min 100), so at the rail
the emitted value IS `max_w` on every schema-legal combination; the 5 % is slack
for a device rating that clips `max_w` slightly in `write_setpoint()`, not a
tuning knob. Making it configurable would offer a way to widen the one term that
quantised to `step_w` (max 100), so at the rail the emitted value IS the ceiling
on every schema-legal combination; the 5 % is quantisation slack, not a tuning
knob. Making it configurable would offer a way to widen the one term that
carries the whole no-false-positive argument.
⚠️ SAFETY-20 - AND THE CEILING IS NOT `max_w`. THE 5 % USED TO BE DESCRIBED AS
"slack for a device rating that clips `max_w` slightly in `write_setpoint()`",
AND THAT SENTENCE WAS THE BUG. 5 % of slack does not absorb a device rating; it
inverts the guard. `write_setpoint()` clamps the emitted command to `max_w` AND
THEN to the setpoint device's own `[dev_min, dev_max]` range (clamp.py,
`clamp_to_rating()`), and the arbiter files the same range as a P_SAFETY limit
claim, so the largest magnitude that can ever stand on the wire is
min(max_w, |dev_min|, |dev_max|)
not `max_w`. Measured on the shipped predicate at `max_w: 5000` against a device
of +-4700 - the exact case the ticket is named for:
looks_frozen(unchanged_s=3600, commanded_w=4700, max_w=5000) -> False
The command is pinned at the hardware's rail, the meter has been frozen for an
hour, and term 2 is unsatisfiable BY CONSTRUCTION because 4700 < 4750. Any
device rating at or below `RAIL_FRAC * max_w` disarms the conjunction outright.
The status page then printed `armed (...command is over 4750 W)`, which is the
"disarmed guard that advertises itself as armed" failure validate.py rule 5 and
SAFETY-15/19 all exist to prevent - so `rail_ceiling_w()` below takes the device
range and the rail is measured against the smaller number.
WHY THE SMALLER OF THE TWO DEVICE BOUNDS, AND NOT A SIDE-AWARE PAIR. The rail is
a MAGNITUDE test against what clamp.py calls a magnitude clamp - it binds import
and export identically - so the ceiling here is a magnitude that is available in
BOTH directions. The alternative considered was a per-sign rail:
`min(max_w, dev_max)` for a positive command, `min(max_w, |dev_min|)` for a
negative one. That is arithmetically tighter and it is NOT wrong - on a device
range of -500..+5000 it would grade a -480 W charge command as railed, which the
symmetric ceiling reaches only by dropping the discharge rail to 475 W too. It
was rejected on cost, not on correctness: a per-sign rail is two rails, and two
rails need two coverage verdicts (`dev_min == 0` is a degenerate charge rail
whatever the discharge side can do) on a status row that carries one number and
in a predicate that takes one magnitude. That is a bigger change than this
defect earns, and the ONLY configuration that distinguishes the two - a device
range narrower than `max_w` on one side - is refused at startup by CFG-01 (see
the reachability note below). Between the two, the symmetric ceiling can only
ever LOWER the rail, which widens term 2 rather than disarming it; term 1
(`unchanged_s >= hold_s`) is the term carrying the no-false-positive argument,
and it is untouched. Whoever needs the tighter version should take both status
rows with it.
⚠️ AND WHEN THE CEILING IS ZERO THE RAIL IS NOT "LOW", IT IS GONE. A device that
accepts no command in one direction at all (`dev_max == 0`, or `dev_min == 0`)
gives a ceiling of 0 W, and `abs(commanded_w) >= 0` is TRUE FOR EVERY COMMAND
INCLUDING 0 W. Term 2 would not be disarmed there, it would be degenerately
true, and the detector would collapse into the bare `unchanged_s > N` threshold
TEL-05 refused - false-tripping at the converged operating point we aim for.
That case is reported as NOT COVERED, through the row the unsupported-transport
case already uses, and `looks_frozen()` returns False rather than firing.
⚠️ HOW REACHABLE IS ANY OF THIS - READ THIS BEFORE "SIMPLIFYING" IT AWAY.
`validate_startup_config()` rule 2 (CFG-01) already REFUSES TO START on
`max_w > dev_max` or `-max_w < dev_min`, and `run_control()` re-runs that gate
once ESPHome is up and the real rating is known. So on any install that reaches
the control loop with a rating it could read, `min(max_w, |dev_min|, |dev_max|)`
IS `max_w` and everything above is arithmetically dead. That is not an argument
against it - it is clamp.py's argument for its own second stage, word for word:
the case where this bites is the case where the startup gate did not run or no
longer holds (`hass.limits()` returns (None, None) whenever ESPHome is not up,
and the range checks are then skipped rather than guessed at, so a rating that
arrives late is never re-read), and a guard that quietly assumes the gate ran is
a guard that reports armed in exactly the state it cannot fire in. See AC 4's
decision, recorded in validate.py under WHAT IS DELIBERATELY *NOT* REFUSED.
⚠️ NOT GATED ON `following`, and that is deliberate. A maintenance charge
commands against the meter on purpose and can sit at the rail for hours - but it
does so while pushing kilowatts through the meter, so the FIRST term is what
@@ -192,6 +268,8 @@ otherwise would be worse than the gap.
from dataclasses import dataclass
from datetime import datetime
from .clamp import is_commandable
# See "THE RAIL TERM, PRECISELY" above. A constant, on purpose.
RAIL_FRAC = 0.95
@@ -203,13 +281,72 @@ class FreezeWatchdogConfig:
hold_s: float = 300.0
def rail_w(max_w) -> float:
"""The magnitude at or above which a command counts as railed."""
return abs(float(max_w)) * RAIL_FRAC
def rail_ceiling_w(max_w, *, dev_min=None, dev_max=None) -> float:
"""The largest command magnitude that can actually stand on the wire.
SAFETY-20, and the whole point of the ticket: this is NOT `max_w`. The
emitted command is bounded by `max_w` AND by the setpoint device's own
`[dev_min, dev_max]` range - twice, in `clamp_to_rating()` and again as the
arbiter's `device` P_SAFETY limit claim - so the reachable ceiling is the
smallest of the three magnitudes. See "THE RAIL TERM, PRECISELY" for why it
is the smaller of the two device bounds rather than a per-sign pair, and for
why this is arithmetically dead on any install CFG-01 let start.
`dev_min` / `dev_max` are `hass.limits()`'s answer and are None whenever
ESPHome could not be reached. UNKNOWN IS NOT ZERO: a missing bound means
this add-on applies no device clamp at all on that side (clamp.py's second
stage is skipped unless BOTH are known), so an unknown bound must not lower
the ceiling. `is_commandable()` is write_setpoint()'s own predicate, reused
rather than retyped: a NaN rating must not become a 0 W ceiling.
Returns 0.0 when the device can command nothing - see rail_unreachable().
"""
ceiling = abs(float(max_w))
for bound in (dev_min, dev_max):
if is_commandable(bound):
ceiling = min(ceiling, abs(float(bound)))
return max(0.0, ceiling)
def rail_unreachable(max_w, *, dev_min=None, dev_max=None) -> str:
""""" when the rail is a real threshold, else WHY it is not. SAFETY-20 AC2.
The status page renders this as a NOT COVERED row - the same row, for the
same reason, that an unsupported transport already gets. It is a second
reason to use that surface, not a new mechanism: in both states the honest
report is "this guard is not watching", and the one thing this project has
decided repeatedly it will not ship is a page that says `armed` instead.
⚠️ THE UNREACHABLE CASE IS NOT "THE RAIL IS HIGH", IT IS "THE RAIL IS 0 W".
A ceiling of zero makes `abs(commanded_w) >= 0` true for every command
including a parked 0 W one, so term 2 is not disarmed but DEGENERATELY TRUE,
and the conjunction decays into the bare `unchanged_s > N` threshold TEL-05
refused - which false-trips at the converged operating point this controller
aims for. Silence plus a NOT COVERED row is strictly better than that.
"""
if not max_w or not is_commandable(max_w):
return (f"max_w is {max_w!r}, so there is no ceiling to measure a rail "
f"against")
if rail_ceiling_w(max_w, dev_min=dev_min, dev_max=dev_max) > 0.0:
return ""
return (f"the setpoint device reports a range of {dev_min}...{dev_max} W, "
f"which leaves no command magnitude available in both directions, "
f"so the rail term would be true of every command including 0 W")
def rail_w(max_w, *, dev_min=None, dev_max=None) -> float:
"""The magnitude at or above which a command counts as railed.
Measured against the REACHABLE ceiling, not against `max_w` - SAFETY-20.
Callers that do not know the device range pass none and get the old
behaviour, which is correct precisely when there is no device clamp to
account for.
"""
return rail_ceiling_w(max_w, dev_min=dev_min, dev_max=dev_max) * RAIL_FRAC
def looks_frozen(unchanged_s, commanded_w, max_w,
cfg: FreezeWatchdogConfig) -> bool:
cfg: FreezeWatchdogConfig, *, dev_min=None, dev_max=None) -> bool:
"""The predicate, and the ONLY place the conjunction is written down.
Public for the same reason `watchdog.disagrees()` is: the checks that grade
@@ -220,12 +357,28 @@ def looks_frozen(unchanged_s, commanded_w, max_w,
`unchanged_s` seconds since the meter served a different measurement, or
None on a transport that cannot know (see the module note).
`commanded_w` the EMITTED setpoint standing on the wire.
`max_w` the configured output bound the rail is measured against.
`max_w` the configured output bound.
`dev_min` / the setpoint device's own reported range, or None when it
`dev_max` could not be read. SAFETY-20: the rail is measured against
`min(max_w, |dev_min|, |dev_max|)`, because that - not
`max_w` - is what the wire can carry.
⚠️ THE DEVICE BOUNDS ARE KEYWORD-ONLY AND DEFAULT TO None, WHICH IS THE
CONSERVATIVE DIRECTION AND ALSO THE HONEST ONE. A caller that does not know
the rating gets a rail measured against `max_w` - correct, because when this
add-on has no rating it applies no device clamp either (clamp.py's second
stage needs both bounds), so `max_w` really is the ceiling on that path.
"""
if unchanged_s is None or commanded_w is None or not max_w:
return False
# SAFETY-20. A ceiling of 0 W would make term 2 true of EVERY command; that
# is the degenerate case, not the armed one. Silence, and the status page
# says NOT COVERED - see rail_unreachable().
if rail_unreachable(max_w, dev_min=dev_min, dev_max=dev_max):
return False
return (float(unchanged_s) >= cfg.hold_s
and abs(float(commanded_w)) >= rail_w(max_w))
and abs(float(commanded_w))
>= rail_w(max_w, dev_min=dev_min, dev_max=dev_max))
class FreezeWatchdog:
@@ -249,24 +402,37 @@ class FreezeWatchdog:
self.reason = ""
self.episodes = 0
def evaluate(self, unchanged_s, commanded_w, max_w, now: datetime) -> bool:
def evaluate(self, unchanged_s, commanded_w, max_w, now: datetime, *,
dev_min=None, dev_max=None) -> bool:
"""Advance one cycle. Returns True ONLY on the rising edge.
`now` is the caller's clock so this stays testable and replayable - the
same discipline as `SignWatchdog.evaluate()`.
same discipline as `SignWatchdog.evaluate()`. `dev_min`/`dev_max` are
the setpoint device's reported range; see looks_frozen().
"""
if not looks_frozen(unchanged_s, commanded_w, max_w, self.cfg):
if not looks_frozen(unchanged_s, commanded_w, max_w, self.cfg,
dev_min=dev_min, dev_max=dev_max):
self.active = False
self.since = None
self.reason = ""
return False
# ⚠️ SAFETY-20. THE REASON QUOTES THE CEILING IT ACTUALLY USED, not
# `max_w`. The old line said "at the 5000 W rail (... command over
# 4750 W)" on an install whose device stopped at 4700 W, i.e. it named
# a threshold the command could not reach - the same untruth the status
# page was telling, printed into the log and the HA notification where
# it would outlive the page.
ceiling = rail_ceiling_w(max_w, dev_min=dev_min, dev_max=dev_max)
capped = ("" if ceiling >= abs(float(max_w))
else f", capped from max_w {float(max_w):.0f} W by the "
f"setpoint device's own rating")
self.reason = (
f"METER_FROZEN: the meter has answered {float(unchanged_s):.0f} s "
f"without its measurement changing while the command stands at "
f"{float(commanded_w):+.0f} W, at the {float(max_w):.0f} W rail "
f"{float(commanded_w):+.0f} W, at the {ceiling:.0f} W rail{capped} "
f"(limits: unchanged over {self.cfg.hold_s:.0f} s, command over "
f"{rail_w(max_w):.0f} W)")
f"{rail_w(max_w, dev_min=dev_min, dev_max=dev_max):.0f} W)")
if self.active:
return False
self.active = True
+154 -28
View File
@@ -42,7 +42,7 @@ from .clamp import (
is_commandable,
)
from .freeze import (
FreezeWatchdog, FreezeWatchdogConfig, looks_frozen, rail_w,
FreezeWatchdog, FreezeWatchdogConfig, looks_frozen, rail_unreachable, rail_w,
)
from .hass import HomeAssistant
from .maintenance import IDLE, MaintConfig, Maintenance
@@ -131,19 +131,16 @@ class Controller:
integrator_max_w=(float(opts["integrator_max_w"])
if opts.get("integrator_max_w") else None),
)
self.maint = Maintenance(
MaintConfig(
enabled=bool(opts.get("maintenance_enabled", False)),
interval_days=int(opts.get("maintenance_interval_days", 28)),
start_hour=int(opts.get("maintenance_start_hour", 10)),
discharge_w=float(opts.get("maintenance_discharge_w", 2500)),
charge_w=float(opts.get("maintenance_charge_w", 2500)),
soc_floor=float(opts.get("maintenance_soc_floor", 11)),
soc_target=float(opts.get("maintenance_soc_target", 99)),
hold_min=int(opts.get("maintenance_hold_min", 120)),
),
store,
)
# ⚠️ CFG-03. EIGHT `opts.get(key, <literal>)` CALLS USED TO LIVE HERE,
# and two of those literals disagreed with config.yaml - 2500 against a
# shipped 2000, which is a config validate.py refuses. The read now
# belongs to `MaintConfig.from_options()`, next to the one in-code
# mirror of config.yaml it falls back to, so this file states no opinion
# at all about what a missing maintenance key means. Read
# maintenance.MAINT_OPTION_DEFAULTS before adding a ninth key: it goes
# in config.yaml's `options:` and `schema:` blocks and in that dict, and
# nowhere else.
self.maint = Maintenance(MaintConfig.from_options(opts), store)
# SAFETY-02. One instance, one actuator, one cadence - see watchdog.py.
#
@@ -240,10 +237,14 @@ class Controller:
# knows, and refusing one set below the pack's own cut-out means knowing
# that cut-out too. So this card adds exactly two keys and reads their
# defaults from `peakguard.PEAK_OPTION_DEFAULTS` - TARIFF-02's mirror
# pattern - rather than typing literals here. THAT is what keeps CFG-03
# at three places: the divergence validate.py's rule 6 documents
# (`maintenance_charge_w` 2000 there, 2500 here) is exactly what a
# literal in this file would repeat.
# pattern - rather than typing literals here. THAT is what kept this
# card from widening: the divergence validate.py's rule 6 used to
# document (`maintenance_charge_w` 2000 in config.yaml, 2500 in this
# file) is exactly what a literal here would have repeated. CFG-03 has
# since closed that one too - `maintenance.MAINT_OPTION_DEFAULTS`,
# read through `MaintConfig.from_options()` - so the rule now holds for
# every option family this file builds: no numeric fallback in main.py
# that config.yaml has not shipped.
self.peak_guard = None
self._peak_engaged = False
self._peak_saturated = False
@@ -557,8 +558,14 @@ class Controller:
"peak_soc_floor",
peakguard.PEAK_OPTION_DEFAULTS["peak_soc_floor"])),
max_hold_s=self.p1.averager.max_hold_s,
# ⚠️ SAFETY-20. The device range goes in TOO, and this call site is
# the one that needed it most: `standing` is `last_write`, i.e. the
# value AFTER `clamp_to_rating()` applied `[dev_min, dev_max]`, so
# grading it against a rail derived from bare `max_w` compares a
# device-clipped number to a ceiling the device cannot reach.
frozen=looks_frozen(getattr(self.p1_source, "unchanged_s", None),
standing, max_w, self.freeze_wd.cfg),
standing, max_w, self.freeze_wd.cfg,
dev_min=self.dev_min, dev_max=self.dev_max),
)
peak_claim = (peakguard.claim(self.peak_guard)
if self.peak_guard is not None else None)
@@ -686,8 +693,16 @@ class Controller:
hi = 0.0
reason = "charge-only"
if self.cheap:
# ⚠️ CFG-03. `self.maint.cfg.charge_w`, NOT A SECOND READ
# OF `self.o`. This line used to re-open the options dict
# with its own literal fallback, so the rate the shaping
# asked for and the rate the state machine drained at could
# be different numbers from the same install - and, with the
# key absent, they were. The Controller already parsed this
# once in __init__; asking the object that owns it cannot
# drift from it.
floor = maintenance_charge_floor(
float(self.o.get("maintenance_charge_w", 2500)),
self.maint.cfg.charge_w,
self.peak_fc, float(self.o.get("peak_cap_w", 3500)))
if floor > 0:
hi, reason = -floor, "cheap-window charge"
@@ -776,6 +791,12 @@ class Controller:
# `self.target`, which is assigned further up - see check_output_clamp()
# and check_meter_frozen() for each. Two guards, two orderings, adjacent
# lines: do not "tidy" them into one rule.
#
# Moving it BELOW the other guards is harmless - nothing between here and
# the end of cycle() writes `self.clamp_last`. Moving it above the write
# is not, and test_clamp.py part 6 fails on exactly that: it grades the
# evidence, not the line number, so a rename or a move into a helper that
# still runs after the write keeps it green. (TEST-11.)
await self.check_output_clamp()
# --- SAFETY-18, and its boundary is the ASSIGNMENT --------------------
@@ -979,6 +1000,16 @@ class Controller:
They cannot both be true: peakguard.decide()'s floor-limited branch
returns before the `achievable_w` clamp that sets `saturated`.
⚠️ SAFETY-25 - AND THE MESSAGE SAYS WHAT THE FLOOR IS NOT. Read on its
own, "the capacity-peak guard has run out of battery" invites exactly
one wrong inference: that the pack is now being held at
`peak_soc_floor`. It is not. `peak_soc_floor` bounds THIS GUARD only;
the grid-following loop has no SoC floor at all and, on the committed
2026-08-20 replay, is being granted discharge in EVERY cycle that raises
this notification. An operator who reads the alarm and relaxes because
"the EMS has a 20 % reserve" has been misled by us, so the alarm carries
the correction itself rather than leaving it to DOCS.md.
Edge-triggered, and de-asserting arms it again - FreezeWatchdog's shape,
for FreezeWatchdog's reason: one notification per episode, not one per
cycle for a quarter of an hour.
@@ -1004,6 +1035,13 @@ class Controller:
# energy floor is not a saturated inverter and is not a frozen meter,
# and an operator who has to dismiss three identical-looking cards
# learns to dismiss the one that mattered.
# ⚠️ SAFETY-25's sentence must render on the unreadable-SoC branch too,
# where `soc_floor` is a number but naming it would invite the reader to
# think the pack is AT it. `decide()` guards its own reason string the
# same way; a f-string that formats a None here would turn the one
# notification that matters into a traceback.
_at_floor = ("at the floor" if g.soc_floor is None
else f"at {float(g.soc_floor):.0f} %")
await self.hass.call("persistent_notification", "create", {
"notification_id": "goodwe_peak_soc_floor",
"title": "GoodWe: the capacity-peak guard has run out of battery",
@@ -1017,7 +1055,13 @@ class Controller:
f"deliberately above the pack's own BMS cut-out. Charging stays "
f"blocked. Shedding load is the only thing that changes the bill "
f"now; if this pack can afford a deeper discharge, lower "
f"peak_soc_floor."),
f"peak_soc_floor.\n\nSAFETY-25 - WHAT THIS FLOOR IS NOT: "
f"peak_soc_floor bounds THE PEAK GUARD ONLY. It is not a "
f"pack-wide reserve, and the battery is NOT being held "
f"{_at_floor} - ordinary self-consumption has no SoC "
f"floor at all and will go on discharging past it, down to the "
f"pack's own BMS cut-out. What has stopped is the guard buying "
f"you a lower bill, not the pack being spent."),
})
async def check_meter_frozen(self) -> None:
@@ -1035,7 +1079,9 @@ class Controller:
unchanged = getattr(self.p1_source, "unchanged_s", None)
fired = self.freeze_wd.evaluate(unchanged, self.target,
float(self.o.get("max_w", 2000)),
datetime.now(timezone.utc))
datetime.now(timezone.utc),
dev_min=self.dev_min,
dev_max=self.dev_max)
if not fired:
return
self.log_event("METER FROZEN? " + self.freeze_wd.reason)
@@ -1270,7 +1316,20 @@ class Controller:
self.mqtt.close()
# -- UI ------------------------------------------------------------------
def checks(self) -> list:
def checks(self, when: datetime | None = None) -> list:
"""The status rows. `when` is the reference time for anything billed by
the calendar - today's month when it is None, which is what the live
page means; `status_payload()` calls this with no argument.
⚠️ IT EXISTS SO THE PEAK ROW CAN BE GRADED (TEST-17). Every other peak
query already takes it - `PeakStore.peak()`, `PeakTracker.peak()`,
`headroom_w()`, `warning_frac()` - and the row built from them was the
one thing that could only be read against `datetime.now()`. A suite
that banks an August quarter then asks this page what the peak is goes
green in August and red in September, which is what happened at 00:00
on 2026-09-01: TARIFF-01's own section 10, red on a calendar boundary,
on a commit nobody had touched for a day.
"""
o = self.o
out = []
if self.p1_enabled:
@@ -1319,26 +1378,60 @@ class Controller:
f"meter_source {o.get('meter_source')} - only "
f"homewizard_local sees whether the meter's own "
f"document changes"})
elif rail_unreachable(o.get("max_w", 2000),
dev_min=self.dev_min, dev_max=self.dev_max):
# SAFETY-20, and THE SECOND REASON TO USE THIS ROW RATHER THAN A
# NEW MECHANISM. The transport case above and this one are the
# same statement - "the conjunction cannot be evaluated here" -
# and an operator does not need to learn two vocabularies for
# it. What differs is only which term is missing: there,
# `unchanged_s`; here, a rail the command could ever stand at.
out.append({"ok": False, "warn": True,
"text": f"freeze detector: NOT COVERED - "
+ rail_unreachable(
o.get("max_w", 2000),
dev_min=self.dev_min,
dev_max=self.dev_max)})
else:
# ⚠️ SAFETY-20. THE RAIL PRINTED HERE IS THE RAIL THE PREDICATE
# USES, device range included. This row used to interpolate
# `rail_w(max_w)` while `looks_frozen()` graded a command the
# device had already clipped below it, so on any install whose
# inverter is smaller than its configured ceiling the page named
# a number the command could never reach and called it `armed`.
# Both the row and the predicate now read the same three inputs.
_rail = rail_w(o.get("max_w", 2000),
dev_min=self.dev_min, dev_max=self.dev_max)
# And when the device is what set that number, SAY SO - the
# operator configured `max_w` and is owed the reason the guard
# is armed somewhere else.
# ⚠️ Either bound may be None on its own - `hass.limits()`
# reads `min` and `max` independently and returns None for
# whichever attribute is missing or unparseable - so this
# renders whatever is there rather than formatting a None.
_cap = ("" if _rail >= rail_w(o.get("max_w", 2000))
else f" - below max_w because "
f"{o.get('setpoint_entity') or 'the setpoint device'}"
f" accepts only {self.dev_min}...{self.dev_max} W")
out.append({"ok": True, "warn": False,
"text": f"freeze detector: armed (alerts after "
f"{self.freeze_wd.cfg.hold_s:.0f} s unchanged "
f"while the command is over "
f"{rail_w(self.o.get('max_w', 2000)):.0f} W)"})
f"{_rail:.0f} W{_cap})"})
# TARIFF-01. The month's billed peak, and - the load-bearing half -
# a DIFFERENT row when the store could not answer. "no peak yet" is
# a normal state on the 1st; "unreadable" is a broken instrument, and
# a status page that spelled them the same way would let a 0 W read
# look like a quiet month right up until SAFETY-07 shaved nothing.
_pk = self.peak.peak()
_pk = self.peak.peak(when)
if _pk.is_unreadable:
out.append({"ok": False, "warn": True,
"text": "capacity-tariff peak: " + _pk.explain()})
else:
# §9.1's "warning entity at 80 %", as a status row rather than
# a second entity - see the constructor on not doubling up.
_frac = self.peak.warning_frac() or 0.0
_frac = self.peak.warning_frac(when) or 0.0
_ok = _frac < 0.8
out.append({"ok": _ok, "warn": not _ok,
"text": _pk.explain()
@@ -1366,8 +1459,35 @@ class Controller:
# is going to be spent and a human is the only actuator left. A
# separate row from saturation because the two ask for opposite
# things - see check_peak_floor_limited().
#
# ⚠️ SAFETY-25. THE SCOPE SENTENCE IS PART OF THE ROW, NOT A
# DOCS FOOTNOTE. This is the one line an operator reads at the
# exact moment the guard stops discharging, and read alone it
# says "the battery is being held at peak_soc_floor" - which is
# false, and measurably so: on the committed evening replay the
# loop goes on discharging in EVERY cycle this row is showing.
# A floor that binds one consumer and not the other is worse
# than no floor if the page does not say which.
#
# ⚠️ AND IT CARRIES ITS OWN `banner`. status_payload() renders
# the FIRST not-ok/not-warn row as the page's headline, so
# without this the loudest element on the page would be a
# 550-character paragraph that the row three lines below
# repeats verbatim. The banner is the short form; the row keeps
# the whole sentence, because the row is where an operator
# reads what the floor does and does not bound. Shortening the
# ROW instead would be weakening AC 3.
out.append({"ok": False, "warn": False,
"text": _pg.explain()})
"banner": _pg.explain()
+ " - and peak_soc_floor bounds THE PEAK "
"GUARD ONLY (SAFETY-25, see below)",
"text": _pg.explain()
+ ". NOTE: peak_soc_floor bounds THE PEAK "
"GUARD ONLY - it is not a pack-wide "
"reserve, and ordinary self-consumption "
"has no SoC floor, so the battery may "
"keep discharging below this level down "
"to the BMS cut-out (SAFETY-25)"})
elif _pg.blind:
out.append({"ok": False, "warn": True, "text": _pg.explain()})
else:
@@ -1473,7 +1593,13 @@ class Controller:
level, banner = "bad", ("FAILSAFE — the command opposed the meter. "
"Inverter held at 0 W.")
elif bad:
level, banner = "bad", f"NOT READY — {bad[0]['text']}"
# ⚠️ `banner` IF THE ROW OFFERS ONE, `text` OTHERWISE. A row may
# need to say more to an operator reading the checks list than fits
# in the one line at the top of the page - SAFETY-25's floor-limited
# row is the case that forced this - and a headline that is a full
# paragraph, repeated verbatim by the row underneath it, is a
# headline nobody reads. Rows without the key are unaffected.
level, banner = "bad", f"NOT READY — {bad[0].get('banner') or bad[0]['text']}"
elif not self.auto:
level, banner = "warn", "Stopped — inverter commanded to 0 W"
elif self.maint.phase != IDLE:
+103 -8
View File
@@ -38,17 +38,112 @@ CHARGE_TIMEOUT_MIN = 2160
# After an abort, do not immediately re-trigger in the same start hour.
RESTART_COOLDOWN_MIN = 90
# ⚠️ CFG-03. THE ONE IN-CODE MIRROR OF config.yaml FOR EVERY `maintenance_*`
# OPTION, and the only place in the add-on where one of these numbers is typed.
#
# WHAT WENT WRONG WITHOUT IT. Until this card each default was written down
# three times - config.yaml's `options:` block, an `opts.get(key, <literal>)`
# fallback in main.py, and this dataclass - and MAINT-04 proved they had already
# drifted: config.yaml said 2000, the other two said 2500. An options dict with
# `maintenance_charge_w` ABSENT was therefore ACCEPTED by validate.py's rule 6
# (which read 2000) and then BUILT by main.py at 2500, against a 2000 W ceiling
# - the exact `lo > hi` contradiction rule 6 exists to refuse, resolving to 0 W
# with `contradiction=True`. Unreachable through the Supervisor, which always
# supplies every key; fully reachable from sim/inject.py and from the test
# suite, which is where anyone debugging maintenance actually is.
#
# WHERE THE SINGLE SOURCE ACTUALLY IS: config.yaml's `options:` block. It is
# what the Supervisor reads and what the operator edits, so it wins by
# definition. This dict is a MIRROR of it and not a second opinion:
# test_maintenance.py pins every entry by READING the shipped file, so a drift
# goes red in CI instead of shipping. That is TARIFF-02's `PRICE_OPTION_DEFAULTS`
# and SAFETY-24's `PEAK_OPTION_DEFAULTS` pattern, now applied to the family that
# named the card. A mirror rather than a runtime read because the Dockerfile
# copies `app/` and `run.sh` into the image and NOT config.yaml - the add-on
# cannot open the file it is configured by, so there is nothing to read at 03:00
# on a client's Pi, and a parser that could fail at import is a new way for the
# add-on not to start.
#
# ⚠️ DEFAULTS ONLY. NO BOUNDS LIVE HERE, and that is a decision, not an
# omission. The RANGE of each key (`maintenance_charge_w: int(500,5000)`) lives
# in config.yaml's `schema:` block and nowhere else, because the Supervisor is
# what enforces it and the Supervisor reads only that file. What this module
# would gain by mirroring the bounds too is a fifth place to disagree with.
# validate.py's rule 6 is NOT a range and does not belong here either: it is a
# relation BETWEEN TWO KEYS (`maintenance_charge_w` against `max_w`) that the
# schema grammar cannot express at all, which is the whole reason that rule is
# written in Python.
#
# ⚠️ KEYED BY THE OPTION NAME, not by the MaintConfig field name. The dict is
# what `from_options()` indexes while reading the operator's dict, so the two
# strings have to be the same string; a `charge_w` key here would reintroduce a
# transcription step between config.yaml and the reader.
MAINT_OPTION_DEFAULTS = {
"maintenance_enabled": False,
"maintenance_interval_days": 28,
"maintenance_start_hour": 10,
# ⚠️ 2000, NOT THE 2500 THIS SHIPPED AS, and config.yaml carries the
# argument: both rates must stay at or below `max_w` (2000) or the
# cheap-window charge shaping asks the arbiter for `hi = -charge_w` against
# a supervised `lo = -max_w` and contradicts itself into 0 W. Raising max_w
# is what unlocks a faster cycle - raise it FIRST, then these.
"maintenance_discharge_w": 2000,
"maintenance_charge_w": 2000,
"maintenance_soc_floor": 11,
"maintenance_soc_target": 99,
"maintenance_hold_min": 120,
}
@dataclass(frozen=True)
class MaintConfig:
enabled: bool = False
interval_days: int = 28
start_hour: int = 10
discharge_w: float = 2500.0
charge_w: float = 2500.0
soc_floor: float = 11.0
soc_target: float = 99.0
hold_min: int = 120
"""The maintenance cycle's settings, already parsed.
⚠️ EVERY DEFAULT IS READ OUT OF `MAINT_OPTION_DEFAULTS`, never typed. A
literal in this class is what made `MaintConfig()` a THIRD opinion about
what a missing key means - see the block above - so `MaintConfig()` and
`MaintConfig.from_options({})` and validate.py's fallback are now
arithmetically the same number by construction rather than by vigilance.
"""
enabled: bool = bool(MAINT_OPTION_DEFAULTS["maintenance_enabled"])
interval_days: int = int(MAINT_OPTION_DEFAULTS["maintenance_interval_days"])
start_hour: int = int(MAINT_OPTION_DEFAULTS["maintenance_start_hour"])
discharge_w: float = float(MAINT_OPTION_DEFAULTS["maintenance_discharge_w"])
charge_w: float = float(MAINT_OPTION_DEFAULTS["maintenance_charge_w"])
soc_floor: float = float(MAINT_OPTION_DEFAULTS["maintenance_soc_floor"])
soc_target: float = float(MAINT_OPTION_DEFAULTS["maintenance_soc_target"])
hold_min: int = int(MAINT_OPTION_DEFAULTS["maintenance_hold_min"])
@classmethod
def from_options(cls, opts: dict) -> "MaintConfig":
"""Build from an add-on options dict.
⚠️ THE ONLY PLACE IN THE ADD-ON THAT READS A `maintenance_*` OPTION.
main.py used to do this inline as eight `opts.get(key, <literal>)`
calls, which is eight opportunities to type a number that config.yaml
does not ship - and one of them had already been taken. Moving the read
next to the mirror means the fallback cannot be anything but the mirror,
because there is no dict literal in sight of it to disagree with.
⚠️ `key in opts`, not `opts.get(key) or ...`. A shipped `false` and a
shipped `0` are values an operator can legitimately set, and the truthy
form would quietly replace both with the default - which is this card's
own bug wearing a different hat.
"""
def _opt(key):
return opts[key] if key in opts else MAINT_OPTION_DEFAULTS[key]
return cls(
enabled=bool(_opt("maintenance_enabled")),
interval_days=int(_opt("maintenance_interval_days")),
start_hour=int(_opt("maintenance_start_hour")),
discharge_w=float(_opt("maintenance_discharge_w")),
charge_w=float(_opt("maintenance_charge_w")),
soc_floor=float(_opt("maintenance_soc_floor")),
soc_target=float(_opt("maintenance_soc_target")),
hold_min=int(_opt("maintenance_hold_min")),
)
@dataclass
+25
View File
@@ -286,6 +286,25 @@ the one place the question is answered. Four things about the shape of it:
discharge, which is the thing SAFETY-07 introduced. A loop-side SoC guard
is a different lever with a different right value.
⚠️ SAFETY-25 MEASURED HOW FAR PAST, so this is no longer a caveat that has
to be taken on trust. On the committed 2026-08-20 capture, 19:00-22:00 UTC
- three hours of house load after the sun has gone, 830 W mean, zero export
- the 13.8 kWh reference pack started one point ABOVE `peak_soc_floor`
ends the evening at 10.0 %, i.e. at `bms_soc_floor`, having delivered
1525 Wh; 343 of 587 control cycles deliver discharge with the pack already
under this floor, and the guard files no floor at all on any of them. The
same replay at `peak_soc_floor` = 5, 11, 20 and 60 ends at the SAME 10.0 %,
which is the finding stated as sharply as it can be: THE EXPOSURE IS A
PROPERTY OF THE CONTROL LAW, NOT A VALUE ANYONE CAN CONFIGURE. And on the
same day's high-load block the two states coexist - 49 cycles reporting
PEAK GUARD FLOOR-LIMITED while the arbiter grants the loop up to 2000 W of
discharge in every one of them. test_peakguard.py part 10 is the replay;
DECISIONS/SAFETY-25-loop-soc-floor.md carries the options and the
recommendation, and the product owner DECIDED it on 2026-09-02: Option A,
the BMS stays the only backstop for demand-driven discharge, with a
loop-side reserve DEFERRED to ALLOC-01. This floor's scope is therefore
settled rather than provisional - it bounds the peak guard, on purpose.
3. IT IS GRADED ONLY WHERE IT IS NOT DEGENERATE. The SoC question is asked
AFTER `wanted > 0` is established - i.e. only where a forced discharge is
actually being asked for. Asked earlier it would grade a quantity that
@@ -373,6 +392,12 @@ CEILING_MONTH_PEAK = "the month's banked peak"
# notification all have to say WHICH, and "floor-limited" alone is unactionable.
FLOOR_SOC_UNREADABLE = ("the battery state of charge was not measured this "
"cycle, and an unreadable SoC is not a full battery")
# ⚠️ SAFETY-25. "the peak guard's SoC floor", not "the SoC floor", and the
# possessive is load-bearing: this string is what the status page, the action log
# and the operator notification all print, and `peak_soc_floor` bounds THIS GUARD
# ONLY. Widening it to "the SoC floor" would make the one sentence an operator
# reads at the moment the battery stops shaving into a claim about the pack that
# the grid-following loop is at that instant disproving.
FLOOR_AT_SOC_FLOOR = "state of charge is at or below the peak guard's SoC floor"
SOURCE = "peak"
+54 -25
View File
@@ -170,6 +170,29 @@ WHAT IS DELIBERATELY *NOT* REFUSED, because it is untidy rather than unsafe:
- `maintenance_discharge_w` above `max_w`. Clamped, not contradicted, and the
clamp names itself in the arbiter's explain() - see rule 6. Warned about,
not refused.
- A device rating that makes SAFETY-18's freeze rail unreachable. SAFETY-20's
AC 4, decided here rather than left implicit: **NO NEW RULE, and rule 2 is
the reason.** The configuration the ticket is about is `max_w` above the
setpoint device's rating, which is rule 2 EXACTLY - already refused, on the
identical predicate, since CFG-01, and re-run by `run_control()` once
ESPHome is up and the real rating is known. A second rule phrased as
"`RAIL_FRAC * max_w` exceeds the device rating" would fire on a strict
subset of the configurations rule 2 already refuses (`0.95 * max_w > dev_max`
implies `max_w > dev_max`), so it could never be the rule that stopped a
start, and its whole visible effect would be a second entry in a refusal
list that already names the problem.
⚠️ AND IT WOULD NOT COVER THE CASE THAT REMAINS, WHICH IS WHY THE STATUS ROW
IS NOT A CONSOLATION PRIZE. The residue after rule 2 is the state where
`hass.limits()` answered `(None, None)` - ESPHome not up when the add-on
booted - so the range checks were SKIPPED rather than guessed at, and the
rating is never re-read afterwards. There is nothing to refuse at startup in
that state, by construction: the number a refusal would need does not exist
yet. That is a runtime coverage question, and the runtime surface -
`freeze.rail_unreachable()` and the NOT COVERED row it feeds - is where it
is answered. Compare rule 5, which CAN be settled at startup because both
`sign_disagree_w` and `max_w` are config and are both known at boot.
- `peak_soc_floor` below `maintenance_soc_floor`, or above it. They are
DIFFERENT QUANTITIES (SAFETY-24: a drain target versus a spend limit) and
every ordering of the two is a legitimate site configuration. Refusing on
@@ -179,6 +202,7 @@ WHAT IS DELIBERATELY *NOT* REFUSED, because it is untidy rather than unsafe:
import logging
from .arbitrage import enabled as arbitrage_on
from .maintenance import MAINT_OPTION_DEFAULTS
from .p1 import is_enabled, validate_meter_options
from .peakguard import PEAK_OPTION_DEFAULTS
from .price import PRICE_OPTION_DEFAULTS, PROVIDERS
@@ -356,26 +380,23 @@ def validate_startup_config(opts: dict, dev_min=None, dev_max=None) -> list[str]
# leave the trap armed for the one operator action - ticking
# maintenance_enabled - that cannot possibly be expected to change what a
# charge rate means.
# ⚠️ THE FALLBACK IS config.yaml's SHIPPED VALUE, and it has to be kept
# equal to it - that is the whole point of AC3. It is reachable only when a
# caller hands over a dict with the key missing (sim/inject.py, a test); the
# Supervisor always supplies every key from config.yaml, so on a real
# install the argument is always present.
#
# ⚠️ KNOWN MISMATCH, LEFT DELIBERATELY AND FLAGGED RATHER THAN FIXED HERE:
# `main.py` still falls back to 2500 in two places
# (`opts.get("maintenance_charge_w", 2500)`), as does maintenance.py's
# MaintConfig dataclass. So a dict with the key ABSENT is accepted by this
# rule at 2000 and then built by main.py at 2500 - the contradiction this
# rule exists to catch, in the one case it cannot see. It is unreachable on
# a Supervisor install and those files are another ticket's right now.
# THE REAL FIX is one source of truth for option defaults; until then the
# divergence is PINNED BY A CHECK rather than by this comment - see
# test_validate.py, "the KNOWN cross-file default divergence". It asserts
# the mismatch as it stands and goes red if EITHER side moves, including
# when somebody closes it in main.py, at which point this block and that
# check both get deleted.
charge_w = _number(opts, "maintenance_charge_w", 2000.0)
# ⚠️ THE FALLBACK IS config.yaml's SHIPPED VALUE, READ RATHER THAN TYPED
# (CFG-03). It is reachable only when a caller hands over a dict with the
# key missing (sim/inject.py, a test); the Supervisor always supplies every
# key from config.yaml, so on a real install the argument is always present
# and this default is dead code. That is precisely why it went stale
# unnoticed for a whole card: MAINT-04 moved config.yaml to 2000 while
# main.py and MaintConfig still said 2500, so a dict with the key ABSENT was
# accepted here at 2000 and then built by main.py at 2500 - the
# contradiction this rule exists to catch, in the one case it could not see.
# The KNOWN MISMATCH block that used to stand here, and the tripwire in
# test_validate.py that pinned it, are both DELETED: the divergence is
# closed rather than recorded. `maintenance.MAINT_OPTION_DEFAULTS` is now
# the one in-code mirror of config.yaml for this family - the same move
# rule 8 below already makes with `PEAK_OPTION_DEFAULTS` - and
# test_maintenance.py pins it by reading the shipped file.
charge_w = _number(opts, "maintenance_charge_w",
float(MAINT_OPTION_DEFAULTS["maintenance_charge_w"]))
if charge_w is None:
problems.append(
f"maintenance_charge_w {opts.get('maintenance_charge_w')!r} is not a number")
@@ -397,10 +418,12 @@ def validate_startup_config(opts: dict, dev_min=None, dev_max=None) -> list[str]
# --- 8. an EMS energy floor the BMS does not already enforce -------------
# ⚠️ THE FALLBACKS ARE peakguard.PEAK_OPTION_DEFAULTS, NOT LITERALS, and
# that is CFG-03 read as a rule rather than as a complaint. Rule 6's own
# comment documents a LIVE divergence in this repo caused by typing 2000
# here and 2500 in main.py; this card refuses to add a second instance of
# it. The dict is the single in-code mirror, pinned to config.yaml by
# test_peakguard.py, and main.py reads the same one.
# comment used to document a LIVE divergence in this repo caused by typing
# 2000 here and 2500 in main.py; SAFETY-24 refused to add a second instance
# of it, and CFG-03 has since closed the first. The dict is the single
# in-code mirror, pinned to config.yaml by test_peakguard.py, and main.py
# reads the same one - exactly as maintenance.MAINT_OPTION_DEFAULTS now is
# for the `maintenance_*` family.
soc_floor = _number(opts, "peak_soc_floor",
PEAK_OPTION_DEFAULTS["peak_soc_floor"])
bms_floor = _number(opts, "bms_soc_floor",
@@ -442,7 +465,13 @@ def validate_startup_config(opts: dict, dev_min=None, dev_max=None) -> list[str]
# words on the status page every cycle, and the cycle still completes -
# slower, and eating into maintenance.DRAIN_TIMEOUT_MIN. Loud and it moves
# energy, so it is neither (a) nor (b): warned, not refused.
disch_w = _number(opts, "maintenance_discharge_w", 2000.0)
# ⚠️ AND THE FALLBACK COMES FROM THE SAME MIRROR AS RULE 6's. CFG-03's PM
# proofread caught this one: `maintenance_discharge_w` had the IDENTICAL
# three-way divergence (config.yaml 2000, MaintConfig 2500) and the card
# named only the charge side. Closing one key and leaving its twin is how a
# single-source fix gets reproduced as a single-source bug one line down.
disch_w = _number(opts, "maintenance_discharge_w",
float(MAINT_OPTION_DEFAULTS["maintenance_discharge_w"]))
if disch_w is not None and max_w is not None and max_w > 0 and disch_w > max_w:
_LOG.warning(
"maintenance_discharge_w %.0f W is above max_w %.0f W. Not refused - "
+11 -9
View File
@@ -97,15 +97,17 @@ Four gates, and each one exists to exclude a specific thing that is NOT a fault:
caller says whether the grid-following loop actually won the arbitration this
cycle, and the timer only accumulates when it did.
⚠️ 1500 W, NOT THE DEFAULT 2500 W, AND THE REASON IS NOT COSMETIC. At the
shipped defaults `maintenance_charge_w` is 2500 and `max_w` is 2000, so the
cheap-window claim is `hi = -2500` against a supervised `lo = -2000`: lo > hi,
which arbiter.py resolves as a CONTRADICTION and 0 W, not as a -2500 W charge.
The example above is written at 1500 W because that is a combination the
schema and the arbiter both actually produce. (The contradiction at the
defaults is a real pre-existing bug - a default maintenance charge silently
never happens in a cheap window - but it is maintenance's, not this module's,
and it is filed separately. Do not "fix" it here.)
⚠️ 1500 W, NOT 2500 W, AND THE REASON IS NOT COSMETIC. The example has to be
a charge the arbiter actually produces. When this was written the shipped
`maintenance_charge_w` was 2500 against a `max_w` of 2000, so the cheap-window
claim was `hi = -2500` against a supervised `lo = -2000`: lo > hi, which
arbiter.py resolves as a CONTRADICTION and 0 W, not as a -2500 W charge - a
default maintenance charge that silently never happened. MAINT-04 refused that
pair in validate.py and moved the shipped rate to 2000; CFG-03 gave the
default one source of truth so main.py and MaintConfig could not go on
answering 2500 to a dict that had never said so. The number here stays 1500
because the point of the example is a charge STRICTLY INSIDE the ceiling, not
one that happens to sit exactly on it.
2. The strict `< 0` product. "Opposed" and "neither side is zero" in one
expression.
+45
View File
@@ -135,6 +135,21 @@ options:
meter_freeze_s: 300
# --- maintenance -----------------------------------------------------------
# ⚠️ CFG-03. THESE EIGHT LINES ARE THE SOURCE OF TRUTH FOR THE MAINTENANCE
# DEFAULTS. The Supervisor reads this file and the operator edits this file,
# so nothing else in the add-on gets an opinion about what a missing
# `maintenance_*` key means. There is exactly ONE in-code copy -
# `app/maintenance.py`'s `MAINT_OPTION_DEFAULTS` - because the Dockerfile does
# not put this file in the image and the running add-on therefore cannot read
# it; test_maintenance.py pins that copy by READING these lines, so a drift
# goes red in CI rather than shipping. main.py and validate.py both read the
# mirror and type no number of their own.
#
# Before this card the same defaults were written down three times and had
# already disagreed: this block said 2000 while main.py and MaintConfig said
# 2500, so an options dict with the key ABSENT passed validation at 2000 and
# then ran at 2500 against a 2000 W ceiling - a silent 0 W arbiter
# contradiction. Changing one of these numbers now moves every consumer.
maintenance_enabled: false
maintenance_interval_days: 28
maintenance_start_hour: 10
@@ -186,6 +201,26 @@ options:
# worst modelled guard day is 878 Wh, i.e. 6.4 % - so 10 points above the
# pack's own cut-out leaves the guard ~1.6 of its worst observed days of room
# and still never reaches the BMS.
#
# ⚠️⚠️ SAFETY-25 - WHAT THIS DOES NOT BOUND, AND IT IS THE HALF THE NAME HIDES.
# peak_soc_floor BOUNDS THE PEAK GUARD ONLY. IT IS NOT A PACK-WIDE RESERVE.
# Ordinary self-consumption - the grid-following loop that holds the meter at
# zero - has no SoC floor of any kind, so on a sustained-load evening it will
# discharge STRAIGHT PAST this number and go on until the pack's own BMS
# cut-out (bms_soc_floor) stops it. Replayed on the committed 2026-08-20
# capture, 19:00-22:00 UTC: a 13.8 kWh pack starting at 21 % ends the evening
# at 10.0 %, and 343 of 587 control cycles deliver discharge with the pack
# already below this floor. Setting this key higher does not change that by
# one tenth of a percent - the same replay at every value the schema accepts
# (5..60) ends at the same 10.0 %.
#
# The reason is structural, not an oversight: the peak guard files a `lo`
# limit (a LOWER bound on the setpoint), which is what makes it provably
# unable to cap a discharge or contradict the arbiter - and therefore also
# unable to stop one the loop itself wants. See peakguard.py's module note and
# DECISIONS/SAFETY-25-loop-soc-floor.md, which records the options for a
# loop-side reserve and is waiting on the product owner. Until that is
# answered, the BMS is the only floor under self-consumption.
peak_soc_floor: 20
# The pack's OWN cut-out percent - what the BMS enforces whatever is set
# above. Register 0x0560 reads 10 on the reference GW5000S-BP, consistent with
@@ -363,6 +398,16 @@ schema:
# app/freeze.py.
meter_freeze_s: int(60,3600)
# ⚠️ CFG-03 - THIS IS WHERE A RANGE LIVES, AND THE ONLY PLACE IT LIVES. The
# `options:` block above holds the DEFAULT; this block holds the BOUNDS, and
# `MAINT_OPTION_DEFAULTS` deliberately mirrors the former and not the latter -
# the Supervisor is what enforces a range and the Supervisor reads only this
# file, so a second copy of `int(500,5000)` in Python would be a place to
# disagree and nothing else. What is NOT expressible here is a relation
# BETWEEN keys: `maintenance_charge_w` must also stay at or below `max_w`, the
# schema grammar has no way to say so, and that is why validate.py's rule 6 is
# written in code instead. Add a ninth maintenance option in three places -
# options:, schema:, MAINT_OPTION_DEFAULTS - and in no fourth.
maintenance_enabled: bool
maintenance_interval_days: int(1,90)
maintenance_start_hour: int(0,23)
+7
View File
@@ -3,6 +3,13 @@
Each assertion is a precedence question someone will eventually ask in the
field: "why did it charge during a peak?", "why did it discharge while the
maintenance cycle was charging?", "what happens if two things disagree?".
⚠️ MUTATING THE MODULE THIS FILE GRADES? PURGE `__pycache__` FIRST - or run
`tools/mutation_run.sh`, which does. `python3 -B` alone does NOT save you: it
stops bytecode being WRITTEN, not a stale one being READ, and a size-preserving
edit reverted inside one second is invisible to CPython's staleness test. That
is TEST-15, and it has already turned one live mutation into a false survivor.
Read MUTATION.md before you report a survivor.
"""
import sys
+17
View File
@@ -62,6 +62,13 @@ THREE RULES THIS FILE HOLDS ITSELF TO, because the reviewer will:
aged out, an hour the series does not cover, an unread state of charge and a
peak guard that never ran are five DIFFERENT reasons - and none of them is
an answer. Section 5 drives all five and asserts they are distinguishable.
⚠️ MUTATING THE MODULE THIS FILE GRADES? PURGE `__pycache__` FIRST - or run
`tools/mutation_run.sh`, which does. `python3 -B` alone does NOT save you: it
stops bytecode being WRITTEN, not a stale one being READ, and a size-preserving
edit reverted inside one second is invisible to CPython's staleness test. That
is TEST-15, and it has already turned one live mutation into a false survivor.
Read MUTATION.md before you report a survivor.
"""
import ast
@@ -506,6 +513,16 @@ check(f"...while THE SAME MAGNITUDES with the sign flipped all DISCHARGE, so "
# Not fixed here on purpose. D and F are TARIFF-03's rungs, they need probes in
# test_static_tariff.py rather than in this file, and the card is explicit that
# its fourth criterion is a look and not a refactor.
#
# ✅ CLOSED BY TEST-16, in test_static_tariff.py SECTION 9, and the two rows
# above are kept as the diagnosis rather than as an open finding. D is pinned by
# a sweep of small-but-real spreads down to 0.000001 EUR/kWh at
# min_spread_eur_kwh=0.0; F is pinned by a ONE-FIRM-HOUR series graded on WHICH
# RUNG'S SENTENCE came back, which is the only way it goes red without borrowing
# the flat rung; and the masking is denied by a table that grades every stimulus
# on its rung's attribution rather than on `kind`. Both are red on their own and
# five checks are red with BOTH weakened at once. Ledger in that section's
# header. Nothing in app/ changed - these rungs were correct all along.
# --------------------------------------------------------------------------- #
+296
View File
@@ -0,0 +1,296 @@
"""Runnable check for TEST-15 - the mutation harness's own honesty.
`python3 test_bytecode.py`
Every other file in this directory grades the add-on. This one grades the thing
that grades the add-on, because in this repository a mutation run IS the
evidence: "I broke it, the suite went red, I put it back, the suite went green"
is how nearly every safety claim here was established.
THE DEFECT, found by FCST-03's developer and reproduced below. CPython decides a
cached `.pyc` is still good from two numbers: the source's SIZE, and its
MTIME TRUNCATED TO WHOLE SECONDS. Reverting `self.provisional` to
`here.provisional` moves neither - same length, same second - so the interpreter
loaded the bytecode it already had. Confirmed then by disassembly: the source
read `here`, the running code loaded `self`. The mutation was reported as a
survivor when in truth it had never run.
WHICH DIRECTION IT LIES IN. A mutation that never took effect makes the suite
stay GREEN, so it is reported as a survivor: stale bytecode MANUFACTURES
SURVIVORS. The opposite - a revert that never took, leaving a red on correct
source - is possible too but announces itself, because a developer chases an
unexplained failure. That asymmetry is why the coverage-audit table in
test_control.py is a lower bound rather than nonsense, and it is what the survey
in MUTATION.md is scoped by.
WHAT THIS FILE PINS, in the order the card's acceptance criteria name it:
AC1 The defect reproduces (part 1), the two mitigations that DO NOT fix it
are shown not to (part 2), the one that does is shown to (part 3), and
the shipped harness is shown to close it end to end on a tree that would
otherwise mis-grade (part 4). Executed, not reasoned: every part builds a
real package, imports it in a real subprocess, and reads back which
value the running code returned.
AC2 The guarantee is where a developer writing a mutation reads it: part 5
requires EVERY test_*.py in this directory to point at MUTATION.md. The
list is derived from the tree, so a new suite that joins without the
pointer is red - CI-01's rule, for CI-01's reason.
AC4 Part 6 pins the two properties that make CI immune, on the workflow file
itself.
⚠️ NOTHING HERE SLEEPS. One-second mtime resolution is the mechanism; a harness
that waits out the clock would be slower on every run and would still only cover
the edit somebody remembered to slow down. Part 1 REPRODUCES the collision
deliberately (it retries until two writes land in the same second, which takes
milliseconds) rather than avoiding it.
⚠️ This file writes only under a temporary directory. It must stay that way: CI
mounts the checkout READ-ONLY, and a check that needs to write into the tree
would fail there for a reason that has nothing to do with what it grades.
⚠️ MUTATING THE MODULE THIS FILE GRADES? PURGE `__pycache__` FIRST - or use
`tools/mutation_run.sh`, which does. `python3 -B` alone does NOT save you: it
stops bytecode being WRITTEN, not a stale one being READ. See MUTATION.md.
"""
import os
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
HERE = Path(__file__).resolve().parent
fails = []
def check(name, cond):
if cond:
print(f" ok {name}")
else:
print(f" FAIL {name}")
fails.append(name)
# ---------------------------------------------------------------------------
# The fixture. `who()` returns one of two names that are THE SAME LENGTH, so
# swapping them leaves the file byte count identical - the first half of
# CPython's staleness test. The second half is the whole-second mtime, which
# part 1 arranges by writing both versions inside one second.
#
# It is deliberately not a copy of a shipped module: the property under test is
# CPython's, and using real code here would make this file go red whenever that
# module changed for unrelated reasons.
# ---------------------------------------------------------------------------
V_OLD = 'def who():\n self = "SELF"\n here = "HERE"\n return self\n'
V_NEW = 'def who():\n self = "SELF"\n here = "HERE"\n return here\n'
assert len(V_OLD) == len(V_NEW), "the fixture must be size-preserving or it grades nothing"
PROBE = "from app.m import who\nprint(who())\n"
# The harness runs `test_*.py` files and grades them by exit status, so the
# probe wears that shape in part 4: it FAILS when it sees the pre-mutation value.
TEST_PROBE = (
"from app.m import who\n"
"v = who()\n"
"print('RUNS:', v)\n"
"raise SystemExit(0 if v == 'HERE' else 1)\n"
)
def run(tree, args, env_extra=None, script="probe.py"):
env = dict(os.environ)
env.pop("PYTHONDONTWRITEBYTECODE", None)
if env_extra:
env.update(env_extra)
out = subprocess.run(
[sys.executable] + args + [script],
cwd=tree, env=env, capture_output=True, text=True,
)
return out.stdout.strip()
def caches(tree):
return sorted(str(p.relative_to(tree)) for p in Path(tree).rglob("__pycache__"))
def seed(tree):
"""Leave `tree` holding V_NEW on disk and V_OLD in its bytecode cache.
Returns True when the collision was actually arranged. Both writes must land
in the same whole second; at a few milliseconds per cycle that is the normal
case, and the caller retries rather than asserting on one attempt, because a
machine that happens to cross a second boundary mid-cycle would otherwise
report a defect in CPython instead of a slow disk.
"""
app = Path(tree) / "app"
shutil.rmtree(app, ignore_errors=True)
app.mkdir(parents=True)
(app / "__init__.py").write_text("")
(Path(tree) / "probe.py").write_text(PROBE)
(Path(tree) / "test_probe.py").write_text(TEST_PROBE)
m = app / "m.py"
m.write_text(V_OLD)
t0 = m.stat().st_mtime
run(tree, []) # compiles V_OLD, writes app/__pycache__
m.write_text(V_NEW) # the "revert": same size, same second
t1 = m.stat().st_mtime
return int(t0) == int(t1) and caches(tree) != []
def seeded_tree(stack):
tree = tempfile.mkdtemp(prefix="test_bytecode.")
stack.append(tree)
for _ in range(40):
if seed(tree):
return tree
return None
tmpdirs = []
print("stale bytecode (TEST-15)")
# ---------------------------------------------------------------------------
print("\n1. the defect: a same-size edit inside one second is not seen at all")
# ---------------------------------------------------------------------------
tree = seeded_tree(tmpdirs)
check("the collision can be arranged at all (same size, same second)", tree is not None)
if tree is None:
print(" cannot continue - the fixture never landed two writes in one second")
raise SystemExit(1)
src = (Path(tree) / "app" / "m.py").read_text()
check("the source on disk says HERE", "return here" in src and "return self" not in src)
check("...and a plain interpreter runs SELF anyway", run(tree, []) == "SELF")
# Stated as its own check because this is the whole ticket in one line: what the
# file says and what the process executes have come apart, with no error, no
# warning, and a zero exit status.
# ---------------------------------------------------------------------------
print("\n2. the two mitigations that do NOT close it")
# ---------------------------------------------------------------------------
# ⚠️ READ THIS BEFORE 'FIXING' A HARNESS WITH -B ALONE. Both of these stop
# bytecode being WRITTEN. Neither stops a stale one being READ, and a mutation
# run always has one already: the previous run wrote it. The advice in
# test_control.py's coverage audit said `-B` first and CLEAR the cache second;
# the order is not a style choice, the clear is the half that works.
check("`python3 -B` over an existing cache still runs SELF", run(tree, ["-B"]) == "SELF")
check(
"PYTHONDONTWRITEBYTECODE=1 over an existing cache still runs SELF",
run(tree, [], {"PYTHONDONTWRITEBYTECODE": "1"}) == "SELF",
)
# ---------------------------------------------------------------------------
print("\n3. the purge closes it, and -B keeps the next run clean")
# ---------------------------------------------------------------------------
for p in Path(tree).rglob("__pycache__"):
shutil.rmtree(p, ignore_errors=True)
check("after the purge, the plain interpreter runs HERE", run(tree, []) == "HERE")
check("...and it has written a fresh cache back", caches(tree) != [])
tree2 = seeded_tree(tmpdirs)
check("second fixture seeded", tree2 is not None)
if tree2:
for p in Path(tree2).rglob("__pycache__"):
shutil.rmtree(p, ignore_errors=True)
check("purge + -B runs HERE", run(tree2, ["-B"]) == "HERE")
check("...and leaves NO cache for the next mutation to inherit", caches(tree2) == [])
# The second half is why the harness passes -B at all. Purging before a run
# protects THIS run; not writing one protects the NEXT edit, which is the
# one nobody is thinking about when they are three mutations into a batch.
# ---------------------------------------------------------------------------
print("\n4. the shipped harness, executed against a tree that would mis-grade")
# ---------------------------------------------------------------------------
harness = HERE / "tools" / "mutation_run.sh"
check("tools/mutation_run.sh exists", harness.is_file())
check("...and is executable", os.access(harness, os.X_OK))
tree3 = seeded_tree(tmpdirs)
check("third fixture seeded", tree3 is not None)
if tree3 and harness.is_file():
# NON-VACUITY FIRST. If the naked run below were already green, the harness
# run after it would prove nothing - it would be passing on a tree that
# needed no help. This is the same trap test_peakguard.py part 7 documents:
# a mutation harness that patches nothing passes beautifully.
naked = subprocess.run(
[sys.executable, "test_probe.py"], cwd=tree3, capture_output=True, text=True
)
check("without the harness the tree grades the STALE source (rc!=0)", naked.returncode != 0)
check("...and says so: it saw SELF", "SELF" in naked.stdout)
got = subprocess.run(
["sh", str(harness), tree3], cwd=tree3, capture_output=True, text=True
)
check("the harness grades the source on disk (rc==0)", got.returncode == 0)
check("...having reported the purge", "no bytecode cache" in got.stdout)
check("...and it leaves no cache behind", caches(tree3) == [])
if got.returncode != 0:
print(got.stdout[-2000:])
print(got.stderr[-2000:])
# The harness must also refuse to report on nothing - CI-01's zero-file rule.
empty = tempfile.mkdtemp(prefix="test_bytecode.empty.")
tmpdirs.append(empty)
none = subprocess.run(
["sh", str(harness), empty], cwd=empty, capture_output=True, text=True
)
check("the harness refuses a tree with no test_*.py", none.returncode != 0)
# ---------------------------------------------------------------------------
print("\n5. the guarantee is stated where a mutation gets written")
# ---------------------------------------------------------------------------
# ⚠️ THE LIST IS DERIVED FROM THE TREE. A hand-written one is how a new suite
# joins this directory carrying no warning at all, which is the exact shape of
# failure CI-01's file glob exists to prevent. If you add a test_*.py, put the
# pointer in its docstring; that is the whole cost.
doc = HERE / "MUTATION.md"
check("MUTATION.md exists", doc.is_file())
if doc.is_file():
text = doc.read_text()
check("...and it names the purge as the load-bearing half", "__pycache__" in text and "purge" in text.lower())
check("...and warns that -B alone does not read fresh", "-B" in text)
check("...and points at the harness", "mutation_run.sh" in text)
suites = sorted(p.name for p in HERE.glob("test_*.py"))
check("there are test suites to survey at all", len(suites) >= 15)
missing = [n for n in suites if "MUTATION.md" not in (HERE / n).read_text()]
check(f"every one of the {len(suites)} suites points at MUTATION.md", missing == [])
if missing:
print(" missing the pointer:", ", ".join(missing))
# ---------------------------------------------------------------------------
print("\n6. CI cannot carry a stale artefact between jobs")
# ---------------------------------------------------------------------------
# ⚠️ THE FIRST TWO PROPERTIES ARE THE ONES THAT ACTUALLY DO THE WORK, AND THEY
# PREDATE THIS CARD. Measured for TEST-15, not assumed: with the checkout bind
# mounted READ-ONLY the interpreter writes no __pycache__ into the tree at all,
# and it does so SILENTLY - no error, no warning, exit status 0. The workflow
# also `rm -rf`s its workspace and clones afresh, so nothing survives from a
# previous job even on the same runner. PYTHONDONTWRITEBYTECODE=1 is belt and
# braces on top: it is what keeps this true if somebody ever needs to drop the
# `:ro`, and dropping the `:ro` is a one-character edit that nothing else here
# would notice.
wf = HERE.parent / ".gitea" / "workflows" / "checks.yml"
check("the workflow file is where this expects it", wf.is_file())
if wf.is_file():
y = wf.read_text()
# ⚠️ GRADED ON THE COMMAND LINE, NOT ON THE FILE. A `in y` search over the
# whole workflow passes on the PROSE around the step - this file's first
# draft did exactly that, and stayed green after the `-e` flag and the `:ro`
# were deleted, because the comment explaining them still named both.
runs = [l for l in y.splitlines() if "docker run" in l and ":/w" in l]
check("exactly one docker run mounts the checkout", len(runs) == 1)
line = runs[0] if runs else ""
check("the checkout is mounted read-only", ':/w:ro"' in line)
check("PYTHONDONTWRITEBYTECODE=1 is set on that run", "-e PYTHONDONTWRITEBYTECODE=1" in line)
check("the workspace is removed before each checkout", 'rm -rf "$WS"' in y)
check("no sleep was introduced to dodge the mtime resolution", "sleep " not in y)
for d in tmpdirs:
shutil.rmtree(d, ignore_errors=True)
print()
if fails:
print(f"{len(fails)} FAILED: " + "; ".join(fails))
sys.exit(1)
print("all checks passed")
+407
View File
@@ -0,0 +1,407 @@
"""Runnable check for CI-02 - what a green from `checks / unit` is a claim about.
`python3 test_ci_gate.py`
test_bytecode.py grades the thing that grades the add-on. This file grades the
thing that decides whether anything was graded at all.
THE DEFECT, and the correction the measurement forced. CI-02 was filed saying
that a CONFLICTED pull request loses its merge ref, so that
git fetch -q --depth 1 origin "$GITHUB_REF" \
|| git fetch -q --depth 1 origin "$GITHUB_SHA"
falls through to the second half and quietly grades the bare branch head. PR #14
did report `checks / unit -> success` while `mergeable: false`, so the symptom
was real. The mechanism was not. Measured on a deliberately conflicted throwaway
pull request (#29, runs 558 and 559 - one question per STEP, because this
Gitea's Actions log endpoints 404 and a step's conclusion is the only channel
out of a job):
GITHUB_REF == refs/pull/<n>/head P01 passed
GITHUB_REF != refs/pull/<n>/merge P02 failed
GITHUB_SHA == the pull request head sha P03 passed
fetching GITHUB_REF succeeds P04 passed <- even conflicted
...and it lands on the bare head P05 passed
refs/pull/<n>/merge does not exist P06 failed
`git ls-remote origin 'refs/pull/*'` on this server advertises only `/head`, for
open and closed pull requests alike. THERE ARE NO MERGE REFS HERE. So the first
half of the `||` always succeeded, the fallback never fired once, and both halves
named the same commit anyway. The gate has never graded merged content on any
pull request in this repository's history. Green has meant "this branch passed
on its own" - which, on a base branch that has moved underneath it, is not the
content that lands. `block_on_outdated_branch` is off on release/1.0, so the
base usually has moved.
WHAT THIS FILE PINS.
Part 1 The context string branch protection requires is assembled from two
tokens in checks.yml. Renaming either makes every open and future
pull request unmergeable forever, silently, because Gitea waits on a
context it will now never receive. This part is the tripwire on that.
Part 2 The three absences in checks.yml that are load-bearing, each graded
on the command lines rather than on the prose around them.
Part 3 THE DEFECT, REPRODUCED. The old one-line checkout is run verbatim
against a real conflicted pull request built here, and is shown to
exit 0 having checked out content that cannot land.
Part 4 THE FIX, EXECUTED. The checkout and merge steps are EXTRACTED FROM
checks.yml AND RUN - the shipped commands, not a paraphrase - against
a pull request that merges. The tree they leave behind is the merge,
and is shown to differ from the head the old line would have graded.
Part 5 The same two steps against a pull request that does NOT merge: the
merge step exits non-zero, says nothing was tested, and never prints
a GRADED line.
Part 6 The gate announces which content it graded, on both paths, so that a
reader can tell merged content from a bare ref (CI-02 AC2).
⚠️ THIS FILE RUNS THE WORKFLOW'S OWN SHELL. That is the point: a check that
read those commands as a string and matched them against an expectation would
be exactly the failure this repository keeps finding - a reading that never
observed its subject. The extractor below is deliberately brittle about finding
the step it wants: if checks.yml is restructured so that the step cannot be
found, this file goes RED rather than quietly grading nothing.
⚠️ NEEDS `git`, which is why .gitea/ci/Dockerfile installs it. No network: the
fixtures are local repositories built in a temp directory, and the workflow's
`git remote add origin "$(echo "$URL" | sed "s#://#://x-access-token:...@#")"`
is a no-op substitution on a path with no `://` in it, which is what lets the
shipped line be used verbatim.
⚠️ This file writes only under a temporary directory. It must stay that way:
CI mounts the checkout READ-ONLY.
⚠️ MUTATING THE MODULE THIS FILE GRADES? PURGE `__pycache__` FIRST - or use
`tools/mutation_run.sh`, which does. See MUTATION.md. (There is no module here
to mutate; the subject is checks.yml. Break a line of it and re-run this file
expecting red - if it stays green, it was never watching.)
"""
import os
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
HERE = Path(__file__).resolve().parent
WF = HERE.parent / ".gitea" / "workflows" / "checks.yml"
fails = []
def check(name, cond):
if cond:
print(f" ok {name}")
else:
print(f" FAIL {name}")
fails.append(name)
# ---------------------------------------------------------------------------
# Reading checks.yml. There is no yaml module in the image the checks run in
# (alpine py3-aiohttp py3-paho-mqtt, and adding a parser to grade five lines
# would be a worse trade than a small parser that fails loudly), so the two
# things this file needs are pulled out by hand:
#
# * the workflow name and the job keys, for part 1
# * the `run:` block of a named step, verbatim, for parts 3 to 6
#
# COMMAND LINES ONLY WHERE IT MATTERS. test_bytecode.py's part 6 learned this
# the hard way: an `in y` search over a whole workflow passes on the PROSE that
# explains a flag, and stayed green after the flag itself was deleted. Every
# absence checked in part 2 is checked against the file with its comment lines
# stripped.
# ---------------------------------------------------------------------------
if not WF.is_file():
print(f"cannot find the workflow at {WF} - nothing to grade")
raise SystemExit(1)
YAML = WF.read_text()
CODE = "\n".join(l for l in YAML.splitlines() if not l.lstrip().startswith("#"))
def workflow_name():
for line in YAML.splitlines():
if line.startswith("name:"):
return line.split(":", 1)[1].strip()
return None
def job_keys():
out, seen = [], False
for line in YAML.splitlines():
if line.startswith("jobs:"):
seen = True
continue
if seen:
if line and not line[0].isspace():
break
if line.startswith(" ") and not line.startswith(" ") and line.rstrip().endswith(":"):
out.append(line.strip()[:-1])
return out
def step_script(name_prefix):
"""Return the `run: |` body of the step whose name starts with name_prefix."""
lines = YAML.splitlines()
i = 0
while i < len(lines):
if lines[i].strip().startswith("- name:") and name_prefix in lines[i]:
break
i += 1
else:
return None
if i >= len(lines):
return None
while i < len(lines) and lines[i].strip() != "run: |":
# stop at the next step so a missing block cannot borrow the next one's
if i > 0 and lines[i].strip().startswith("- name:") and name_prefix not in lines[i]:
return None
i += 1
if i >= len(lines):
return None
body, i = [], i + 1
while i < len(lines):
l = lines[i]
if l.strip() == "":
body.append("")
elif l.startswith(" " * 10):
body.append(l[10:])
else:
break
i += 1
return "\n".join(body).strip("\n")
# ---------------------------------------------------------------------------
# The fixture: a real bare repository with a base branch and a refs/pull/N/head,
# built to order. `conflict=True` makes the pull request touch the same lines
# the base moved, which is how PR #29 was made unmergeable on the server.
#
# The shapes matter. In BOTH cases the pull request adds `from_pr.txt` and the
# base adds `from_base.txt` AFTER the branch point, so the branch head is never
# the content that lands even when it merges perfectly - that difference is what
# part 4 measures, and it is the ordinary case, not the pathological one.
# ---------------------------------------------------------------------------
GIT = ["git", "-c", "user.email=fixture@localhost", "-c", "user.name=fixture",
"-c", "init.defaultBranch=release/1.0", "-c", "commit.gpgsign=false"]
PRNUM = "7"
BASEREF = "release/1.0"
def git(cwd, *args, check_rc=True):
r = subprocess.run(GIT + list(args), cwd=cwd, capture_output=True, text=True)
if check_rc and r.returncode != 0:
raise RuntimeError(f"git {' '.join(args)} failed in {cwd}:\n{r.stderr}")
return r.stdout.strip()
def build_origin(stack, conflict):
"""A bare repo carrying refs/heads/release/1.0 and refs/pull/7/head."""
root = Path(tempfile.mkdtemp(prefix="test_ci_gate."))
stack.append(str(root))
work, bare = root / "work", root / "origin.git"
work.mkdir()
git(work, "init", "-q", ".")
(work / "shared.txt").write_text("one\ntwo\nthree\n")
git(work, "add", "-A")
git(work, "commit", "-qm", "branch point")
fork = git(work, "rev-parse", "HEAD")
# the base moves on
(work / "from_base.txt").write_text("only the base has this\n")
if conflict:
(work / "shared.txt").write_text("one\nTWO FROM BASE\nthree\n")
git(work, "add", "-A")
git(work, "commit", "-qm", "the base branch moves on")
base_sha = git(work, "rev-parse", "HEAD")
# the pull request branches from the fork point
git(work, "checkout", "-q", "-b", "pr", fork)
(work / "from_pr.txt").write_text("only the pull request has this\n")
if conflict:
(work / "shared.txt").write_text("one\nTWO FROM THE PULL REQUEST\nthree\n")
git(work, "add", "-A")
git(work, "commit", "-qm", "the pull request")
pr_sha = git(work, "rev-parse", "HEAD")
git(root, "init", "-q", "--bare", str(bare))
git(work, "remote", "add", "origin", str(bare))
git(work, "push", "-q", "origin", f"{base_sha}:refs/heads/{BASEREF}")
git(work, "push", "-q", "origin", f"{pr_sha}:refs/pull/{PRNUM}/head")
return str(bare), base_sha, pr_sha, str(root)
def run_script(script, ws, origin, pr_sha, extra=None):
env = dict(os.environ)
env.pop("PYTHONDONTWRITEBYTECODE", None)
env.update(
WS=ws, PRNUM=PRNUM, BASEREF=BASEREF, URL=origin, TOKEN="",
GITHUB_REF=f"refs/pull/{PRNUM}/head", GITHUB_SHA=pr_sha,
GIT_TERMINAL_PROMPT="0",
)
if extra:
env.update(extra)
return subprocess.run(["sh", "-c", script], env=env, capture_output=True, text=True)
tmpdirs = []
print("the gate's own honesty (CI-02)")
# ---------------------------------------------------------------------------
print("\n1. the required context string, from the two tokens that build it")
# ---------------------------------------------------------------------------
# ⚠️ READ BEFORE RENAMING ANYTHING IN checks.yml. Branch protection on
# release/1.0 has `enable_status_check: true` and
# `status_check_contexts: ['checks / unit (pull_request)']`. Gitea assembles
# that string from `name:` at the top of the workflow and the job KEY under
# `jobs:`. Change either and Gitea starts posting a context nobody is waiting
# for, while the one branch protection requires never arrives - so it stays
# `pending` forever, on every open pull request and every future one, and
# admin override is blocked. There is no error message anywhere in that
# sequence. This check is the only thing between a tidy-up and that.
REQUIRED = "checks / unit (pull_request)"
name, jobs = workflow_name(), job_keys()
check("the workflow still has a name", name is not None)
check("the workflow declares exactly one job", len(jobs) == 1)
built = f"{name} / {jobs[0]} (pull_request)" if name and len(jobs) == 1 else "<unparseable>"
check(f"the context it builds is exactly {REQUIRED!r}", built == REQUIRED)
if built != REQUIRED:
print(f" it now builds {built!r} - branch protection will wait forever for {REQUIRED!r}")
check("the workflow still triggers on pull_request", "pull_request:" in CODE)
# ---------------------------------------------------------------------------
print("\n2. the three absences that are load-bearing")
# ---------------------------------------------------------------------------
# `paths:` is CI-01's: a workflow that learns to sit a pull request out leaves
# the required context pending forever, which is unmergeable forever.
check("no paths: filter", not any(l.strip().startswith("paths:") or l.strip().startswith("paths-ignore:")
for l in CODE.splitlines()))
# `concurrency:` is CI-02's, and it was MEASURED rather than reasoned about, on
# throwaway PR #29 with one run holding the single runner slot and two more
# pushes behind it:
# no block at all -> runs 561 and 562 both queued, both executed
# group + cancel-in-progress: false
# -> run 564 sat `Blocked by required conditions`
# and was cancelled at 0s the moment 565 existed
# A shared group cancels a run that has not started regardless of that flag, and
# a cancelled run posts `failure` on the required context ("Canceled after 0s"),
# which branch protection cannot tell from a real test failure. Runs 531 and 533
# on PR #14 died exactly this way, each at the same second the next run was
# created. Having no group is the only setting measured to leave a queued run
# alive.
check("no concurrency: group", not any(l.startswith("concurrency:") for l in CODE.splitlines()))
check("no cancel-in-progress anywhere in the commands", "cancel-in-progress" not in CODE)
# The fallback itself. Graded on the command lines: the prose above the step
# quotes the old line on purpose, and an `in YAML` search would match that.
check("the || $GITHUB_SHA fallback is gone from the commands",
not any("||" in l and "GITHUB_SHA" in l for l in CODE.splitlines()))
check("the checkout is no longer shallow (a merge needs the merge base)",
"--depth 1" not in CODE)
# ---------------------------------------------------------------------------
print("\n3. the defect, reproduced: the old line grades a conflicted head, happily")
# ---------------------------------------------------------------------------
# NON-VACUITY FOR EVERYTHING BELOW. If this part were already red - if the old
# line refused a conflicted pull request on its own - then parts 4 and 5 would
# be measuring nothing, and the ticket would have no subject.
origin, base_sha, pr_sha, _root = build_origin(tmpdirs, conflict=True)
ws = tempfile.mkdtemp(prefix="test_ci_gate.ws.")
tmpdirs.append(ws)
OLD = '''
set -eu
rm -rf "$WS" && mkdir -p "$WS/goodwe-addon" && cd "$WS/goodwe-addon"
git init -q .
git remote add origin "$(echo "$URL" | sed "s#://#://x-access-token:${TOKEN}@#")"
git fetch -q --depth 1 origin "$GITHUB_REF" || git fetch -q --depth 1 origin "$GITHUB_SHA"
git checkout -qf FETCH_HEAD
echo "checked out $(git log --oneline -1)"
'''
old = run_script(OLD, ws, origin, pr_sha)
check("the pull request genuinely does not merge (the fixture is not lying)",
subprocess.run(GIT + ["merge-tree", "--write-tree", base_sha, pr_sha],
cwd=origin, capture_output=True, text=True).returncode != 0)
check("...and the old checkout exits 0 on it anyway", old.returncode == 0)
tree = Path(ws) / "goodwe-addon"
check("...having checked out the bare head", (tree / "from_pr.txt").is_file())
check("...which is missing what the base branch added", not (tree / "from_base.txt").is_file())
check("...and it says nothing about which of the two refs it used",
"GRADED" not in old.stdout and "REFUSED" not in old.stdout)
if old.returncode != 0:
print(old.stdout[-800:], old.stderr[-800:])
# ---------------------------------------------------------------------------
print("\n4. the shipped steps, executed, on a pull request that MERGES")
# ---------------------------------------------------------------------------
CO = step_script("check out the base branch and the pull request head")
MERGE = step_script("grade the merge, not the branch")
check("the checkout step can be found in checks.yml", CO is not None)
check("the merge/refuse step can be found in checks.yml", MERGE is not None)
if CO is None or MERGE is None:
print(" checks.yml has been restructured; this file grades nothing until it is updated")
print()
print(f"{len(fails)} FAILED")
raise SystemExit(1)
origin2, base2, pr2, _r2 = build_origin(tmpdirs, conflict=False)
ws2 = tempfile.mkdtemp(prefix="test_ci_gate.ws2.")
tmpdirs.append(ws2)
co = run_script(CO, ws2, origin2, pr2)
mg = run_script(MERGE, ws2, origin2, pr2)
check("the checkout step succeeds", co.returncode == 0)
check("the merge step succeeds on a mergeable pull request", mg.returncode == 0)
if co.returncode or mg.returncode:
print(co.stdout[-600:], co.stderr[-600:], mg.stdout[-600:], mg.stderr[-600:])
t2 = Path(ws2) / "goodwe-addon"
check("what is left on disk carries the pull request's file", (t2 / "from_pr.txt").is_file())
check("...AND the file the base branch added after the branch point", (t2 / "from_base.txt").is_file())
# That second one is the whole difference. The old line graded a tree WITHOUT
# from_base.txt - green about content that is not what lands - and nothing in
# the run said so. This is the ordinary case: no conflict anywhere in it.
check("the graded tree is exactly the tree of a real merge",
git(t2, "rev-parse", "HEAD^{tree}") ==
subprocess.run(GIT + ["merge-tree", "--write-tree", base2, pr2],
cwd=origin2, capture_output=True, text=True).stdout.strip())
# ---------------------------------------------------------------------------
print("\n5. the same two steps on a pull request that does NOT merge")
# ---------------------------------------------------------------------------
ws3 = tempfile.mkdtemp(prefix="test_ci_gate.ws3.")
tmpdirs.append(ws3)
co3 = run_script(CO, ws3, origin, pr_sha)
mg3 = run_script(MERGE, ws3, origin, pr_sha)
check("the checkout step still succeeds - a conflict does not stop a fetch",
co3.returncode == 0)
# Stated as its own check because it is why the defect was invisible: nothing
# about a conflicted pull request makes any git fetch fail on this server.
check("the merge step REFUSES (non-zero)", mg3.returncode != 0)
check("...and says nothing was tested, not that a test failed",
"REFUSED" in mg3.stdout and "NOTHING HAS BEEN TESTED" in mg3.stdout)
check("...and never claims to have graded anything", "GRADED:" not in mg3.stdout)
check("...and leaves no half-merged tree behind for a later step to grade",
not (Path(ws3) / "goodwe-addon" / "from_pr.txt").is_file()
or git(Path(ws3) / "goodwe-addon", "rev-parse", "HEAD") == base_sha)
# ---------------------------------------------------------------------------
print("\n6. the run says which content it graded (CI-02 AC2)")
# ---------------------------------------------------------------------------
check("the mergeable run announces the merge it graded", "GRADED:" in mg.stdout)
check("...naming the base branch it merged into", BASEREF in mg.stdout)
check("...and the tree, which is the only unambiguous name for content",
"tree" in mg.stdout and git(t2, "rev-parse", "HEAD^{tree}")[:12] in mg.stdout)
# The no-pull-request path (workflow_dispatch) keeps a fallback, because a
# branch really can vanish between the dispatch and the fetch. It has to say so.
disp = run_script(CO, tempfile.mkdtemp(prefix="test_ci_gate.ws4."), origin2, pr2,
extra={"PRNUM": "", "GITHUB_REF": f"refs/heads/{BASEREF}"})
check("the no-pull-request path still checks something out", disp.returncode == 0)
check("...and announces that it is NOT merged content",
"GRADED:" in disp.stdout and "NOT merged content" in disp.stdout)
if disp.returncode != 0:
print(disp.stdout[-600:], disp.stderr[-600:])
for d in tmpdirs:
shutil.rmtree(d, ignore_errors=True)
print()
if fails:
print(f"{len(fails)} FAILED: " + "; ".join(fails))
sys.exit(1)
print("all checks passed")
+250 -1
View File
@@ -4,7 +4,8 @@
No framework, asserts only, same house style as test_freeze.py.
Five parts, and parts 3 and 4 are the ones that carry the acceptance criteria:
Six parts, and parts 3 and 4 are the ones that carry SAFETY-03's own
acceptance criteria; part 6 is TEST-11's:
1. THE CLAMP ARITHMETIC, on the shipped `clamp_to_rating()` - boundaries,
symmetry, the device second stage, and the non-finite cases. Table driven.
@@ -23,6 +24,13 @@ Five parts, and parts 3 and 4 are the ones that carry the acceptance criteria:
5. NO PATH BYPASSES IT. write_setpoint() is the only route to the wire, so it
is called directly with an out-of-range value the way the heartbeat and the
operator's buttons call it.
6. TEST-11. THE GUARD READS THE WRITE THAT JUST HAPPENED. `self.clamp_last`
is assigned by `write_setpoint()` and by nothing else, so a
`check_output_clamp()` moved above the write keeps its loop-side evidence
and silently loses its write-side half. Graded as a CONSEQUENCE - what the
watchdog could see when it was consulted - so that a rename or a helper
does not trip it, and with the write-path half exercised on a stimulus of
its own, because parts 3-5 never produce one through cycle().
------------------------------------------------------------------------------
WHY PART 4 ALSO ASSERTS ON `Decision`'s BOOLEANS AND NOT ON `reason`
@@ -47,6 +55,13 @@ WHAT THIS CHECK DOES NOT COVER
asserted here over every value that reached `set_number()`, which is the last
thing this process controls; proving it at the inverter needs the witness log
and belongs with DRIVER-07.
⚠️ MUTATING THE MODULE THIS FILE GRADES? PURGE `__pycache__` FIRST - or run
`tools/mutation_run.sh`, which does. `python3 -B` alone does NOT save you: it
stops bytecode being WRITTEN, not a stale one being READ, and a size-preserving
edit reverted inside one second is invisible to CPython's staleness test. That
is TEST-15, and it has already turned one live mutation into a false survivor.
Read MUTATION.md before you report a survivor.
"""
import asyncio
@@ -543,6 +558,240 @@ check("an in-range value is untouched", hass_d.writes[3] == 1500.0)
check("every emitted frame satisfies |emitted| <= the rating",
all(abs(w) <= 2000.0 for w in hass_d.writes))
# ==============================================================================
print()
print("6. TEST-11: the guard's evidence is THIS cycle's write, not the last one")
# WHY THIS PART EXISTS. `check_output_clamp()` sits one line below
# `await self.write_setpoint(self.target)` in cycle(), and moving it above the
# write left this file, test_freeze.py and test_loop.py ALL GREEN. That is not a
# missing assertion about line numbers - it is a missing assertion about
# EVIDENCE. The guard has two sources:
#
# * `self.loop_clamped`, set from the Decision well ABOVE the write. Still
# seen wherever the call is put, which is why the move is nearly invisible:
# on the §10.3 replay above, every engagement the alarm reports is this one.
# * `self.clamp_last`, which ONLY `write_setpoint()` assigns (main.py) and
# which is None until it has run. This half is what loses its evidence.
#
# So the check below does not pin the call's POSITION IN THE SOURCE, and must
# not: the comment at that line warns against tidying SAFETY-03's ordering and
# SAFETY-18's into one rule, and a check a rename breaks is worse than no check.
# It pins the CONSEQUENCE - that when the guard is consulted, `self.clamp_last`
# is the result of the write of THIS cycle - and part 6b runs the identical
# assertions through a deliberately refactored controller to prove it.
class _SpyWatchdog(ClampWatchdog):
"""The shipped watchdog, plus a record of what the guard could SEE.
⚠️ IT HOOKS THE CONSUMER, NOT THE GUARD'S NAME. Wrapping
`check_output_clamp` by name would make a rename - AC 2's legitimate
refactor - look identical to the defect, and this ticket is explicitly not
allowed to buy its check with a nuisance. `clamp_wd.note()` is the one call
the guard exists to make, so it is hooked instead: it is reached from the
guard under any name, from any helper, as long as that helper runs after the
write.
"""
def __init__(self):
super().__init__()
self.owner = None
self.seen = [] # clamp_last.requested_w at each consultation
self.seen_write = [] # was the WRITE-path half engaged, per cycle
def note(self, engaged, reason, now):
cl = self.owner.clamp_last
self.seen.append(None if cl is None else cl.requested_w)
self.seen_write.append(bool(cl and cl.engaged))
return super().note(engaged, reason, now)
def probed(cls=Controller, grid=9000.0, cycles=5, **over):
"""`wired()`, with the watchdog replaced by the spy and the per-cycle
command returned. A RAMP is used on purpose: the slew limiter makes every
cycle's command a different number, which is what makes "this cycle's
evidence" and "last cycle's evidence" distinguishable at all."""
async def go():
# `track=True` - the plant follows, so the saturation freeze never
# engages and the slew limiter keeps the command MOVING; against a
# dead plant the freeze pins it flat after three cycles and the ramp
# stops being a ramp.
hass = _Hass(grid, track=True)
c = cls(dict(
{"setpoint_entity": "number.sp", "meter_entity": "sensor.grid",
"soc_entity": "sensor.soc", "batt_entity": "sensor.batt",
"meter_source": "off", "max_w": LIVE_MAX_W, "gain": 0.6,
"slew_w": 1000, "deadband_w": 15, "target_grid_w": 0,
"step_w": 10, "heartbeat_s": 10, "stale_input_s": 15},
**over), hass, _Store(), _Pub(), stop=asyncio.Event())
c.auto = True
c.dev_min, c.dev_max = -LIVE_MAX_W, LIVE_MAX_W
c.clamp_wd = _SpyWatchdog()
c.clamp_wd.owner = c
asked = []
for _ in range(cycles):
await c.read_inputs()
await c.cycle()
asked.append(c.target)
return hass, c, asked
return asyncio.run(go())
def evidence_checks(label, asked, wd):
"""The same four claims, run against the shipped controller (6a) and against
a refactored one (6b). Sharing them is the point: if a rename or a helper
changed the answer, this function would say so in the same words."""
seen = wd.seen
print(f" {label}: asked "
f"{[f'{w:+.0f}' for w in asked]}")
print(f" {label}: the guard saw "
f"{['None' if s is None else f'{s:+.0f}' for s in seen]}")
check(f"{label}: PRECONDITION - the command MOVES on every cycle, so this "
f"cycle's evidence and last cycle's are different numbers",
len(set(asked)) == len(asked) and len(asked) >= 4)
check(f"{label}: the guard was consulted exactly once per cycle",
len(seen) == len(asked))
check(f"{label}: AC 1 - on EVERY cycle self.clamp_last held the result of "
f"the write THAT CYCLE. write_setpoint() is the only line that "
f"assigns self.clamp_last, so a check_output_clamp() moved above the "
f"write grades the PREVIOUS cycle's write instead",
seen == asked)
check(f"{label}: ...and on the FIRST cycle self.clamp_last was already set "
f"- before the run's first write it is None, i.e. the write-path half "
f"of the guard has no evidence at all",
bool(seen) and seen[0] is not None)
hass_e, ctl_e, asked_e = probed()
evidence_checks("shipped", asked_e, ctl_e.clamp_wd)
# ⚠️ AND HERE IS WHY AC 3 NEEDS A STIMULUS OF ITS OWN, MEASURED RATHER THAN
# ASSERTED. Through the real cycle() the write-path half never engages: the
# arbiter files the device range and max_w as P_SAFETY LIMIT claims, so
# `resolution.target_w` is already inside both bounds before write_setpoint()
# re-applies them (main.py calls that duplication defence in depth, and it is).
# Every engagement the alarm reports on this path is therefore the loop-side
# one - which is exactly what makes the move nearly invisible, and exactly why
# 6c below drives the write path directly instead of hoping cycle() will.
check(f"MEASURED: the write-path half engaged 0 times in {len(asked_e)} real "
f"cycles ({sum(ctl_e.clamp_wd.seen_write)}), so no cycle()-driven check "
f"can be watching it", not any(ctl_e.clamp_wd.seen_write))
class _RefactoredController(Controller):
"""AC 2, as a fixture rather than as a promise: the two refactors a P3 tidy
would actually make, applied at once.
* the guard is RENAMED to `_clamp_guard()`, the old name left as the thin
delegate such a rename leaves behind;
* the write MOVES INTO A HELPER, `_emit_setpoint()`.
Neither changes when the guard runs relative to the write, so every check in
`evidence_checks()` must stay green. If one of them goes red here, the check
is grading the text of main.py and has to be thrown away.
"""
async def _emit_setpoint(self, value, *, force=False):
await Controller.write_setpoint(self, value, force=force)
async def write_setpoint(self, value, *, force=False):
await self._emit_setpoint(value, force=force)
async def _clamp_guard(self):
await Controller.check_output_clamp(self)
async def check_output_clamp(self):
await self._clamp_guard()
# ⚠️ VERIFIED AGAINST main.py ITSELF, NOT ONLY AGAINST THIS SUBCLASS. Renaming
# `check_output_clamp` throughout main.py AND moving both the write and the guard
# into a new `_emit_and_guard()` helper called from cycle() leaves every check in
# this part green; moving the guard above the write turns the two AC 1 lines
# below red. The one thing a repo-wide rename does cost is the direct call in 6c,
# which is a mechanical find/replace and fails as an AttributeError naming the
# new method - not as an assertion claiming the ordering is wrong, which is the
# false signal this part was written to avoid.
hass_f, ctl_f, asked_f = probed(cls=_RefactoredController)
evidence_checks("renamed + helper", asked_f, ctl_f.clamp_wd)
check("AC 2: the refactored controller behaves identically to the shipped one "
"- same commands, same evidence, so the check above is not pinning "
"either name",
asked_f == asked_e and ctl_f.clamp_wd.seen == ctl_e.clamp_wd.seen)
# --------------------------------------------------------------------------- #
# 6c. AC 3 - the WRITE-PATH half, exercised
# --------------------------------------------------------------------------- #
# The stimulus is SAFETY-20's shape and that is not a coincidence: `max_w` 5000
# on an inverter that reports +-2500 is the one configuration where the value
# put on the wire DIFFERS from the value the loop asked for while every loop-side
# flag stays clean. That difference is the whole content of `clamp_last`, and a
# DEVICE-bound engagement is the only kind `loop_clamped` cannot also see.
#
# It is driven through `write_setpoint()` and the guard directly rather than
# through cycle(), because the measurement above says cycle() cannot produce it
# today. That is stated as a limitation, not hidden: what is being graded here is
# the guard's own contract - given a write that clamped, alarm - and the ordering
# in cycle() is what 6a grades.
async def _write_path(moved=False):
"""`moved` runs the two calls in the order the ticket asks about."""
hass = _Hass(0.0)
c = Controller({"setpoint_entity": "number.sp", "meter_source": "off",
"max_w": LIVE_MAX_W},
hass, _Store(), _Pub(), stop=asyncio.Event())
c.auto = True
# The inverter is SMALLER than the configured ceiling - SAFETY-20's install.
c.dev_min, c.dev_max = -2500.0, 2500.0
c.target = 3000.0
if moved:
await c.check_output_clamp()
await c.write_setpoint(c.target)
else:
await c.write_setpoint(c.target)
await c.check_output_clamp()
return hass, c
hass_w, ctl_w = asyncio.run(_write_path())
notes_w = clamp_notes(hass_w)
print(f" max_w {LIVE_MAX_W:.0f} on a +-2500 W device, asked for "
f"{ctl_w.target:+.0f} W: the device saw {hass_w.writes[-1]:+.0f} W, "
f"bound={ctl_w.clamp_last.bound!r}, loop_clamped={ctl_w.loop_clamped[0]}")
check("PRECONDITION: the write really did clamp, on the DEVICE bound",
ctl_w.clamp_last is not None and ctl_w.clamp_last.engaged
and ctl_w.clamp_last.bound == "device"
and hass_w.writes[-1] == 2500.0)
check("...and the loop-side half is SILENT here, so self.clamp_last is the "
"only evidence that this happened at all",
ctl_w.loop_clamped == (False, ""))
check("AC 3: the guard alarmed on write-path evidence alone",
ctl_w.clamp_wd.engagements == 1 and len(notes_w) == 1)
check("...and the operator is told WHICH bound bit, so a device-rating clamp "
"is not reported as a max_w one",
bool(notes_w) and "device bound" in notes_w[0]["message"])
check("...and the action log carries the row, written by write_setpoint()",
any(REASON_CODE in e and "device bound" in e for e in ctl_w.events))
# The same stimulus, the same clamp, the two calls swapped. This is the ticket
# in one pair of runs.
hass_m, ctl_m = asyncio.run(_write_path(moved=True))
print(f" the same stimulus with the guard consulted BEFORE the write: "
f"{ctl_m.clamp_wd.engagements} engagement(s), "
f"{len(clamp_notes(hass_m))} notification(s), and the clamp still "
f"happened (engaged={ctl_m.clamp_last.engaged})")
check("THE DEFECT, DEMONSTRATED: consulted before the write the guard is "
"SILENT - self.clamp_last is still None at that point - while the wire "
"carries a clamped value either way",
not clamp_notes(hass_m) and ctl_m.clamp_wd.engagements == 0
and ctl_m.clamp_last.engaged and hass_m.writes[-1] == 2500.0)
check("...and main.py:856's consumer is the line that goes quietly false",
bool(ctl_w.clamp_last and ctl_w.clamp_last.engaged))
print()
if fails:
print(f"{len(fails)} FAILED: {', '.join(fails)}")
+23 -8
View File
@@ -6,6 +6,13 @@ its absence caused an observed failure on real hardware.
If you change control.py, run this. If it fails, the inverter would have done
something you did not intend.
⚠️ MUTATING THE MODULE THIS FILE GRADES? PURGE `__pycache__` FIRST - or run
`tools/mutation_run.sh`, which does. `python3 -B` alone does NOT save you: it
stops bytecode being WRITTEN, not a stale one being READ, and a size-preserving
edit reverted inside one second is invisible to CPython's staleness test. That
is TEST-15, and it has already turned one live mutation into a false survivor.
Read MUTATION.md before you report a survivor.
"""
import sys
@@ -71,14 +78,22 @@ def check(name, cond):
# Hence: A FIXTURE MUST SIT CLEAR OF EVERY RAIL IT IS NOT TESTING. Where a test
# names one mechanism, make that mechanism the binding one (see TCLAMP and TF).
#
# ⚠️ RUN MUTATIONS WITH `python -B` AND CLEAR app/__pycache__. CPython
# invalidates a .pyc on (source mtime in whole seconds, source size), so a
# same-second rewrite that also preserves the file size reuses stale bytecode
# and the suite reports on code you are no longer running. It under-reported one
# mutation here as 2 where the true figure is 6. The error is one-directional -
# stale bytecode can only under-report - so every figure above is a lower bound
# at worst, and the two zeros ever recorded were both confirmed by fixing them
# and watching the count rise, which a caching artefact cannot do.
# ⚠️ RUN MUTATIONS THROUGH `tools/mutation_run.sh`, WHICH CLEARS __pycache__
# BEFORE IT RUNS ANYTHING. CPython invalidates a .pyc on (source mtime in whole
# seconds, source size), so a same-second rewrite that also preserves the file
# size reuses stale bytecode and the suite reports on code you are no longer
# running. It under-reported one mutation here as 2 where the true figure is 6.
#
# ⚠️ AND THE CLEAR IS THE HALF THAT WORKS. This note used to lead with
# `python -B`; TEST-15 measured what that flag actually does, and it is
# write-only - it does not stop an EXISTING stale .pyc being read, and a
# mutation run always has one, because the previous run wrote it. -B is still
# worth passing, for the NEXT edit rather than this one.
#
# The error is one-directional - stale bytecode can only under-report - so
# every figure above is a lower bound at worst, and the two zeros ever recorded
# were both confirmed by fixing them and watching the count rise, which a
# caching artefact cannot do.
# ---------------------------------------------------------------------------
print("control law")
+267 -25
View File
@@ -62,6 +62,13 @@ load the meter's POWER FIGURE never moved - 10130.0 W for 26 consecutive polls -
and only the kWh registers kept `unchanged_s` at zero. See the note in
freeze.py; it is why the fingerprint's register terms are the negative case
rather than a nicety.
⚠️ MUTATING THE MODULE THIS FILE GRADES? PURGE `__pycache__` FIRST - or run
`tools/mutation_run.sh`, which does. `python3 -B` alone does NOT save you: it
stops bytecode being WRITTEN, not a stale one being READ, and a size-preserving
edit reverted inside one second is invisible to CPython's staleness test. That
is TEST-15, and it has already turned one live mutation into a false survivor.
Read MUTATION.md before you report a survivor.
"""
import asyncio
@@ -79,7 +86,8 @@ import aiohttp
from app.control import Tuning, compute
from app.freeze import (
RAIL_FRAC, FreezeWatchdog, FreezeWatchdogConfig, looks_frozen, rail_w,
RAIL_FRAC, FreezeWatchdog, FreezeWatchdogConfig, looks_frozen,
rail_ceiling_w, rail_unreachable, rail_w,
)
from app.main import Controller
from app.p1 import HomeWizardLocalSource, P1Ingest
@@ -88,11 +96,17 @@ fails = []
T0 = datetime(2026, 8, 26, 7, 0, 0, tzinfo=timezone.utc)
HERE = Path(__file__).resolve().parent
# The live install's numbers, which are the ones the exposure is written at.
LIVE_MAX_W = 5000.0
# ⚠️ NOT config.yaml's shipped max_w. This is the LIVE INSTALL's own setting -
# the schema maximum, 5000 - which this file uses on purpose wherever the
# scenario under test is "a device smaller than the configured max_w" (freeze.py
# describes exactly this install). Named LIVE_INSTALL_MAX_W, not the shorter
# LIVE_MAX_W it used to be called, so it cannot be misread as "the current
# shipped default" - see SHIPPED_MAX_W below for that number, and the pin two
# sections down for what stops the two from drifting apart unnoticed (TEST-10).
LIVE_INSTALL_MAX_W = 5000.0
# --------------------------------------------------------------------------- #
# THE SHIPPED THRESHOLD, READ FROM config.yaml (TEST-06 / AC3)
# THE SHIPPED DEFAULTS, READ FROM config.yaml (TEST-06 / TEST-10 / AC3)
# --------------------------------------------------------------------------- #
# ⚠️ `meter_freeze_s: 300` used to appear in this file only as the literal 300,
# retyped six times, so `300 -> 3600` in config.yaml left every check here
@@ -110,9 +124,18 @@ def _cfg_default(key):
return float(found[0]) if len(found) == 1 else None
SHIPPED_HOLD_S = _cfg_default("meter_freeze_s")
SHIPPED_DEADBAND_W = _cfg_default("deadband_w")
SHIPPED_MAX_W = _cfg_default("max_w")
# THE KEYS THIS FILE PINS - one place, so the next key added to config.yaml's
# options block can be checked against it rather than discovered unread later
# (TEST-10 / AC3). Deliberately not every key: max_w, deadband_w and
# meter_freeze_s are the ones this file's arithmetic actually reasons about
# (the mutual-exclusion argument in section 2b needs all three together).
# Everything else in config.yaml's options block is out of scope here - see
# test_validate.py for the general "no default silently drifts" pin, and do
# NOT add a maintenance_* key here: CFG-03 is moving that default between
# config.yaml, main.py and maintenance.py concurrently with this ticket.
PINNED_KEYS = ("meter_freeze_s", "deadband_w", "max_w")
SHIPPED_HOLD_S, SHIPPED_DEADBAND_W, SHIPPED_MAX_W = (
_cfg_default(key) for key in PINNED_KEYS)
def check(name, cond):
@@ -121,7 +144,7 @@ def check(name, cond):
fails.append(name)
def tuning(max_w=LIVE_MAX_W):
def tuning(max_w=LIVE_INSTALL_MAX_W):
"""The shipped defaults from config.yaml, at the live install's max_w."""
return Tuning(gain=0.6, max_w=max_w, slew_w=1000, deadband_w=15,
target_grid_w=-10, step_w=10, saturation_w=500,
@@ -155,6 +178,87 @@ check("no transport signal (unchanged_s None) -> silent, never assumed frozen",
check("no command yet -> silent", not looks_frozen(3600, None, 5000, cfg))
check("rail_w tracks RAIL_FRAC", rail_w(5000) == 5000 * RAIL_FRAC)
# --------------------------------------------------------------------------- #
# 1c. SAFETY-20 - the rail is measured against what the WIRE can carry
# --------------------------------------------------------------------------- #
# ⚠️ EVERY CHECK IN THIS SECTION WAS RED BEFORE THE FIX AND IS THE FIX'S ONLY
# EVIDENCE. The shipped rail was `RAIL_FRAC * max_w` and the emitted command is
# clipped to the SETPOINT DEVICE's range as well (clamp.py's second stage, and
# the arbiter's `device` P_SAFETY claim), so any rating at or below
# `0.95 * max_w` made term 2 unsatisfiable by construction while the status page
# went on printing `armed (... over 4750 W)`.
#
# THIS IS ALSO THE CHECK THAT HAS TO GO RED IF ANYONE REVERTS THE RAIL TO BARE
# `max_w` (AC3). Verified by doing it - reinstating
# `return abs(float(max_w)) * RAIL_FRAC` in `rail_w()` fails the six checks
# below plus three in part 6, and nothing else in the suite.
print("SAFETY-20: the rail against the device rating")
# The ticket's own numbers: a 5 kW ceiling on a 4.7 kW inverter.
DEV = dict(dev_min=-4700.0, dev_max=4700.0)
check("the rail is the DEVICE's rail, not max_w's, when the device is smaller",
rail_w(LIVE_INSTALL_MAX_W, **DEV) == 4700.0 * RAIL_FRAC
and rail_w(LIVE_INSTALL_MAX_W, **DEV) != LIVE_INSTALL_MAX_W * RAIL_FRAC)
check("a command pinned at the device rating with a meter frozen for an hour "
"FIRES - this is the ticket, and it returned False before the fix",
looks_frozen(3600, 4700, LIVE_INSTALL_MAX_W, cfg, **DEV))
check("...and the identical call without the rating is still False, so the "
"check above is measuring the rating and not something else",
not looks_frozen(3600, 4700, LIVE_INSTALL_MAX_W, cfg))
check("the charge rail moves with it too - the runaway can be either sign",
looks_frozen(3600, -4700, LIVE_INSTALL_MAX_W, cfg, **DEV))
check("just under the DEVICE rail is still silent, so the fix widened term 2 "
"by exactly the rating and not into a bare unchanged_s threshold",
not looks_frozen(3600, 4700 * RAIL_FRAC - 1, LIVE_INSTALL_MAX_W, cfg, **DEV))
check("a device BIGGER than max_w cannot raise the rail - max_w is still a "
"ceiling the operator set and this is a min(), not a swap",
rail_w(LIVE_INSTALL_MAX_W, dev_min=-9000.0, dev_max=9000.0)
== LIVE_INSTALL_MAX_W * RAIL_FRAC)
check("an unread rating (ESPHome not up) leaves the old behaviour exactly - "
"no device clamp is applied on that path either, so max_w IS the ceiling",
rail_w(LIVE_INSTALL_MAX_W, dev_min=None, dev_max=None) == LIVE_INSTALL_MAX_W * RAIL_FRAC)
check("one bound alone still lowers it - hass.limits() reads min and max "
"independently and either can come back None on its own",
rail_w(LIVE_INSTALL_MAX_W, dev_max=4000.0) == 4000.0 * RAIL_FRAC)
check("a non-finite rating is IGNORED, never read as a 0 W ceiling",
rail_w(LIVE_INSTALL_MAX_W, dev_min=float("nan"), dev_max=float("inf"))
== LIVE_INSTALL_MAX_W * RAIL_FRAC)
check("the ceiling helper says what it measured",
rail_ceiling_w(LIVE_INSTALL_MAX_W, **DEV) == 4700.0)
# The degenerate end. A ceiling of 0 W does not disarm term 2, it makes it TRUE
# OF EVERY COMMAND - including a parked 0 W one - which decays the conjunction
# into the bare `unchanged_s > N` threshold TEL-05 refused for false-tripping at
# this controller's own operating point.
check("a device that can command nothing makes the rail UNREACHABLE, with a "
"reason for the status page",
bool(rail_unreachable(LIVE_INSTALL_MAX_W, dev_min=0.0, dev_max=0.0)))
check("...and a reachable rail says so with an empty string, or the row above "
"would be permanent",
rail_unreachable(LIVE_INSTALL_MAX_W, **DEV) == ""
and rail_unreachable(LIVE_INSTALL_MAX_W) == "")
check("...and the predicate is SILENT there rather than degenerately true - "
"0 W would otherwise satisfy `abs(command) >= 0`",
not looks_frozen(3600, 0.0, LIVE_INSTALL_MAX_W, cfg, dev_min=0.0, dev_max=0.0)
and not looks_frozen(3600, 5000, LIVE_INSTALL_MAX_W, cfg, dev_min=0.0,
dev_max=0.0))
# The alarm text is the third surface that carried the untrue number - it
# outlives the page, in the log and in the HA notification.
_wd20 = FreezeWatchdog(cfg)
_wd20.evaluate(3600, 4700, LIVE_INSTALL_MAX_W, T0, **DEV)
print(f" at max_w {LIVE_INSTALL_MAX_W:.0f} on a +-4700 W device: "
f"{_wd20.reason}")
check("the alarm reason quotes the rail it actually used and NOT the max_w one "
"the command could never have reached",
f"command over {4700 * RAIL_FRAC:.0f} W" in _wd20.reason
and f"{LIVE_INSTALL_MAX_W * RAIL_FRAC:.0f} W" not in _wd20.reason)
check("...and it says the device is what capped it, so the operator is not "
"left wondering why the guard is armed somewhere other than max_w",
"rating" in _wd20.reason and "max_w" in _wd20.reason)
print("the edge")
wd = FreezeWatchdog(cfg)
edges = [wd.evaluate(u, c, 5000, T0 + timedelta(seconds=i))
@@ -188,6 +292,18 @@ check("the code default and the shipped default are the same number - "
check("this file's `tuning()` really is config.yaml's deadband, so the "
"mutual-exclusion arithmetic below is about the shipped law",
tuning().deadband_w == SHIPPED_DEADBAND_W)
# TEST-10: max_w had no such pin - `max_w: 2000 -> 4500` in config.yaml left
# every check in this file green, the same gap TEST-06 closed for
# meter_freeze_s one key over. `Tuning`'s own bare default (control.py) is
# 2000.0 because that IS the shipped default; comparing the two means a
# config.yaml edit that is not matched in control.py goes red here, the same
# way FreezeWatchdogConfig().hold_s catches a drifted meter_freeze_s above.
# This is deliberately NOT a check against LIVE_INSTALL_MAX_W (5000) - that
# constant is the live install's own override and is supposed to differ from
# the shipped default; see its definition for why.
check("the code default and the shipped default agree on max_w too - "
"Tuning() is a default, config.yaml is the ship",
Tuning().max_w == SHIPPED_MAX_W)
# The upper bound is money: config.yaml's own comment says 300 s is "still
# inside the 900 s quarter that bills the capacity tariff". A hold that outlives
@@ -246,7 +362,7 @@ def replay(hold_s, max_w, cycle_floor_s=15.0):
return wd, peak_cmd, peak_unchanged, fired_at
for mw in (2000.0, LIVE_MAX_W):
for mw in (SHIPPED_MAX_W, LIVE_INSTALL_MAX_W):
wd_r, peak_cmd, peak_unchanged, fired = replay(SHIPPED_HOLD_S, mw)
print(f" max_w {mw:.0f}: worst |command| {peak_cmd:.0f} W (rail "
f"{rail_w(mw):.0f} W), worst unchanged {peak_unchanged:.1f} s "
@@ -258,7 +374,7 @@ for mw in (2000.0, LIVE_MAX_W):
# The margin on the OTHER term, as numbers rather than as trust. Both figures
# are quoted in config.yaml and freeze.py, so they are re-measured every run and
# a capture swapped underneath them cannot leave the prose saying the old thing.
_, _, worst_unchanged, _ = replay(SHIPPED_HOLD_S, LIVE_MAX_W)
_, _, worst_unchanged, _ = replay(SHIPPED_HOLD_S, LIVE_INSTALL_MAX_W)
gaps, last, prev = [], rows[0]["t"], None
for r in rows:
if prev is None or r["pwr"] != prev:
@@ -292,7 +408,7 @@ check(f"the shipped {SHIPPED_HOLD_S:.0f} s is at least 15x the worst of the two"
# that happens not to move.
print("TEL-05's low-power case - a converged meter that legitimately repeats")
tel05 = FreezeWatchdog(FreezeWatchdogConfig(hold_s=SHIPPED_HOLD_S))
t5 = tuning(LIVE_MAX_W)
t5 = tuning(LIVE_INSTALL_MAX_W)
tgt, iw, sc = 0.0, 0.0, 0
bare_would_fire = False
tel05_cmd = 0.0
@@ -308,7 +424,7 @@ for k in range(TEL05_S):
tel05_cmd = max(tel05_cmd, abs(tgt))
# The REJECTED design, written out so the case can be shown to be real.
bare_would_fire = bare_would_fire or float(k) >= SHIPPED_HOLD_S
tel05.evaluate(float(k), tgt, LIVE_MAX_W, T0 + timedelta(seconds=k))
tel05.evaluate(float(k), tgt, LIVE_INSTALL_MAX_W, T0 + timedelta(seconds=k))
print(f" {TEL05_S / 60:.0f} min at -14.2 W: worst |command| {tel05_cmd:.0f} W, "
f"unchanged_s reaches {TEL05_S - 1} s, episodes {tel05.episodes}")
check("the bare unchanged_s threshold TEL-05 rejected WOULD fire here",
@@ -316,7 +432,7 @@ check("the bare unchanged_s threshold TEL-05 rejected WOULD fire here",
check("the conjunction does not - this is what the rail term buys",
tel05.episodes == 0)
check("...and the command stayed nowhere near the rail",
tel05_cmd < rail_w(LIVE_MAX_W))
tel05_cmd < rail_w(LIVE_INSTALL_MAX_W))
# The structural version of the same point, re-derived rather than asserted in
# prose: the slowest register a HEALTHY meter can have while still being seen as
@@ -332,7 +448,7 @@ print(f" at the shipped {SHIPPED_HOLD_S:.0f} s hold, the slowest healthy "
check("a healthy meter slow enough to look unchanged is inside the deadband",
slowest_healthy_w < DEADBAND_W)
_park = compute(prev_w=0.0, grid_w=-slowest_healthy_w, actual_w=0.0,
tuning=tuning(LIVE_MAX_W), sat_count=0, i_w=0.0)
tuning=tuning(LIVE_INSTALL_MAX_W), sat_count=0, i_w=0.0)
check("...and the shipped law really does park the command there",
_park.target_w == 0.0)
@@ -411,7 +527,7 @@ while True:
'''
async def live_run(port, mode, hold_s=10.0, seconds=16.0, max_w=LIVE_MAX_W):
async def live_run(port, mode, hold_s=10.0, seconds=16.0, max_w=LIVE_INSTALL_MAX_W):
"""Poll a real HTTP meter through the real transport and drive the detector."""
ingest = P1Ingest(phases=1, max_age_s=30)
wd = FreezeWatchdog(FreezeWatchdogConfig(hold_s=hold_s))
@@ -494,7 +610,7 @@ fired2, polls2, unch2, cmd2 = with_server(
print(f" moving: {polls2} polls, worst unchanged {unch2:.1f} s, "
f"worst |command| {cmd2:.0f} W, alarm at "
f"{'never' if fired2 is None else f'{fired2:.1f} s'}")
check("the moving meter also drove the command to the rail", cmd2 >= rail_w(LIVE_MAX_W))
check("the moving meter also drove the command to the rail", cmd2 >= rail_w(LIVE_INSTALL_MAX_W))
check("a REAL railed condition against a live meter stays silent", fired2 is None)
check("...because the meter kept moving", unch2 < 10.0)
@@ -582,7 +698,7 @@ STALE_INPUT_S = 15.0
def _opts(**over):
o = {"setpoint_entity": "number.sp", "meter_entity": "sensor.grid",
"soc_entity": "sensor.soc", "batt_entity": "sensor.batt",
"meter_source": "off", "max_w": LIVE_MAX_W, "gain": 0.6,
"meter_source": "off", "max_w": LIVE_INSTALL_MAX_W, "gain": 0.6,
"slew_w": 1000, "deadband_w": SHIPPED_DEADBAND_W,
"target_grid_w": -10, "step_w": 10, "heartbeat_s": 10,
"stale_input_s": STALE_INPUT_S}
@@ -649,19 +765,24 @@ def notes_by_text_of(hass):
if "frozen" in str(d.get("title", "")).lower()]
def wired(unchanged_s, grid, cycles=60, **over):
def wired(unchanged_s, grid, cycles=60, dev=(-5000.0, 5000.0), **over):
"""Returns (hass, controller, trace).
`trace` is one row per cycle - (command after the cycle, the watchdog's
level, notifications raised so far) - which is what AC1 needs: the
QUESTION IS NOT WHETHER THE ALARM HAPPENS BUT ON WHICH CYCLE.
⚠️ `dev` IS THE SETPOINT DEVICE'S OWN REPORTED RANGE, and it is a parameter
rather than a constant because SAFETY-20 is entirely about installs where it
is NOT the default +-5000. It defaults to the live install's rating, which
equals its `max_w` - which is exactly why that install never saw the defect.
"""
async def go():
hass = _Hass(grid)
c = Controller(_opts(**over), hass, _Store(), _Pub(),
stop=asyncio.Event())
c.auto = True
c.dev_min, c.dev_max = -5000.0, 5000.0
c.dev_min, c.dev_max = dev
c.p1_source = _Source(unchanged_s)
trace = []
for _ in range(cycles):
@@ -717,7 +838,7 @@ check("the event log names it", any("METER FROZEN" in e for e in ctl_f.events))
# ⚠️ NOTIFY, NOT TRIP. If a later cut turns this into a trip it must come here
# and change this expectation deliberately, not discover it in the field.
check("and it does NOT command 0 W - this cut is an alarm only",
abs(ctl_f.target) >= rail_w(LIVE_MAX_W))
abs(ctl_f.target) >= rail_w(LIVE_INSTALL_MAX_W))
# ⚠️ THE THREE SCENARIOS THAT SAFETY-03 FORCED A DECISION ON, decided one at a
# time and not reflexively narrowed to green. Measured on the merged tree:
@@ -754,7 +875,7 @@ print(f" real 8 kW load, moving meter: surface "
f"freeze {len(notes_of(hass_m))}")
check("wired up, a real railed load against a moving meter raises nothing FROM "
"THIS GUARD (the clamp alarm there is SAFETY-03's and is correct)",
not notes_of(hass_m) and abs(ctl_m.target) >= rail_w(LIVE_MAX_W))
not notes_of(hass_m) and abs(ctl_m.target) >= rail_w(LIVE_INSTALL_MAX_W))
hass_u = wired(None, 4000.0)[0]
print(f" uncovered transport: surface "
@@ -808,7 +929,7 @@ check("an uncovered transport (no unchanged_s) raises nothing FROM THIS GUARD, "
print("WHERE the detector is evaluated in cycle() - the ordering AC1 protects")
_railed = [i for i, (t, _, _) in enumerate(trace_f)
if abs(t) >= rail_w(LIVE_MAX_W)]
if abs(t) >= rail_w(LIVE_INSTALL_MAX_W)]
_alarmed = [i for i, (_, _, n) in enumerate(trace_f) if n >= 1]
_first_railed = _railed[0] if _railed else None
_first_alarm = _alarmed[0] if _alarmed else None
@@ -878,7 +999,7 @@ print(f" poll task killed: alarming at {_before[0]:+.0f} W "
for i, (t, a, n) in enumerate(_dead)))
check("the episode really was standing before the poll task died - otherwise "
"the release below is vacuous",
_before[1] and _before[2] == 1 and abs(_before[0]) >= rail_w(LIVE_MAX_W))
_before[1] and _before[2] == 1 and abs(_before[0]) >= rail_w(LIVE_INSTALL_MAX_W))
check("a dead poll task drives the command to 0 W",
bool(_zeroed) and _zeroed[0] == 0)
check("...and on THAT SAME cycle the alarm is already clear, because the "
@@ -903,7 +1024,7 @@ check("...and it stays clear for as long as the failsafe holds it there",
# loop re-rails, and that is a new episode which MUST speak. What must not
# happen is a second notification stacking up beside the first.
_re_railed = [i for i, (t, _, _) in enumerate(_revived)
if abs(t) >= rail_w(LIVE_MAX_W)]
if abs(t) >= rail_w(LIVE_INSTALL_MAX_W)]
print(f" transport revived: command re-rails on cycle "
f"{_re_railed[0] if _re_railed else None}, "
f"{_ctl_d.freeze_wd.episodes} episode(s), {len(_freeze_notes)} "
@@ -990,10 +1111,131 @@ check("...and it quotes the hold and the rail it is armed at, derived from the "
"config the controller was actually built with",
bool(_rows_c)
and f"{_ctl_c.freeze_wd.cfg.hold_s:.0f} s unchanged" in _rows_c[0]["text"]
and f"{rail_w(LIVE_MAX_W):.0f} W" in _rows_c[0]["text"])
and f"{rail_w(LIVE_INSTALL_MAX_W):.0f} W" in _rows_c[0]["text"])
check("...as an ok row, since a covered armed guard is not a warning",
bool(_rows_c) and _rows_c[0]["ok"] and not _rows_c[0]["warn"])
# --------------------------------------------------------------------------- #
# 5b. SAFETY-20 - is the device range actually WIRED into the guard? (AC1)
# --------------------------------------------------------------------------- #
# ⚠️ THIS SECTION EXISTS BECAUSE THE FIX SURVIVED ITS OWN MUTATION TEST WITHOUT
# IT. Deleting `dev_min=`/`dev_max=` from `check_meter_frozen()`'s call - i.e.
# shipping the corrected predicate and then not telling it the rating - left
# every check in 1c and 6b green, because those grade `freeze.py` and the status
# string and neither of them goes through `cycle()`. A guard that is right in the
# module and unwired in the caller is the defect with an extra step.
#
# So this drives the REAL `Controller.cycle()` on a controller configured the way
# the ticket describes - `max_w: 5000` on a +-4700 W inverter - and asserts on
# the notification that leaves the process.
#
# ⚠️ WHAT IT STILL DOES NOT COVER, stated rather than implied: the OTHER call
# site, `looks_frozen(...)` inside the SAFETY-07 peak-guard block, is behind
# `if self.p1_enabled` and needs a fed averager to have any observable
# consequence (`blindness()` returns BLIND_NO_BLOCK before it ever reads
# `frozen`). That gate is uncovered here for the same reason freeze_rows() says
# it is uncovered there, and widening the fixture belongs to whoever covers it.
print("SAFETY-20: the device range through the REAL cycle()")
_h20, _c20, _t20 = wired(3600.0, 4000.0, dev=(-4700.0, 4700.0))
_n20 = notes_of(_h20)
print(f" max_w 5000 on a +-4700 W device, meter frozen an hour: the command "
f"stood at {_c20.target:+.0f} W, {len(_n20)} freeze notification(s), "
f"watchdog active={_c20.freeze_wd.active}")
check("PRECONDITION: the device rating - not max_w - is what stopped the "
"command, so this really is the configuration the ticket is about",
abs(_c20.target) == 4700.0)
check("...and that command is BELOW the max_w rail, which is why the shipped "
"guard could never fire on this install",
abs(_c20.target) < rail_w(LIVE_INSTALL_MAX_W))
check("...and at or above the device rail, which is why it must",
abs(_c20.target) >= rail_w(LIVE_INSTALL_MAX_W, dev_min=-4700.0, dev_max=4700.0))
check("THE ALARM FIRES through the real cycle() - the rating reaches the "
"predicate from the controller, not just from a unit call",
len(_n20) == 1 and _c20.freeze_wd.active)
check("...and the notification the operator gets quotes the capped rail, "
"not the max_w one",
bool(_n20)
and f"{rail_w(LIVE_INSTALL_MAX_W, dev_min=-4700.0, dev_max=4700.0):.0f} W"
in str(_n20[0].get("message", "")))
# p1_enabled is what a homewizard_local install has - set by hand here for the
# same reason part 4 sets it, see freeze_rows().
_c20.p1_enabled = True
check("...and the red status row is up too, so the page and the notification "
"agree",
any("METER MAY BE FROZEN" in r["text"] for r in _c20.checks()))
# --------------------------------------------------------------------------- #
# 6b. SAFETY-20 - what the page says when the DEVICE is the ceiling (AC2)
# --------------------------------------------------------------------------- #
# ⚠️ THIS IS THE ACCEPTANCE CRITERION READ OFF THE RENDERED PAGE, NOT OFF THE
# SOURCE. The card is explicit that reading the code does not settle it, so
# every assertion below goes through the real `Controller.checks()` on a
# controller that was CONFIGURED with a device smaller than its `max_w` and
# then run - three real cycles, the real arbiter, the real write path.
print("what the page says when the device rating is the smaller ceiling")
# max_w 5000 on a 4700 W inverter - the ticket's own install. Covered transport,
# so the only question is what the ARMED row says.
_ctl_s, _rows_s = freeze_rows(2.0, -14.2, dev=(-4700.0, 4700.0))
# And the degenerate end: a device that can command nothing at all.
_ctl_z, _rows_z = freeze_rows(2.0, -14.2, dev=(0.0, 0.0))
print(f" max_w 5000 on a +-4700 W device: {_rows_s[0]['text'] if _rows_s else '(no row)'}")
print(f" a device with no commandable range: {_rows_z[0]['text'] if _rows_z else '(no row)'}")
check("a device smaller than max_w still gets exactly one freeze-detector row",
len(_rows_s) == 1)
check("...and the page does NOT print the max_w rail the command can never "
"reach - THE DEFECT, in one assertion",
bool(_rows_s)
and f"{rail_w(LIVE_INSTALL_MAX_W):.0f} W" not in _rows_s[0]["text"])
check("...it prints the rail the predicate actually uses",
bool(_rows_s)
and f"{rail_w(LIVE_INSTALL_MAX_W, dev_min=-4700.0, dev_max=4700.0):.0f} W"
in _rows_s[0]["text"])
check("...and it names the device range as the reason, since the operator "
"configured max_w and is owed the reason the guard is armed elsewhere",
bool(_rows_s) and "4700" in _rows_s[0]["text"]
and "max_w" in _rows_s[0]["text"])
# ⚠️ THE NUMBER IS TAKEN OFF THE ROW AND FED BACK INTO THE SHIPPED PREDICATE.
# Asserting the page against `rail_w(...)` alone proves the two agree, which a
# revert of BOTH to bare max_w also satisfies. What a revert cannot satisfy is
# this: the rail the page advertises has to be a magnitude the wire can carry,
# and the wire stops at the device rating.
_m = re.search(r"command is over (\d+(?:\.\d+)?) W", _rows_s[0]["text"]) if _rows_s else None
_page_rail = float(_m.group(1)) if _m else None
print(f" the page advertises a rail of {_page_rail} W against a device that "
f"stops at {_ctl_s.dev_max:.0f} W")
check("...the row states a rail in watts at all, so the parse below means "
"something", _page_rail is not None)
check("...and THE RAIL THE PAGE ADVERTISES IS ONE THE WIRE CAN ACTUALLY CARRY. "
"This is the whole ticket: 4750 W on a device that stops at 4700 W is a "
"guard that cannot fire, advertising that it can",
_page_rail is not None and _page_rail <= abs(_ctl_s.dev_max))
check("...and a command at exactly that advertised rail, with the meter frozen, "
"really does trip the shipped predicate the row is describing",
_page_rail is not None
and looks_frozen(3600, _page_rail, LIVE_INSTALL_MAX_W, cfg,
dev_min=_ctl_s.dev_min, dev_max=_ctl_s.dev_max))
check("...as an ok row - a guard armed at a lower rail is still armed, not a "
"warning", bool(_rows_s) and _rows_s[0]["ok"] and not _rows_s[0]["warn"])
check("a device with no commandable range gets exactly one row", len(_rows_z) == 1)
check("...and it says NOT COVERED - the rail is not merely low there, it is "
"0 W, which would be TRUE of every command including a parked one",
bool(_rows_z) and "NOT COVERED" in _rows_z[0]["text"])
check("...and it NEVER says armed",
bool(_rows_z) and "armed" not in _rows_z[0]["text"])
check("...flagged as a warning rather than a silent ok, like the uncovered "
"transport row it shares",
bool(_rows_z) and not _rows_z[0]["ok"] and _rows_z[0]["warn"])
check("...and the predicate agrees with the page rather than firing behind it",
not looks_frozen(3600, 0.0, LIVE_INSTALL_MAX_W, cfg,
dev_min=_ctl_z.dev_min, dev_max=_ctl_z.dev_max))
# AC3's other half, through the built object rather than through a literal: the
# opts dict does NOT carry meter_freeze_s, so this is the number an install that
# leaves the key at its config.yaml default actually lands on.
+7
View File
@@ -19,6 +19,13 @@ HANDOVER.md. An understated runtime reads as a hang.
`cycle_floor_s` is read from options with no lower bound in code, so a huge
value reproduces the pre-fix behaviour exactly. Every claim below is therefore
an A/B on one binary, not a comparison against a remembered old one.
⚠️ MUTATING THE MODULE THIS FILE GRADES? PURGE `__pycache__` FIRST - or run
`tools/mutation_run.sh`, which does. `python3 -B` alone does NOT save you: it
stops bytecode being WRITTEN, not a stale one being READ, and a size-preserving
edit reverted inside one second is invisible to CPython's staleness test. That
is TEST-15, and it has already turned one live mutation into a false survivor.
Read MUTATION.md before you report a survivor.
"""
import asyncio
+121 -1
View File
@@ -3,12 +3,24 @@
Walks a whole cycle in simulated time, which is the test the YAML version never
had - and it is exactly the phase transitions that a real cycle takes ten hours
to exercise once a month.
⚠️ MUTATING THE MODULE THIS FILE GRADES? PURGE `__pycache__` FIRST - or run
`tools/mutation_run.sh`, which does. `python3 -B` alone does NOT save you: it
stops bytecode being WRITTEN, not a stale one being READ, and a size-preserving
edit reverted inside one second is invisible to CPython's staleness test. That
is TEST-15, and it has already turned one live mutation into a false survivor.
Read MUTATION.md before you report a survivor.
"""
import dataclasses
import re
import sys
from datetime import datetime, timedelta, timezone
from pathlib import Path
from app.maintenance import CHARGE, DRAIN, HOLD, IDLE, MaintConfig, Maintenance
from app.maintenance import (
CHARGE, DRAIN, HOLD, IDLE, MAINT_OPTION_DEFAULTS, MaintConfig, Maintenance,
)
fails = []
@@ -104,6 +116,114 @@ print("disabled schedule")
m = Maintenance(MaintConfig(enabled=False), FakeStore())
check("disabled never starts", m.tick(t0, soc=80).phase == IDLE)
print("CFG-03: config.yaml is the source, this module is the only mirror")
# ⚠️ WHY THIS IS PINNED BY READING THE FILE. Before CFG-03 each maintenance
# default was written down three times - config.yaml's `options:` block,
# `opts.get(key, <literal>)` in main.py, and MaintConfig's dataclass defaults -
# and MAINT-04 proved they had already drifted (2000 shipped, 2500 in code). The
# fix is one source and one mirror; the mirror is only worth anything if drift
# from it is a CI failure rather than a comment, and a transcription of
# config.yaml into this file would just be a fourth place to disagree. So the
# shipped values are READ out of the file the Supervisor reads.
#
# Regex rather than PyYAML on purpose, for test_validate.py's reason: the add-on
# image installs py3-aiohttp and py3-paho-mqtt only, and a check that skips on
# ImportError is not a check.
HERE = Path(__file__).resolve().parent
_CFG_TEXT = (HERE / "config.yaml").read_text(encoding="utf-8")
_SCHEMA_AT = _CFG_TEXT.index("\nschema:")
def shipped_default(key):
"""The value under `options:` - the FIRST match, before `schema:`."""
m = re.search(rf"^ {key}: *(.+?) *$", _CFG_TEXT[:_SCHEMA_AT], re.M)
return None if m is None else m.group(1)
def schema_range(key):
"""`int(lo,hi)` under `schema:` -> (lo, hi); None if the key is absent."""
m = re.search(rf"^ {key}: *\w+\((-?[\d.]+),(-?[\d.]+)\) *$",
_CFG_TEXT[_SCHEMA_AT:], re.M)
return None if m is None else (float(m.group(1)), float(m.group(2)))
def as_number(text):
if text in ("true", "false"):
return 1.0 if text == "true" else 0.0
return float(text)
_ship = {k: shipped_default(k) for k in MAINT_OPTION_DEFAULTS}
print(f" config.yaml ships {_ship}")
check("every mirrored key is actually shipped in config.yaml's options: block",
all(v is not None for v in _ship.values()))
check("...and MAINT_OPTION_DEFAULTS reproduces each one exactly, so the mirror "
"is a copy of the source and not an opinion about it",
all(str(MAINT_OPTION_DEFAULTS[k]).lower() == _ship[k]
for k in MAINT_OPTION_DEFAULTS))
# ⚠️ THE OTHER DIRECTION MATTERS TOO. Equality alone would still pass if the
# mirror quietly stopped covering a key someone added to config.yaml, and the
# key nobody mirrors is exactly the key that gets a literal typed for it.
_shipped_keys = set(re.findall(r"^ (maintenance_[a-z_]+):", _CFG_TEXT[:_SCHEMA_AT],
re.M))
check(f"...and it covers EVERY maintenance_* option the file ships, so a ninth "
f"key cannot arrive unmirrored {sorted(_shipped_keys)}",
_shipped_keys == set(MAINT_OPTION_DEFAULTS))
# ⚠️ WHERE THE RANGE LIVES, ASSERTED RATHER THAN COMMENTED. The PM proofread on
# this card named a FOURTH declaration site of a different kind:
# `maintenance_charge_w: int(500,5000)` in the schema block. It is a BOUND, not
# a default, and the decision this card records is that bounds live in the
# schema block ONLY - the Supervisor enforces them and reads only that file, so
# a Python copy would be a place to disagree and nothing else. What that
# decision needs from a check is (a) every mirrored key really does have a
# schema entry, or the Supervisor drops the option and the add-on silently runs
# on the mirror instead of the operator's value, and (b) the shipped default
# lies INSIDE its own range, because a default the schema rejects is a config
# that cannot be re-entered once it is edited.
_ranged = {k: schema_range(k) for k in MAINT_OPTION_DEFAULTS}
check("every mirrored key is in the schema: block too - `bool` has no range, so "
"it is the one exception and it is named",
all(v is not None for k, v in _ranged.items()
if k != "maintenance_enabled")
and _ranged["maintenance_enabled"] is None)
_outside = {k: (as_number(_ship[k]), rng) for k, rng in _ranged.items()
if rng is not None and not rng[0] <= as_number(_ship[k]) <= rng[1]}
check(f"...and every shipped default sits inside its own schema range, so the "
f"Supervisor accepts the file it ships with {_outside or 'all inside'}",
not _outside)
# ⚠️ AND THE CONSUMERS MOVE WITH IT - checked as a RELATION, not against
# numbers. AC4 asks for the replacement to be broken and every consumer observed
# moving together. A number typed here would pass whether or not the derivation
# survived; `dataclasses.fields()` reads what the class actually defaulted to,
# so this can only pass while the class is still indexing the mirror.
_fields = {f.name: f.default for f in dataclasses.fields(MaintConfig)}
check(f"MaintConfig's field names are the option names minus the prefix, so a "
f"new field cannot miss the mirror by being spelt differently {sorted(_fields)}",
{f"maintenance_{n}" for n in _fields} == set(MAINT_OPTION_DEFAULTS))
check("...and every dataclass default IS the mirror's value - no literal "
"survives in the class that used to hold the third opinion",
all(float(d) == float(MAINT_OPTION_DEFAULTS[f"maintenance_{n}"])
for n, d in _fields.items()))
# from_options() is the only reader, so it is the only thing that can put a
# different number in front of main.py.
_from_empty = MaintConfig.from_options({})
check("...and from_options({}) - the sim/inject.py and test-suite path, the one "
"the Supervisor never takes and the only one the divergence was reachable "
"from - equals MaintConfig() exactly",
_from_empty == MaintConfig())
check("...while a supplied value still wins, or the mirror would be a ceiling "
"rather than a default",
MaintConfig.from_options({"maintenance_charge_w": 1234}).charge_w == 1234.0)
# ⚠️ `key in opts`, not truthiness: `false` and `0` are values an operator can
# set, and a truthy read would silently replace both with the default - this
# card's own bug in a different costume.
check("...and an explicit falsey value is honoured rather than defaulted away",
MaintConfig.from_options({"maintenance_start_hour": 0}).start_hour == 0
and MaintConfig.from_options({"maintenance_enabled": False}).enabled is False)
print()
print()
if fails:
print(f"{len(fails)} FAILED: {', '.join(fails)}")
+7
View File
@@ -8,6 +8,13 @@ Every assert here is a rule whose absence poisons something downstream: an
inverted sign inverts the control loop, a fabricated zero hides a dead meter, a
naive per-phase sum misbills the capacity tariff, and a plain mean of samples
computes the wrong quarter-hour figure whenever the telegram cadence changes.
⚠️ MUTATING THE MODULE THIS FILE GRADES? PURGE `__pycache__` FIRST - or run
`tools/mutation_run.sh`, which does. `python3 -B` alone does NOT save you: it
stops bytecode being WRITTEN, not a stale one being READ, and a size-preserving
edit reverted inside one second is invisible to CPython's staleness test. That
is TEST-15, and it has already turned one live mutation into a false survivor.
Read MUTATION.md before you report a survivor.
"""
import asyncio
+690 -13
View File
@@ -2,7 +2,7 @@
python3 test_peakguard.py
Ten parts. What each is for, and - where it matters - what it is deliberately
Eleven parts. What each is for, and - where it matters - what it is deliberately
NOT allowed to be tested at:
1. THE CONTROL LAW, `excess_w`, graded AWAY from the two points where it is
@@ -46,7 +46,25 @@ NOT allowed to be tested at:
capture, against a MODELLED PACK small enough that the guard's own 878 Wh
day would take it to the BMS cut-out - so the two worlds, before and after
this card, are run against each other rather than reasoned about.
10. MUTATION. Eleven one-line defeats of these two guards, each run against
10. SAFETY-25: THE LOOP, WHICH THIS FLOOR DOES NOT BOUND. A TRIPWIRE, not a
guarantee - it records a defect and goes red when the defect is fixed.
Part 11's mutation 13 has said in words since SAFETY-24 that ordinary
self-consumption can take the pack past `peak_soc_floor`; this part
replays a sustained-load evening through the SHIPPED control law, the
SHIPPED guard and the REAL arbiter and measures how far past. It also
sweeps `peak_soc_floor` over the whole schema range to show the answer
does not move by one part in ten thousand, and pins the four
operator-facing surfaces that now say so.
⚠️ THE REPLAY ALONE IS NOT THE TRIPWIRE, and believing it was is the
defect PR #31's reviewer found: `replay_loop()` hand-builds main.py's
claim list, so it is blind to any claim main.py ADDS - which is where a
loop-side floor would be built. 10f is what closes that. It pins the set
of claim sources `Controller.cycle()` can file, statically over its AST
and dynamically through real cycles swept over the whole SoC range, so a
ninth source takes this part red. A floor built inside `control.compute()`
or the guard instead moves 10a-10c's numbers directly, because the replay
drives both.
11. MUTATION. Eleven one-line defeats of these two guards, each run against
the checks above to show they are not vacuous.
------------------------------------------------------------------------------
@@ -72,6 +90,13 @@ Two days is also not thirty. AC 3's 95 %-over-30-days criterion is TARIFF-01's
and is still not met; `test_tariff.py`'s part 9 says so at length and this file
does not re-litigate it. What part 6 reports is the comparison that two days CAN
support: the same quarters, with and without the guard.
⚠️ MUTATING THE MODULE THIS FILE GRADES? PURGE `__pycache__` FIRST - or run
`tools/mutation_run.sh`, which does. `python3 -B` alone does NOT save you: it
stops bytecode being WRITTEN, not a stale one being READ, and a size-preserving
edit reverted inside one second is invisible to CPython's staleness test. That
is TEST-15, and it has already turned one live mutation into a false survivor.
Read MUTATION.md before you report a survivor.
"""
import asyncio
@@ -92,8 +117,9 @@ from app import peakguard
from app.arbiter import (
P_LOOP, P_MAINT_SHAPE, P_MAINTENANCE, P_PEAK, P_SAFETY, Claim, resolve,
)
from app.control import peak_at_risk
from app.control import Tuning, compute, peak_at_risk
from app.freeze import FreezeWatchdogConfig, looks_frozen, rail_w
from app import main as app_main
from app.main import Controller
from app.p1 import (
PLAUSIBLE_MAX_W, P1Ingest, QUARTER_S, QuarterAverager, make_sample,
@@ -162,12 +188,26 @@ def read_option(key: str):
def read_schema_max(key: str):
"""The schema's upper bound for `key` - `int(lo,hi)` -> hi."""
return _schema_bound(key, 1)
def read_schema_min(key: str):
"""The schema's lower bound for `key` - `int(lo,hi)` -> lo.
SAFETY-25's sweep needs BOTH ends: the argument there is that no value the
schema accepts changes the answer, and a sweep that only reached upwards
would leave "well, set it lower then" unanswered.
"""
return _schema_bound(key, 0)
def _schema_bound(key: str, which: int):
body = (HERE / "config.yaml").read_text(encoding="utf-8")
marker = body.index("\nschema:")
for line in body[marker:].splitlines():
st = line.strip()
if st.startswith(f"{key}:") and "(" in st and ")" in st:
return float(st[st.index("(") + 1:st.rindex(")")].split(",")[1])
return float(st[st.index("(") + 1:st.rindex(")")].split(",")[which])
return None
@@ -875,6 +915,11 @@ class _Hass:
def __init__(self):
self.writes = []
self.notifications = []
# SAFETY-25. The whole payload, not only the id. AC 3 is about what the
# operator READS, so a fixture that records only that a notification
# fired cannot grade it - TEST-06's finding on SAFETY-18's NOT COVERED
# row, one file across.
self.calls = []
async def limits(self, entity):
return (-LIVE_MAX_W, LIVE_MAX_W, 1.0)
@@ -888,8 +933,15 @@ class _Hass:
async def call(self, domain, service, data):
self.notifications.append(data.get("notification_id"))
self.calls.append(dict(data))
return True
def last_message(self, notification_id: str) -> str:
"""The body of the most recent notification with that id, or ""."""
bodies = [d.get("message", "") for d in self.calls
if d.get("notification_id") == notification_id]
return bodies[-1] if bodies else ""
def built(db_path, opts=None, store=None):
hass = _Hass()
@@ -1786,9 +1838,9 @@ check("...and both are in the schema: block too, or the Supervisor drops the "
"operator's value", sorted(_schema24) == sorted(PEAK_OPTION_DEFAULTS))
_val_src = (HERE / "app" / "validate.py").read_text(encoding="utf-8")
check("...and validate.py takes its fallbacks from that same mirror rather than "
"typing literals - which is the divergence its own rule 6 documents "
"(maintenance_charge_w 2000 there, 2500 in main.py), refused a second "
"outing here",
"typing literals - which is the divergence its own rule 6 used to "
"document (maintenance_charge_w 2000 in config.yaml, 2500 in main.py), "
"refused a second outing here and since closed by CFG-03",
"PEAK_OPTION_DEFAULTS" in _val_src
and not re.search(r'"peak_soc_floor"\s*,\s*[0-9]', _val_src)
and not re.search(r'"peak_soc_floor"\s*,\s*[0-9]', _mainsrc))
@@ -1807,9 +1859,617 @@ check("...and it is a SEPARATE KEY from maintenance_soc_floor, whose SHIPPED "
and "maintenance_soc_floor" not in PEAK_OPTION_DEFAULTS)
# ==============================================================================
print()
print("10. mutation: what defeats these guards, and which check bites")
print("10. SAFETY-25: the loop discharges past this floor, and how far past")
# ⚠️ WHAT THIS PART IS. It is a TRIPWIRE, in MAINT-04's manner, and it records a
# DEFECT rather than a guarantee. SAFETY-24's mutation 13 said in words that the
# grid-following loop can take the pack past `peak_soc_floor`; that sentence has
# now been written down four times across four tickets and never once measured.
# This part measures it on the committed capture and pins the number, so that:
#
# * the honesty half of SAFETY-25 - the config comment, DOCS.md, the operator
# notification and the status row - is anchored to a replayed figure rather
# than to a claim, and
# * THE DAY SOMEBODY BUILDS A LOOP-SIDE FLOOR, THIS GOES RED. That is the
# point. The exposure must not be able to change under a green suite; it has
# to be closed deliberately, and closing it means answering AC 2 and
# deleting or inverting these checks along with
# DECISIONS/SAFETY-25-loop-soc-floor.md's status - OPEN when this was
# written, DECIDED (Option A, deferred B) since 2026-09-02.
#
# ⚠️ AND IT IS 10f THAT MAKES THAT SENTENCE TRUE, NOT 10a-10c. The replay
# below hand-builds main.py's claim list, so on its own it is blind to a
# floor filed as a NEW CLAIM - the memo's own Option B, and PR #31's
# reviewer proved the blindness by building it: the whole suite stayed
# green. 10f pins the claim-source set so that shape goes red too. The two
# halves cover the two places a loop-side floor can be built: 10f for an
# arbiter claim in Controller.cycle(), 10a-10c for a clamp inside
# control.compute() or peakguard, which the replay drives directly.
#
# ⚠️ AND IT DRIVES THE SHIPPED CODE, not a transcription of it: control.compute()
# at the shipped tuning, peakguard.decide(), peakguard.claim() and
# arbiter.resolve(), in main.py's order. Break any of them and this part moves -
# which is what makes it a check rather than a paragraph. See the memo section 7
# for what is modelled and what is measured.
# The shipped tuning, READ from config.yaml rather than typed - the same rule as
# every other number in this file. A tuning transcribed here would grade a
# control law nobody ships.
LOOP_TUNING = Tuning(
gain=read_option("gain"), max_w=read_option("max_w"),
slew_w=read_option("slew_w"), deadband_w=read_option("deadband_w"),
step_w=int(read_option("step_w")), saturation_w=read_option("saturation_w"),
saturation_cycles=int(read_option("saturation_cycles")),
target_grid_w=read_option("target_grid_w"))
LOOP_MAX_W = float(LOOP_TUNING.max_w)
print(f" the shipped loop tuning, out of config.yaml: {LOOP_TUNING}")
# ⚠️ THE REFERENCE PACK, DERIVED FROM THE THREE HARDWARE NUMBERS THIS REPOSITORY
# ALREADY STATES, not from a rounded kWh figure typed here. peakguard.py's
# PEAK_OPTION_DEFAULTS comment says "300 Ah at 51.2 V with DoD 90 - 13.8 kWh
# usable"; that sentence is asserted below, so if the reference pack ever
# changes this fixture goes red instead of quietly modelling the old one.
REF_PACK_WH = 300.0 * 51.2 * 0.90
_pg_src = (HERE / "app" / "peakguard.py").read_text(encoding="utf-8")
check("the modelled pack is the repository's own reference pack, and the source "
"still says so - 300 Ah at 51.2 V with DoD 90. A fixture whose hardware "
"assumption drifts away from the module it grades is a fixture measuring "
"a machine nobody owns",
"300 Ah at 51.2 V with DoD 90" in _pg_src
and abs(REF_PACK_WH - 13800.0) < 100.0)
def evening(h0: int, h1: int):
"""The rows of 2026-08-20's capture inside [h0, h1) UTC, as they were.
`h1` may be 24, meaning "to the end of the capture" - the file runs to
21:59:56 UTC, which is local midnight.
"""
lo = datetime(2026, 8, 20, h0, tzinfo=timezone.utc)
hi = (datetime(2026, 8, 21, tzinfo=timezone.utc) if h1 >= 24
else datetime(2026, 8, 20, h1, tzinfo=timezone.utc))
out = []
for line in gzip.open(BAD, "rt", encoding="utf-8"):
row = json.loads(line)
t = datetime.fromisoformat(row["t"])
if lo <= t < hi:
out.append((t, float(row["w"])))
return out
def replay_loop(window, *, start_soc, soc_floor, usable_wh=REF_PACK_WH):
"""The GRID-FOLLOWING LOOP over a window, closed-loop, with a modelled pack.
part 6's `replay()` models the PEAK GUARD's discharge and pins the SoC above
the floor on purpose - it is grading SAFETY-07. This one models the thing
SAFETY-07 never claimed to bound: ordinary self-consumption.
The cycle is main.py's, in main.py's order and with main.py's claims:
peakguard.decide(...) the guard sees this cycle's SoC
control.compute(...) the loop sees the meter minus the battery
arbiter.resolve([supervised, loop@P_LOOP, peakguard.claim(...)])
⚠️ THE ARBITER IS IN THE PATH AND THAT IS THE WHOLE POINT. Cutting it out
and reading `Decision.target_w` directly would measure the control law and
prove nothing about the floor: the question is whether the guard's `lo`
claim, filed at P_PEAK against a loop winning at P_LOOP, can cap the
discharge. It cannot, and it is `resolve()` that has to say so.
The pack model is part 9's, one line for one line - SoC falls by the
DELIVERED discharge integrated over the real telegram stamps, the BMS is a
hard cut at `bms_soc_floor`, and nothing recharges inside the window.
`start_soc` is the one number the captures cannot supply (they carry meter
power only), and it is derived from the shipped option rather than picked.
"""
ing = P1Ingest(phases=1, max_age_s=MAX_HOLD_S)
store = fresh_store(f"s25-{window[0][0]:%H%M}-{soc_floor:.0f}-{start_soc:.0f}")
tracker = PeakTracker(store, cap_w=CAP_W)
batt = 0.0 # delivered discharge, W (positive)
prev_w = i_w = 0.0
sat = 0
soc = float(start_soc)
min_soc = soc
wh = 0.0
prev_t = next_cycle = None
cycles = below = below_discharging = limited = limited_discharging = 0
at_bms = guard_floors = 0
max_granted = 0.0
for t, w in window:
if prev_t is not None:
dwh = batt * (t - prev_t).total_seconds() / 3600.0
wh += dwh
soc = max(0.0, soc - 100.0 * dwh / usable_wh)
min_soc = min(min_soc, soc)
prev_t = t
ing.submit(sample(t, w - batt))
tracker.sync(ing)
if next_cycle is not None and t < next_cycle:
continue
next_cycle = t + timedelta(seconds=CYCLE_S)
cycles += 1
d = decide(PeakTracker.project(ing.averager, t), batt_w=batt,
cap_w=CAP_W, reading=tracker.peak(t),
achievable_w=LOOP_MAX_W, max_hold_s=MAX_HOLD_S, soc=soc,
soc_floor=soc_floor, frozen=False)
dec = compute(prev_w, w - batt, batt, LOOP_TUNING, sat_count=sat,
i_w=i_w)
sat, i_w = dec.sat_count, dec.i_w
claims = [Claim.limit("supervised", P_SAFETY, -LOOP_MAX_W, LOOP_MAX_W,
"max_w"),
Claim.set("loop", P_LOOP, dec.target_w, dec.reason)]
pc = peakguard.claim(d)
if pc is not None:
claims.append(pc)
if pc.lo > 0.0:
guard_floors += 1
r = resolve(claims)
prev_w = r.target_w
# THE BMS, MODELLED - part 9's line, for part 9's reason. The pack's own
# cut-out is a real floor and it works; the finding is that it is the
# only one.
if soc <= BMS_FLOOR:
at_bms += 1
batt = 0.0
else:
batt = max(0.0, r.target_w)
max_granted = max(max_granted, batt)
if soc < soc_floor:
below += 1
below_discharging += 1 if batt > 0.0 else 0
if d.floor_limited:
limited += 1
limited_discharging += 1 if batt > 0.0 else 0
return {"cycles": cycles, "wh": wh, "min_soc": min_soc, "end_soc": soc,
"below": below, "below_discharging": below_discharging,
"limited": limited, "limited_discharging": limited_discharging,
"at_bms": at_bms, "guard_floors": guard_floors,
"max_granted": max_granted}
# --- 10a. the sustained-load evening ----------------------------------------
# 19:00-22:00 UTC is 21:00-24:00 local: the sun is down, the PV is off, and the
# house is simply drawing. Chosen for that property and CHECKED for it below -
# a window with export in it would let the loop recharge and the replay would be
# measuring something else.
EVE = evening(19, 24)
EVE_W = [w for _, w in EVE]
print(f" the evening of 2026-08-20, {EVE[0][0]:%H:%M}-{EVE[-1][0]:%H:%M} UTC: "
f"{len(EVE)} telegrams, mean {sum(EVE_W) / len(EVE_W):.0f} W, "
f"min {min(EVE_W):.0f} W, max {max(EVE_W):.0f} W")
check("the window really is a SUSTAINED-LOAD evening and not a quiet one - "
"every telegram in it is an IMPORT, so the pack has nowhere to recharge "
"from and the loop is discharging for the whole three hours",
min(EVE_W) > 0.0 and len(EVE) > 1500)
# ⚠️ ONE POINT ABOVE THE FLOOR, DERIVED FROM THE SHIPPED OPTION. This is the
# state an operator who has read `peak_soc_floor: 20` believes is protected: the
# pack is above the number they set. It is the only fixture parameter the
# captures cannot supply, and it is taken from config.yaml rather than chosen.
EVE_START = SOC_FLOOR + 1.0
EV = replay_loop(EVE, start_soc=EVE_START, soc_floor=SOC_FLOOR)
print(f" the reference pack ({REF_PACK_WH:.0f} Wh usable) starting at "
f"{EVE_START:.0f} %, one point above peak_soc_floor {SOC_FLOOR:.0f} %:")
print(f" ends at {EV['end_soc']:.1f} %, low-water {EV['min_soc']:.1f} %, "
f"{EV['wh']:.0f} Wh delivered by the LOOP over {EV['cycles']} cycles")
print(f" {EV['below']} cycles with the pack under peak_soc_floor, "
f"{EV['below_discharging']} of them still discharging; "
f"{EV['at_bms']} at the BMS cut-out; the guard filed a floor on "
f"{EV['guard_floors']}")
check(f"THE FINDING, REPLAYED. One sustained-load evening takes the pack from "
f"above peak_soc_floor to the pack's own BMS cut-out - "
f"{EVE_START:.0f} % -> {EV['end_soc']:.1f} % against a "
f"{BMS_FLOOR:.0f} % cut-out - and the EMS floor an operator set is not "
f"what stopped it",
EV["min_soc"] <= BMS_FLOOR + 0.05 and EV["at_bms"] > 0)
check("...and it is not one cycle of overshoot past the floor either: the loop "
"goes on delivering discharge for hundreds of cycles with the pack "
"already below the number the operator configured",
EV["below_discharging"] > 100 and EV["below"] > EV["below_discharging"])
check("...and the peak guard is not involved at all. It never files a floor on "
"this evening, because 830 W of house load never projects a quarter over "
"the 3500 W ceiling - so `peak_soc_floor` is not merely too weak here, it "
"is never consulted", EV["guard_floors"] == 0 and EV["limited"] == 0)
# --- 10b. and it is a BEHAVIOUR, not a config value -------------------------
# ⚠️ THE SWEEP IS THE ARGUMENT. "Raise peak_soc_floor" is the first thing anyone
# reading the option name would try, so the check is not that it is insufficient
# - it is that it does NOTHING, at any value the schema will accept, to four
# decimal places. Both ends of the schema range are swept rather than a
# comfortable middle.
SOC_SCHEMA_LO = float(read_schema_min("peak_soc_floor"))
SOC_SCHEMA_HI = float(read_schema_max("peak_soc_floor"))
SWEEP_FLOORS = [SOC_SCHEMA_LO, BMS_FLOOR + 1.0, SOC_FLOOR, SOC_SCHEMA_HI]
SWEPT = [(f, replay_loop(EVE, start_soc=EVE_START, soc_floor=f))
for f in SWEEP_FLOORS]
for f, res in SWEPT:
print(f" peak_soc_floor {f:5.0f} % -> ends at {res['end_soc']:.4f} %,"
f" {res['wh']:.2f} Wh out, guard floors {res['guard_floors']}")
check(f"the exposure is a BEHAVIOUR, NOT A CONFIG VALUE - the same evening ends "
f"at the same state of charge at every peak_soc_floor the schema accepts "
f"({SOC_SCHEMA_LO:.0f}..{SOC_SCHEMA_HI:.0f} %), to four decimal places. "
f"This is AC 4's sentence, measured: the option an operator would reach "
f"for cannot move this number by any amount at all",
len({round(res["end_soc"], 4) for _, res in SWEPT}) == 1
and len({round(res["wh"], 4) for _, res in SWEPT}) == 1)
# ⚠️ THE SWEEP DELIBERATELY OVERRUNS WHAT VALIDATE WOULD ACCEPT. Its low end is
# the SCHEMA's, and rule 8 refuses anything at or below `bms_soc_floor`, so a
# start at 5 % is not a configuration an operator could boot. Including it is the
# point: it closes "you swept only the legal band" without leaving the reader to
# wonder what happens outside it. The band that IS startable is bounded below by
# rule 8, and BMS_FLOOR + 1 is its first member, which is in the sweep too.
check("...and the sweep spans the whole schema range, rule 8's refused low end "
"included, so 'a legal value would have worked' is closed off rather "
"than left open. The first STARTABLE floor - one point above "
"bms_soc_floor - is swept as well, and lands on the same number",
SOC_SCHEMA_HI >= 60.0 and SOC_SCHEMA_LO <= BMS_FLOOR
and (BMS_FLOOR + 1.0) in SWEEP_FLOORS
and len([f for f in SWEEP_FLOORS if f > BMS_FLOOR]) >= 3)
# --- 10c. the two states in the SAME cycle ----------------------------------
# The evening never engages the guard, so it cannot show the sharpest form of
# the finding: the status page saying FLOOR-LIMITED while the pack empties. The
# same day's high-load block can, and it is the same capture and the same code.
HOT = evening(15, 17)
HOT_R = replay_loop(HOT, start_soc=SOC_FLOOR - 1.0, soc_floor=SOC_FLOOR)
print(f" the same day's high-load block "
f"{HOT[0][0]:%H:%M}-{HOT[-1][0]:%H:%M} UTC, pack started one point BELOW "
f"the floor:")
print(f" {HOT_R['limited']} cycles reporting PEAK GUARD FLOOR-LIMITED, "
f"{HOT_R['limited_discharging']} of them with the loop simultaneously "
f"granted discharge (max {HOT_R['max_granted']:.0f} W)")
check("THE ASYMMETRY, ON REAL DATA. On every cycle where the guard reports "
"FLOOR-LIMITED - 'commanding no forced discharge' on the status page and "
"in the operator's notification - the arbiter is at the same instant "
"granting the LOOP a discharge. A `lo` limit cannot cap a discharge, so "
"the guard's floor and the pack emptying are not alternatives; they "
"happen together",
HOT_R["limited"] > 10
and HOT_R["limited_discharging"] == HOT_R["limited"]
and HOT_R["max_granted"] > 0.0)
check("...which is why SAFETY-24's floor could not be widened into this one, "
"and why the fix is not a bigger number. Recorded in "
"DECISIONS/SAFETY-25-loop-soc-floor.md, where AC 2 was DECIDED on "
"2026-09-02: Option A, the BMS stays the only backstop, and the "
"loop-side reserve is DEFERRED to ALLOC-01 - so this replay is not a "
"pending exposure but the RECORDED behaviour, and part 10 stays as its "
"tripwire", HOT_R["min_soc"] <= BMS_FLOOR + 0.05)
# --- 10d. the trap in the obvious fix, checked rather than asserted ---------
# ⚠️ THE MEMO'S CENTRAL ENGINEERING CLAIM, RUN THROUGH THE REAL ARBITER. The
# first shape anyone reaches for is a `hi` limit on the loop - and filed while
# the peak guard is asking for a positive floor it is `lo > hi`, which
# arbiter.py resolves to 0 W: THE BATTERY PARKED, in the one quarter of the
# month that sets the bill. That is the same crossing-limits hazard
# shaping_suspended() already exists to avoid, and it is why the memo's Option B
# carries an ORDERING RULE rather than a number.
_RESERVE_HI = Claim.limit("reserve", P_LOOP, hi=0.0, reason="loop SoC floor")
_naive = resolve(SAFE + [Claim.set("loop", P_LOOP, 1800.0, "grid"),
peakguard.claim(d_ok), _RESERVE_HI])
_ordered = resolve(SAFE + [Claim.set("loop", P_LOOP, 1800.0, "grid"),
lc, _RESERVE_HI])
print(f" a naive loop reserve while the guard wants a floor: "
f"{_naive.explain()}")
print(f" the same reserve while the guard is floor-limited: "
f"{_ordered.explain()}")
check("a loop-side `hi` reserve filed while the peak guard is asking for a "
"POSITIVE floor is a CONTRADICTION and parks the battery at 0 W - so the "
"obvious shape of AC 2 has a trap in it, and this is it, run rather than "
"described", _naive.contradiction and near(_naive.target_w, 0.0))
check("...and the ordering the memo proposes removes it: with "
"loop_soc_floor <= peak_soc_floor the guard is ALREADY floor-limited "
"wherever the reserve binds, so it files lo = 0, and lo == hi == 0 "
"resolves to a clean 0 W with no contradiction",
not _ordered.contradiction and near(_ordered.target_w, 0.0)
and near(lc.lo, 0.0) and peakguard.claim(d_ok).lo > 0.0)
# --- 10e. the honesty half, pinned to the shipped text ----------------------
# ⚠️ ASSERT THE STRING, NOT THE INTENT - TEST-06's lesson on SAFETY-18's NOT
# COVERED row, which was untested for exactly this reason: the one branch that
# exists to tell an operator what a guard does NOT cover is the one nothing
# grades. These four surfaces are the whole of AC 3, and each is checked where
# it actually renders.
_cfg_src = (HERE / "config.yaml").read_text(encoding="utf-8")
_docs_src = (HERE / "DOCS.md").read_text(encoding="utf-8")
_memo = HERE / "DECISIONS" / "SAFETY-25-loop-soc-floor.md"
check("config.yaml says next to the option itself that peak_soc_floor bounds "
"the peak guard only and is not a pack-wide reserve - the operator edits "
"this file, so it is the first place the scope has to be true",
"BOUNDS THE PEAK GUARD ONLY" in _cfg_src
and "NOT A PACK-WIDE RESERVE" in _cfg_src.upper()
and "bms_soc_floor) stops it" in _cfg_src)
check("...and DOCS.md says it in the options table AND in the section, with the "
"replayed evening rather than an assurance",
"not a pack-wide reserve" in _docs_src
and "IT BOUNDS THE PEAK GUARD ONLY" in _docs_src
and "SAFETY-25" in _docs_src)
# ⚠️ THE DECISION LANDED (2026-09-02, Option A) AND THIS CHECK MOVED WITH IT.
# It used to pin "Status: OPEN. This is a memo, not a decision." - the memo being
# HONEST that AC 2 was unanswered. AC 2 is answered now, so the same check pins
# the same property in its new form: the memo states WHICH option, WHEN, and its
# REVISIT TRIGGER, and it still carries the options and the recommendation
# UNCHANGED. A memo that recorded the verdict and deleted the reasoning would be
# the failure this is guarding against, which is why "Recommendation" and both
# rejected options are still asserted here rather than only the status line.
_memo_txt = _memo.read_text(encoding="utf-8")
check("...and the decision memo AC 1 asks for is COMMITTED, records AC 2 as "
"DECIDED with a date, an option and a revisit trigger, and STILL carries "
"the options analysis and the recommendation that were put to the owner",
_memo.exists()
and "Status: DECIDED 2026-09-02 — Option A." in _memo_txt
and "ALLOC-01" in _memo_txt
and "Recommendation" in _memo_txt
and "### Option A" in _memo_txt and "### Option B" in _memo_txt)
check("...and it says plainly that part 10f - the pin that made SAFETY-25 "
"mergeable - is a SCALAR SoC sweep against a single-series capture and "
"so cannot express two packs. The tripwire's own limits belong in the "
"memo that leans on it, or the next reader merges a two-pack reserve on "
"a green check that cannot see the failure",
"10f" in _memo_txt and "SAFETY-27" in _memo_txt
and "cannot express two packs" in _memo_txt.lower())
check("...and DOCS.md sends the reader to it rather than leaving the open "
"question implicit",
"DECISIONS/SAFETY-25-loop-soc-floor.md" in _docs_src)
# The two OPERATOR-FACING surfaces, rendered by the real Controller rather than
# grepped: the status row and the notification body are what a human reads at
# the moment the guard stops, and a scope sentence that lives only in a source
# comment is a scope sentence the operator never sees.
c25, hass25, NET25, _ = wired_over_limit(
TMP / "soc25.db", LIVE_MAX_W * 0.3, soc=SOC_FLOOR - 1.0)
rows25 = [r for r in c25.checks() if "peak guard" in r["text"].lower()]
print(" status row: " + (rows25[0]["text"] if rows25 else "(none)"))
check("the STATUS PAGE row for a floor-limited guard says the floor bounds the "
"guard only and that self-consumption may keep discharging below it. "
"Without that sentence the page implies a pack-wide reserve at the exact "
"moment the replay above says the loop is still emptying the pack",
len(rows25) == 1
and "PEAK GUARD FLOOR-LIMITED" in rows25[0]["text"]
and "BOUNDS THE PEAK GUARD ONLY" in rows25[0]["text"].upper()
and "not a pack-wide reserve" in rows25[0]["text"]
and "BMS cut-out" in rows25[0]["text"])
# ⚠️ THE ROW KEEPS THE WHOLE SENTENCE; THE BANNER DOES NOT. status_payload()
# renders the first not-ok/not-warn row as the page headline, so before this the
# loudest element on the page was the same 550-character paragraph the row three
# lines below repeats verbatim. The scope wording is not weakened anywhere it
# matters - it is the ROW that an operator reads to learn what the floor bounds,
# and the row is asserted in full above.
_pay25 = c25.status_payload()
print(f" banner ({len(_pay25['banner'])} chars): {_pay25['banner']}")
# The guard's own line, which the banner has always carried and which is not
# this card's to shorten: `explain()` is SAFETY-24's sentence about a quarter
# that is going over the ceiling.
_expl25 = rows25[0]["text"].split(". NOTE:")[0]
check("the NOT READY banner is the guard's own line plus a SHORT scope tag - "
"under 90 characters of it - and NOT the row's whole paragraph repeated "
"at the top of the page. A headline that is a paragraph is a headline "
"nobody reads, and this one is followed three lines later by the same "
"text verbatim",
_pay25["level"] == "bad"
and _pay25["banner"].startswith("NOT READY")
and _expl25 in _pay25["banner"]
and "BOUNDS THE PEAK GUARD ONLY" in _pay25["banner"].upper()
and "not a pack-wide reserve" not in _pay25["banner"]
and len(_pay25["banner"]) - len(_expl25) < 90)
check("...and shortening the banner did NOT shorten the row: the full AC 3 "
"sentence is still what the checks list carries, which is the surface the "
"operator reads to find out what the floor does not bound",
len(rows25[0]["text"]) > 300
and "not a pack-wide reserve" in rows25[0]["text"]
and "BMS cut-out" in rows25[0]["text"])
_body25 = hass25.last_message("goodwe_peak_soc_floor")
print(f" notification body tail: ...{_body25[-180:]}")
check("...and so does the persistent notification, which outlives the page and "
"is the thing an operator reads on a phone at 19:00. It names what has "
"stopped - the guard buying a lower bill - and what has not",
"peak_soc_floor bounds THE PEAK GUARD ONLY" in _body25
and "not a" in _body25 and "pack-wide reserve" in _body25
and "BMS cut-out" in _body25)
# --- 10f. THE CLAIM-SOURCE SET, PINNED --------------------------------------
# ⚠️ THIS IS WHAT MAKES 10a-10c A TRIPWIRE RATHER THAN A SNAPSHOT, and it is
# here because the first cut of this part did NOT have it and the tripwire
# sentence above was therefore FALSE. `replay_loop()` hand-builds main.py's
# claim list as a literal `[supervised, loop, peakguard.claim(...)]`, so it is
# structurally BLIND to any claim main.py ADDS - which is exactly where AC 2
# would be built. PR #31's reviewer proved it by building the fix: they
# implemented the memo's own Option B in main.py - a
# `Claim.limit("reserve", P_LOOP, hi=0.0)` filed under a `loop_soc_floor` - and
# the whole suite stayed GREEN, this part included, while mutation 13 went on
# printing "NOTHING PREVENTS IT, ON PURPOSE" and the same 21 % -> 10.0 % on a
# tree where something DID prevent it. Pushed to an always-binding 95 % reserve
# it was still green here. That is this repository's named failure mode - a
# check that observed something other than what it claimed to observe - and it
# had been committed as a guarantee in four places.
#
# So the MODEL is now pinned to the MODELLED THING, two ways, because the two
# fail differently:
#
# * STATICALLY, over `Controller.cycle()`'s own AST. Every `claims.append(...)`
# in it must be one this scan can read, and the set of sources it can file
# must be exactly the eight below. A ninth - a `reserve`, whatever it ends
# up called - takes this red on the line it is written, in every
# configuration, whether or not any fixture here reaches the state that
# files it.
# * DYNAMICALLY, through REAL `Controller.cycle()`s with main.py's OWN
# `resolve` spied, swept over the WHOLE state-of-charge range in the two
# states 10a-10c replay. The static scan pins the NAMES; this pins that the
# names actually reach the arbiter and that nothing else does. A claim that
# appears only at a low SoC - precisely the shape a loop-side floor has -
# cannot hide from a sweep that visits 0 %.
#
# The third way a loop-side floor could be built is INSIDE `control.compute()`
# or the guard (the memo's Option D), and that needs nothing new here: the
# replay above drives both, so it moves the numbers in 10a-10c directly.
# The whole inventory of claim sources main.py can file, in any configuration.
# ⚠️ ADDING TO THIS SET IS A DELIBERATE ACT. If you are here because you added a
# claim to `Controller.cycle()` and this went red, that is the tripwire working:
# read DECISIONS/SAFETY-25-loop-soc-floor.md and update part 10 and mutation 13
# rather than this line alone. ⚠️ AC 2 IS DECIDED (2026-09-02, Option A) AND
# THAT DOES NOT RETIRE THIS SET - Option B is DEFERRED, not rejected, and
# "deferred" is exactly the state in which a ninth source gets built by
# accident. Its revisit trigger is ALLOC-01, under which the reserve becomes a
# PER-INVERTER interval at the allocator rather than a ninth claim here.
CLAIM_SOURCES = {"device", "supervised", "failsafe", "safety", "peak",
"arbitrage", "maintenance", "loop"}
# The two appends that file a claim BUILT ELSEWHERE in the method. Named here so
# that a THIRD such indirection reads as an unrecognised append rather than as a
# silent gap in the scan.
CLAIM_BUILDERS = {"peak_claim": "peak", "arb_claim": "arbitrage"}
_main_tree = ast.parse((HERE / "app" / "main.py").read_text(encoding="utf-8"))
_cycle_def = next(
f
for cls in ast.walk(_main_tree)
if isinstance(cls, ast.ClassDef) and cls.name == "Controller"
for f in cls.body
if isinstance(f, (ast.FunctionDef, ast.AsyncFunctionDef)) and f.name == "cycle")
def claim_source(node):
"""The source string an appended expression files, or None if unreadable."""
if (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute)
and isinstance(node.func.value, ast.Name)
and node.func.value.id == "Claim"
and node.func.attr in ("set", "limit") and node.args
and isinstance(node.args[0], ast.Constant)
and isinstance(node.args[0].value, str)):
return node.args[0].value
if isinstance(node, ast.Name):
return CLAIM_BUILDERS.get(node.id)
return None
_appends = [n for n in ast.walk(_cycle_def)
if isinstance(n, ast.Call) and isinstance(n.func, ast.Attribute)
and n.func.attr == "append" and isinstance(n.func.value, ast.Name)
and n.func.value.id == "claims" and len(n.args) == 1]
_filed = [claim_source(n.args[0]) for n in _appends]
print(f" main.py Controller.cycle() files {len(_appends)} claims, from "
f"{len(CLAIM_SOURCES)} sources: "
f"{', '.join(sorted({s for s in _filed if s}))}")
check("every `claims.append(...)` in main.py's cycle is one this scan can READ "
"- a claim filed through a shape it cannot parse has to fail here rather "
"than be counted as nothing, which is how a scan like this goes quietly "
"vacuous", len(_appends) >= 10 and None not in _filed)
check("...and the sources that cycle can file are EXACTLY these eight. THIS is "
"what makes part 10 a tripwire: replay_loop() hand-builds the claim list, "
"so it cannot see a claim main.py adds - and a loop-side SoC reserve is a "
"NINTH source. Filing one takes this line red on the line it is written",
set(_filed) == CLAIM_SOURCES)
def cycle_claims(run):
"""The claim list main.py's OWN `resolve` was handed, from a real cycle.
⚠️ SPIED AT `app.main.resolve`, not reconstructed. The point of the whole
sub-part is that this file must stop believing its own transcription of
main.py's claim list, so the observation has to be taken from main.py's
call site and nowhere else.
"""
seen = []
real = app_main.resolve
def _spy(claims):
seen.append(list(claims))
return real(claims)
app_main.resolve = _spy
try:
out = run()
finally:
app_main.resolve = real
return out, (seen[-1] if seen else [])
def run_cycle(ctl):
asyncio.get_event_loop_policy().new_event_loop().run_until_complete(
ctl.cycle())
return ctl
# The IDLE state, which is what 10a and 10b replay: a sustained house load well
# under the ceiling, so the guard files nothing and the loop is alone with the
# safety limits. One controller, cycled once per state of charge - the load is
# the evening's own mean, so this is the evening's cycle at every SoC it passes
# through and at every SoC it does not.
EVE_MEAN_W = sum(EVE_W) / len(EVE_W)
c_src, _ = built(TMP / "sources.db")
c_src.auto, c_src.batt, c_src.soc = True, 0.0, 100.0
_blk_src = datetime.fromtimestamp(
int(datetime.now(timezone.utc).timestamp() // QUARTER_S) * QUARTER_S,
timezone.utc)
for _i in range(0, int((datetime.now(timezone.utc)
- _blk_src).total_seconds()) + 1, 5):
c_src.p1.submit(sample(_blk_src + timedelta(seconds=_i), EVE_MEAN_W))
c_src.grid = EVE_MEAN_W
# ⚠️ THE WHOLE RANGE, INCLUDING 0 %. A reserve conditioned on a low pack is
# invisible to a sweep that starts at a comfortable one, and "conditioned on a
# low pack" is the definition of the claim this is watching for.
SRC_SWEEP = sorted({float(s) for s in range(0, 101, 5)}
| {BMS_FLOOR, SOC_FLOOR, EVE_START, EV["end_soc"]})
IDLE_SRC = {}
for _soc in SRC_SWEEP:
c_src.soc = _soc
_, _cl = cycle_claims(lambda: run_cycle(c_src))
IDLE_SRC[_soc] = frozenset(c.source for c in _cl)
IDLE_SETS = set(IDLE_SRC.values())
print(f" a real idle cycle at {len(SRC_SWEEP)} states of charge "
f"({min(SRC_SWEEP):.0f}..{max(SRC_SWEEP):.0f} %) files: "
+ " | ".join(sorted(", ".join(sorted(s)) for s in IDLE_SETS)))
check("a REAL Controller.cycle() in the state 10a and 10b replay - auto, P1 "
"healthy, the guard idle under an 830 W load - hands the arbiter exactly "
"{device, supervised, loop}, at EVERY state of charge from 0 to 100 %. "
"Not one source appears at a low pack that does not appear at a full one, "
"which is the claim a loop-side reserve would break",
IDLE_SETS == {frozenset({"device", "supervised", "loop"})}
and len(SRC_SWEEP) >= 21 and min(SRC_SWEEP) == 0.0)
# The ENGAGED state, which is what 10c replays: the guard over its ceiling and
# floor-limited on an empty pack. Two states of charge, both under the floor,
# because that is the band a loop-side reserve would be conditioned on.
HOT_SRC = set()
for _soc in (SOC_FLOOR - 1.0, 0.0):
(c_h, _h, _n, _r), _cl = cycle_claims(
lambda: wired_over_limit(TMP / f"sources-hot-{_soc:.0f}.db",
LIVE_MAX_W * 0.3, soc=_soc))
HOT_SRC.add(frozenset(c.source for c in _cl))
_hot_limited = c_h.peak_guard is not None and c_h.peak_guard.floor_limited
print(" a real FLOOR-LIMITED cycle files: "
+ " | ".join(sorted(", ".join(sorted(s)) for s in HOT_SRC)))
check("...and with the guard actually FLOOR-LIMITED - 10c's state, on an empty "
"pack - the set gains the guard's own claim and NOTHING ELSE. So the "
"three sources replay_loop() hand-builds are the whole cycle in both of "
"the states it replays, rather than a subset of it that happened to "
"match", _hot_limited
and HOT_SRC == {frozenset({"device", "supervised", "loop", "peak"})})
# THE FOLD, stated rather than assumed. replay_loop() files ONE `supervised`
# limit where main.py files two - `device`, from the inverter's own reported
# range, and `supervised`, from `max_w`. Both are symmetric P_SAFETY limits, so
# the tighter one binds and modelling them as one is exact, not an
# approximation. Checked on the claims the real cycle actually filed.
_safety_lims = [c for c in _cl if c.source in ("device", "supervised")]
check("...and replay_loop() folding main.py's TWO P_SAFETY rating limits into "
"its one `supervised` claim is exact rather than convenient: both are "
"symmetric LIMIT claims at P_SAFETY, so the tighter of the pair binds and "
"one claim at the tighter bound is the same constraint",
len(_safety_lims) == 2
and all(c.kind == "limit" and c.priority == P_SAFETY
and near(c.lo, -c.hi) and c.hi > 0.0 for c in _safety_lims)
and near(LOOP_MAX_W, read_option("max_w")))
# ==============================================================================
print()
print("11. mutation: what defeats these guards, and which check bites")
# Each entry re-implements ONE defeat and reports whether a check above would
# have gone red. The last row is the honest one: it does NOT bite, and saying so
@@ -1922,13 +2582,28 @@ MUT.append(("floor-limited reported but the floor still filed at `wanted`",
# 13. THE SECOND ONE THAT DOES NOT BITE, and it is a real limitation rather than
# a defect. Stated, because the alternative is a reader believing this card
# bounds more than it does.
#
# ⚠️ SAFETY-25 CHANGED WHAT "NOT CAUGHT" MEANS HERE, AND ONLY THAT. Nothing
# PREVENTS it - the code is unchanged and a `lo` limit still cannot cap a
# discharge - but part 10 now MEASURES it on the committed capture and 10f
# PINS THE CLAIM-SOURCE SET around it, so the exposure can no longer change
# size under a green suite: file the reserve and 10f goes red on the line
# it is written. That is the whole difference between an uncaught mutation
# and an unrecorded one. ⚠️ THE PIN IS LOAD-BEARING FOR THIS ROW. Without
# it this rationale was FALSE - PR #31's reviewer built the memo's Option B
# and this row went on printing "NOTHING PREVENTS IT" under a green suite.
_loop_unbounded = near(r_disch.target_w, 1800.0, 1e-9)
MUT.append(("the grid-following loop discharging past this floor",
not _loop_unbounded,
"NOTHING, ON PURPOSE - this card bounds THE PEAK GUARD's forced "
"discharge, the thing SAFETY-07 introduced. SAFETY-18's finding "
"that the loop itself has no SoC guard is still open, and a `lo` "
"limit is structurally incapable of closing it"))
"NOTHING PREVENTS IT, ON PURPOSE - this card bounds THE PEAK "
"GUARD's forced discharge, the thing SAFETY-07 introduced. A `lo` "
"limit is structurally incapable of closing SAFETY-18's finding "
"that the loop has no SoC guard. SAFETY-25 part 10 now MEASURES "
"it: one sustained-load evening, "
f"{EVE_START:.0f} % -> {EV['end_soc']:.1f} % on the reference pack, "
f"identical at every peak_soc_floor the schema accepts - and 10f "
f"pins the claim-source set, so building the floor takes this "
f"part RED instead of leaving this row quietly stale"))
for label, caught, where in MUT:
print(f" {'caught' if caught else 'NOT CAUGHT':>10} {label}")
@@ -1948,7 +2623,9 @@ check("...and so is the last one, which is not a defeat at all but the EDGE OF "
"THIS CARD: the grid-following loop can still take the pack past this "
"floor, because the floor bounds the peak guard's own forced discharge "
"and a `lo` limit cannot cap a discharge. Saying so here is worth more "
"than a green line that would be untrue", not MUT[12][1])
"than a green line that would be untrue - and part 10 now says it with a "
"number instead of a sentence, which is worth more again",
not MUT[12][1] and EV["min_soc"] <= BMS_FLOOR + 0.05)
# ==============================================================================
+7
View File
@@ -34,6 +34,13 @@ TWO RULES THIS FILE HOLDS ITSELF TO, because the reviewer will:
- the DST checks run on the 23-hour and 25-hour days, not on a normal
24-hour day where a fixed-24-slot implementation and a correct one
agree exactly.
⚠️ MUTATING THE MODULE THIS FILE GRADES? PURGE `__pycache__` FIRST - or run
`tools/mutation_run.sh`, which does. `python3 -B` alone does NOT save you: it
stops bytecode being WRITTEN, not a stale one being READ, and a size-preserving
edit reverted inside one second is invisible to CPython's staleness test. That
is TEST-15, and it has already turned one live mutation into a false survivor.
Read MUTATION.md before you report a survivor.
"""
import ast
+7
View File
@@ -48,6 +48,13 @@ THREE RULES THIS FILE HOLDS ITSELF TO, because the reviewer will:
and a stale one is not a fresh one: the gate blocks on `no_data`, blocks on
an hour the series does not cover, and blocks on a provisional hour - three
different reasons, none of them an answer.
⚠️ MUTATING THE MODULE THIS FILE GRADES? PURGE `__pycache__` FIRST - or run
`tools/mutation_run.sh`, which does. `python3 -B` alone does NOT save you: it
stops bytecode being WRITTEN, not a stale one being READ, and a size-preserving
edit reverted inside one second is invisible to CPython's staleness test. That
is TEST-15, and it has already turned one live mutation into a false survivor.
Read MUTATION.md before you report a survivor.
"""
import ast
+262 -1
View File
@@ -10,6 +10,11 @@ it:
AC2 Fully-fixed pricing DISABLES ARBITRAGE and leaves self-consumption only.
AC3 The Belgian scenario suite carries a static-profile regression case.
Section 9 is TEST-16 and is not one of those criteria. It pins the two
`arbitrage()` rungs SAFETY-26's AC4 sweep found pinned from ONE SIDE ONLY -
`spread == 0.0` and `len(firm) < 2` - and, more to the point, pins them so
they stop MASKING EACH OTHER. Read its header before editing either rung.
THREE RULES THIS FILE HOLDS ITSELF TO, because the reviewer will:
* EVERY VERDICT IS DERIVED. No `check("the split is right", True)`. Where a
@@ -45,6 +50,13 @@ THREE RULES THIS FILE HOLDS ITSELF TO, because the reviewer will:
price, and zero is exactly the value that makes everything look free. So
`static_plan` with no profile is checked to produce a read with NO
`.points`, and `price_at` on it must RAISE rather than answer 0.0.
⚠️ MUTATING THE MODULE THIS FILE GRADES? PURGE `__pycache__` FIRST - or run
`tools/mutation_run.sh`, which does. `python3 -B` alone does NOT save you: it
stops bytecode being WRITTEN, not a stale one being READ, and a size-preserving
edit reverted inside one second is invisible to CPython's staleness test. That
is TEST-15, and it has already turned one live mutation into a false survivor.
Read MUTATION.md before you report a survivor.
"""
import gzip
@@ -55,7 +67,7 @@ from pathlib import Path
from app.price import (
Absence, PricePoint, PriceProduct, PriceRead, arbitrage_allowed, brussels,
plan_is_provisional,
plan_is_provisional, required_spread, uncertainty_of,
)
from app.static_tariff import (
MEAN_WINDOW_DAYS, ProfileInvalid, StaticProfile, TariffPlan,
@@ -853,6 +865,255 @@ check("...and main.py grew no `o.get(\"static_profile\", <a default>)` fallback
'get("static_profile"' not in _MAIN and "static_status(" in _MAIN)
# --------------------------------------------------------------------------- #
print()
print("9. TEST-16 - the two arbitrage rungs, pinned from BOTH sides and "
"un-masked from each other")
# SAFETY-26's AC4 gave the same tolerance mutation to every price and quantity
# boundary in arbitrage.py and static_tariff.py. Everything in arbitrage.py went
# red. The two survivors are the two rungs graded below, and section 2 above is
# why they survived: it probes the flat rung with an EXACTLY FLAT series and
# never probes the firm-pair rung at all.
#
# D `spread == 0.0` weakened to `spread <= 0.001` SURVIVED (+2 B). An
# exactly flat series refuses under both spellings, so a tolerance is
# invisible to a flat probe. It is NOT cosmetic: a real 0.0005 spread
# flips ALLOWED -> REFUSED at min_spread_eur_kwh=0.0, which arbitrage()'s
# own docstring documents as supported ("pass 0.0 to mean any positive
# spread, explicitly") and which its validator at :861 accepts on purpose.
#
# F `len(firm) < 2` weakened to `< 1` SURVIVED, at +0 BYTES - the delta
# MUTATION.md names as the risky one.
#
# ⚠️ AND THE FINDING IS THE INTERACTION, NOT EITHER ROW. D AND F MASK EACH
# OTHER. A single firm hour has a spread of 0.0, so with F weakened the FLAT
# rung catches the stimulus and the verdict is still "refused"; with D weakened
# the tiny-spread stimulus is still refused, just for a lie. Each rung's failure
# is absorbed by the other, so BOTH can be weakened together and a suite that
# grades only `kind` reports nothing. That is invisible to single-mutation
# testing, which is how this pair survived four rounds of review on TARIFF-03
# and FCST-03.
#
# TWO THINGS FOLLOW, and they shape every check below.
#
# 1. THE REASON IS GRADED, NOT JUST THE REFUSAL. The masking case REFUSES
# CORRECTLY WHILE REPORTING THE WRONG SENTENCE - an operator reading "the
# tariff is flat" about a tariff that is not flat, or reading it about a
# series whose real problem is that §8.3 has no firm pair to trade on. A
# check that asserts only "refused" passes on a broken tree. So each
# stimulus below is graded on WHICH RUNG ANSWERED IT.
# 2. EACH RUNG NEEDS A STIMULUS THE OTHER CANNOT ABSORB, or the pinning is
# circular. The flat rung gets a series with THREE firm hours, where the
# firm-pair rung cannot fire under any weakening down to `< 0`. The
# firm-pair rung gets a ONE-FIRM series, which the flat rung CAN answer -
# so its attribution is the whole check, and that is why row 2 of the table
# is written as a rung name rather than as a verdict.
#
# ⚠️ SHIPPED BEHAVIOUR IS UNCHANGED BY THIS SECTION. Both rungs are correct
# today; nothing in app/ was touched. This is the missing measurement, not a fix.
#
# THE LEDGER. Eight rounds through `tools/mutation_run.sh` (TEST-15): recursive
# `__pycache__` purge before each, `python3 -B`, the tree re-copied FROM DISK
# between rounds, the mutated line grepped out of the file before the run, and
# the byte delta printed. `test_static_tariff.py` and `test_arbitrage.py` graded
# each time. Both suites green on the unmutated tree.
#
# round delta test_static_tariff.py
# --------------------------------------------- ------ ---------------------
# baseline, shipped +0 B PASS
# D1 `spread == 0.0` -> `<= 0.001` +2 B RED, 3 checks
# D2 `spread == 0.0` -> `<= 0.000001` +5 B RED, AC1 alone
# D3 `spread == 0.0` -> `< 0.0` (rung gone) +0 B RED (section 2 too)
# F1 `len(firm) < 2` -> `< 1` +0 B RED, 3 checks
# F2 `len(firm) < 2` -> `< 3` +0 B RED, 6 checks
# F3 `len(firm) < 2` -> `< 0` (rung gone) +0 B RED (and ValueError)
# D1+F1 BOTH AT ONCE - THE TICKET +2 B RED, 5 checks
#
# Read the rows in pairs. D1 and F1 are SAFETY-26's two survivors and each is
# now red on its own; D2 is the tolerance bisected to the rung's own resolution,
# so "pinned at exactly zero" is measured rather than asserted at one epsilon;
# F2 and F3 pin the firm-pair count from ABOVE and BELOW, which the ticket's
# criteria do not ask for but which is what stops this section being one-sided
# in the way it was written to fix. THE LAST ROW IS THE TICKET: with BOTH rungs
# weakened together - the arrangement that reported nothing before this section
# existed - five checks go red, including AC1 and AC2, because neither of them
# is spelled in terms of the other rung's behaviour.
#
# ⚠️ FOUR OF THOSE SEVEN MUTATIONS ARE +0 BYTES, which MUTATION.md names as the
# delta stale bytecode can hide. They are all REDS, the direction the bytecode
# defect cannot fabricate - but they were run under the purge anyway, because
# "it went red so the cache cannot have lied" is a conclusion, not a procedure.
_A9 = dict(peak_guard_active=False, min_spread_eur_kwh=0.0,
uncertainty=frozenset())
def plan9(prices, provisional=None, product=PriceProduct.DAY_AHEAD):
"""A bare hourly series, built here rather than through a profile.
A `static_profile` cannot express a 0.0005 spread or a part-provisional day,
and going through one would grade the profile generator as well. These are
the smallest series that put exactly one rung in question.
"""
flags = provisional if provisional is not None else [False] * len(prices)
pts = [PricePoint(start=brussels(THU + timedelta(hours=i)),
eur_per_kwh=p, provisional=v)
for i, (p, v) in enumerate(zip(prices, flags))]
return TariffPlan(PriceRead.series(pts, product, "generic_dayahead", THU),
None, "provider")
def rung9(verdict):
"""WHICH refusal answered, named from the reason the operator would read.
Deliberately not a code inspection: the sentence in the log IS the artefact
that degrades when these two rungs mask each other, so it is the sentence
that gets graded. An unrecognised refusal is reported as such rather than
quietly matching nothing - "no rung fired" and "a rung I did not list fired"
must not grade the same.
"""
if verdict.kind == "allowed":
return "allowed"
r = verdict.reason
hit = [n for n, needle in (("flat", "the tariff is flat"),
("firm-pair", "carry a published price"),
("threshold", "needs"),
("peak", "peak guard"),
("no-series", "No series exists"))
if needle in r]
return hit[0] if len(hit) == 1 else f"UNATTRIBUTED<{r[:60]}>"
# --- the sweep D survived: a small but REAL spread, at min_spread 0.0 --------
# ⚠️ NOT AN EXACTLY FLAT SERIES, which is the whole point - a flat probe cannot
# see a tolerance. The threshold is 0.0 so the `spread < need` rung below cannot
# fire either (required_spread(0.0, anything) is 0.0, asserted first), leaving
# the flat rung as the only thing that can refuse these.
check(f"the widened threshold at min_spread_eur_kwh=0.0 is still 0.0, so the "
f"probes below are graded by the FLAT rung and not by the threshold rung "
f"({required_spread(0.0, uncertainty_of(PriceProduct.DAY_AHEAD)):.6f})",
near(required_spread(0.0, uncertainty_of(PriceProduct.DAY_AHEAD)), 0.0))
# 1e-6 is the floor of the question, not of the check: app/static_tariff.py
# rounds the spread to 6 decimals before comparing, so a 5e-7 difference IS
# zero to this rung by construction. Graded as its own row below rather than
# left as an unstated edge.
TINY9 = (0.0005, 0.0001, 0.00001, 0.000001)
_tiny9 = [(d, plan9([0.20000, round(0.20000 + d, 6)])) for d in TINY9]
check(f"each tiny-spread probe really carries the spread it is named for, and "
f"two FIRM hours - so the firm-pair rung cannot be what answers them "
f"{[(f'{d:.6f}', f'{p.spread_eur_kwh():.6f}') for d, p in _tiny9]}",
all(near(p.spread_eur_kwh(), d, 1e-12)
and len([q for q in p.read.points if not q.provisional]) == 2
for d, p in _tiny9))
_tinyv9 = [(d, rung9(p.arbitrage(**_A9))) for d, p in _tiny9]
check(f"TEST-16 AC1: a spread that is SMALL BUT REAL is ALLOWED at "
f"min_spread_eur_kwh=0.0 - down to 0.000001 EUR/kWh, so the flat rung is "
f"`spread == 0.0` and not `spread <= epsilon` for any epsilon "
f"{_tinyv9}",
all(r == "allowed" for _d, r in _tinyv9))
check("...and the exactly flat series on the OTHER side of that boundary is "
"still refused, and refused BY THE FLAT RUNG - without this the sweep "
"above would also pass for a rung that had been deleted outright",
rung9(plan9([0.20000, 0.20000]).arbitrage(**_A9)) == "flat")
_q9 = plan9([0.20000, 0.2000005])
check(f"...and a difference below the rung's own 6-decimal rounding is flat BY "
f"CONSTRUCTION and says so: the raw difference is "
f"{_q9.spread_eur_kwh():.7f} and non-zero, `round(..., 6)` makes it "
f"exactly 0.0, and the rung agrees. That is the QUANTISATION the shipped "
f"line chooses in the open, not a tolerance smuggled into the comparison "
f"- and it is why the sweep above stops at 0.000001 rather than pretending "
f"to bisect further",
not near(_q9.spread_eur_kwh(), 0.0, 1e-9)
and near(round(_q9.spread_eur_kwh(), 6), 0.0, 1e-12)
and rung9(_q9.arbitrage(**_A9)) == "flat")
# --- and what D's survival actually costs: the sentence, not the verdict -----
_lie9 = plan9([0.20000, 0.20050]).arbitrage(**_A9)
check(f"TEST-16 AC4: the 0.0005 verdict carries the real spread rather than a "
f"flatness claim about a tariff that is not flat - the false sentence is "
f"what a loosened rung ships to the operator while the outcome at a "
f"shipped threshold looks unchanged ({_lie9.kind})",
_lie9.kind == "allowed" and near(_lie9.spread_eur_kwh, 0.0005)
and near(_lie9.cheapest.eur_per_kwh, 0.20000)
and near(_lie9.dearest.eur_per_kwh, 0.20050))
# --- the rung F survived: ON ITS OWN, not through the flat rung --------------
# ⚠️ THIS ROW IS THE ANTI-MASKING ONE. A one-firm series has a spread of 0.0,
# so with `< 2` weakened to `< 1` the FLAT rung refuses it and `kind` never
# moves. The only thing that moves is the sentence: §8.3's honest "only 1 of 3
# hours carry a published price" degrades to "the tariff is flat" about a series
# whose firm and provisional prices differ by 0.20 EUR/kWh. Grading the rung
# name is what makes `< 1` red without borrowing anything from the flat rung.
_one9 = plan9([0.20, 0.40, 0.10], [False, True, True])
check(f"the one-firm probe is well formed: exactly ONE firm hour out of three, "
f"and its full series is anything but flat (spread "
f"{max(p.eur_per_kwh for p in _one9.read.points) - min(p.eur_per_kwh for p in _one9.read.points):.2f} "
f"EUR/kWh) - so 'flat' would be a false sentence about it",
len([p for p in _one9.read.points if not p.provisional]) == 1
and len(_one9.read.points) == 3)
check("TEST-16 AC2: one firm hour is refused BY §8.3's FIRM-PAIR RUNG, named "
"in the reason - not by the flat rung that would also have refused it. "
"This is what takes `len(firm) < 2` -> `< 1` red on its own",
rung9(_one9.arbitrage(**_A9)) == "firm-pair")
check("...and the sentence is §8.3's in full, so the operator is told the "
"series is half-published rather than told it is fixed-price",
"§8.3" in _one9.arbitrage(**_A9).reason
and "only 1 of 3" in _one9.arbitrage(**_A9).reason
and "flat" not in _one9.arbitrage(**_A9).reason)
# The rung pinned from ABOVE as well. Without this, `len(firm) < 3` - the same
# +0 B edit in the other direction - would pass everything above.
_two9 = plan9([0.20, 0.40, 0.10], [False, False, True])
check("...and TWO firm hours are ALLOWED on the identical series shape, so the "
"rung is pinned from above too and `< 3` is red as well as `< 1`",
rung9(_two9.arbitrage(**_A9)) == "allowed"
and near(_two9.arbitrage(**_A9).spread_eur_kwh, 0.20))
# ...and from below, where the failure is not a wrong sentence but a crash:
# `max()` over an empty `firm` raises ValueError, so `< 0` does not degrade the
# reason, it takes the verdict away entirely.
_zero9 = plan9([0.20, 0.40, 0.10], [True, True, True])
check("...and a FULLY provisional series is refused by the same rung and does "
"not raise - `max()` over an empty firm set is a ValueError, so this row "
"is what makes `len(firm) < 0` red",
rung9(derived(lambda: _zero9.arbitrage(**_A9))) == "firm-pair")
# --- AC3: the two rungs do not mask each other ------------------------------
# ⚠️ THE POINT OF THE TICKET, AND IT IS A PROPERTY OF THE TABLE, NOT OF A ROW.
# Masking is possible exactly when every stimulus that one rung answers could
# also be answered by the other with an acceptable-looking result. The table
# below denies that on both sides:
#
# * the flat rung is asked a question the firm-pair rung CANNOT reach - three
# firm hours, where `len(firm) < N` refuses for no N a person would write;
# * the firm-pair rung is asked a question the flat rung CAN reach - one firm
# hour - and the answer is graded on WHICH rung gave it, so the flat rung
# absorbing it is a failure rather than a pass;
# * and the tiny-spread row is allowed, which neither rung may refuse.
#
# Verified by running BOTH mutations at once (`spread <= 0.001` AND
# `len(firm) < 1`, purged harness, +2 B and +0 B): three rows move. Under
# single-mutation testing this arrangement reports nothing at all.
_TABLE9 = (
("three firm hours, all 0.2000", plan9([0.2, 0.2, 0.2]), "flat"),
("two firm hours, 0.0005 apart", plan9([0.20000, 0.20050]), "allowed"),
("one firm hour of three", _one9, "firm-pair"),
("two firm hours of three", _two9, "allowed"),
("no firm hours at all", _zero9, "firm-pair"),
)
_got9 = [(name, want, rung9(derived(lambda p=pl: p.arbitrage(**_A9))))
for name, pl, want in _TABLE9]
check(f"TEST-16 AC3: each stimulus is answered by the rung that OWNS it, and "
f"by no other - the flat rung is asked a question the firm-pair rung "
f"cannot reach, and the firm-pair rung is asked one the flat rung could "
f"reach but must not be allowed to. Weakening EITHER rung moves a row; "
f"weakening BOTH TOGETHER still moves three "
f"{[(n, w, g) for n, w, g in _got9]}",
all(want == got for _n, want, got in _got9))
check("...and the table really does exercise both rungs and the allowing path, "
"so 'every row matched' is not a statement about one rung repeated",
{want for _n, _p, want in _TABLE9} == {"flat", "firm-pair", "allowed"})
# --------------------------------------------------------------------------- #
print()
if fails:
+249 -38
View File
@@ -85,6 +85,13 @@ regression fixture that CI cannot see is not a regression fixture.
The recorder's window rolls: 2026-08-01 leaves it around 2026-09-15, which is
why the committed copy is the artefact and not the API call.
⚠️ MUTATING THE MODULE THIS FILE GRADES? PURGE `__pycache__` FIRST - or run
`tools/mutation_run.sh`, which does. `python3 -B` alone does NOT save you: it
stops bytecode being WRITTEN, not a stale one being READ, and a size-preserving
edit reverted inside one second is invisible to CPython's staleness test. That
is TEST-15, and it has already turned one live mutation into a false survivor.
Read MUTATION.md before you report a survivor.
"""
import asyncio
@@ -108,10 +115,16 @@ fails = []
HERE = Path(__file__).resolve().parent
TMP = Path(tempfile.mkdtemp(prefix="goodwe-tariff-"))
# The live install's numbers: NOTES.md and freeze.py both record max_w 5000
# there. `peak_cap_w` ships at 3500 in config.yaml and is the SOFT LIMIT AC 3
# grades against - read out of the shipped file in part 10 rather than typed.
LIVE_MAX_W = 5000.0
# ⚠️ NOT config.yaml's shipped max_w (2000). NOTES.md and freeze.py both record
# that the LIVE INSTALL runs max_w 5000, and that is the number this file uses
# as the device's power ceiling wherever it needs one - it is named
# LIVE_INSTALL_MAX_W, not the shorter LIVE_MAX_W, precisely so it cannot be
# misread as "the current shipped default" (TEST-10; test_freeze.py carries the identical
# constant, under the identical name, for the identical reason - grep it there
# for the pin that stops config.yaml's max_w from drifting under it unnoticed).
# `peak_cap_w` ships at 3500 in config.yaml and is the SOFT LIMIT AC 3 grades
# against - read out of the shipped file in part 10 rather than typed.
LIVE_INSTALL_MAX_W = 5000.0
def check(name, cond):
@@ -291,7 +304,7 @@ CTRL_W = ctrl_closed[0].offtake_avg_w
# (b) restarted at minute 10, checkpoint restored through a real SQLite file.
st = fresh_store("restart")
tr = PeakTracker(st, cap_w=LIVE_MAX_W)
tr = PeakTracker(st, cap_w=LIVE_INSTALL_MAX_W)
a1 = QuarterAverager(phases=1, max_hold_s=MAX_HOLD_S)
feed(a1, 0, RESTART_AT_S)
check("the checkpoint round-trips through SQLite", st.save_partial(a1.snapshot()))
@@ -328,7 +341,7 @@ OUTAGE_S = 200
a4 = QuarterAverager(phases=1, max_hold_s=MAX_HOLD_S)
st4 = fresh_store("outage")
st4.save_partial(a1.snapshot())
PeakTracker(st4, cap_w=LIVE_MAX_W).restore(a4, B + timedelta(seconds=RESTART_AT_S + OUTAGE_S))
PeakTracker(st4, cap_w=LIVE_INSTALL_MAX_W).restore(a4, B + timedelta(seconds=RESTART_AT_S + OUTAGE_S))
o_closed = feed(a4, RESTART_AT_S + OUTAGE_S, QUARTER_S)
OUTAGE_UNCOVERED_S = OUTAGE_S - MAX_HOLD_S
print(f" a {OUTAGE_S} s outage inside the quarter, of which "
@@ -408,7 +421,7 @@ check("...so a new month starts from its OWN quarters, not from the previous "
# The restart that straddles the boundary: a checkpoint whose open block is in
# August, restored when `now` is already September.
st7 = fresh_store("straddle")
tr7 = PeakTracker(st7, cap_w=LIVE_MAX_W)
tr7 = PeakTracker(st7, cap_w=LIVE_INSTALL_MAX_W)
straddler = QuarterAverager(phases=1, max_hold_s=MAX_HOLD_S)
for i in range(0, 400, STEP_S):
straddler.add(sample(AUG_LATE + timedelta(seconds=i), RUN_W))
@@ -436,17 +449,17 @@ print("5. AN UNREADABLE STORE IS NOT A ZERO PEAK (the acceptance argument)")
# Three stores, three states, and the three must not answer alike.
good = fresh_store("states")
good_tr = PeakTracker(good, cap_w=LIVE_MAX_W)
good_tr = PeakTracker(good, cap_w=LIVE_INSTALL_MAX_W)
empty_r = good_tr.peak(B)
gone = fresh_store("gone")
gone_tr = PeakTracker(gone, cap_w=LIVE_MAX_W)
gone_tr = PeakTracker(gone, cap_w=LIVE_INSTALL_MAX_W)
gone.record_block(_CB(B, 3000.0, None))
gone.close() # the database goes away under a live reader
gone_r = gone_tr.peak(B)
never = PeakStore(str(TMP / "no-such-dir" / "x.db"))
never_tr = PeakTracker(never, cap_w=LIVE_MAX_W)
never_tr = PeakTracker(never, cap_w=LIVE_INSTALL_MAX_W)
never_r = never_tr.peak(B)
# A store that is OPEN and whose query FAILS is a third code path - a closed
@@ -456,7 +469,7 @@ broken = fresh_store("broken-table")
broken.record_block(_CB(B, 3000.0, None))
broken._db.execute("DROP TABLE monthly_peak")
broken._db.commit()
broken_r = PeakTracker(broken, cap_w=LIVE_MAX_W).peak(B)
broken_r = PeakTracker(broken, cap_w=LIVE_INSTALL_MAX_W).peak(B)
for label, r in (("fresh store, no quarter yet", empty_r),
("store that broke under a live reader", gone_r),
@@ -506,26 +519,26 @@ check("PeakReading exposes no accessor that defaults a missing peak to a "
if a.startswith(("get", "value")) or a.endswith("_or")])
# The consequence, which is the reason any of this matters.
print(f" headroom under a {LIVE_MAX_W:.0f} W limit: "
print(f" headroom under a {LIVE_INSTALL_MAX_W:.0f} W limit: "
f"no quarter yet -> {good_tr.headroom_w(B)}, "
f"unreadable -> {gone_tr.headroom_w(B)}")
check("an unreadable store yields NO headroom figure - the disarming default "
"(full headroom, guard silently off) is unreachable",
gone_tr.headroom_w(B) is None and never_tr.headroom_w(B) is None)
check(f"...where a genuinely empty month yields the full {LIVE_MAX_W:.0f} W, "
check(f"...where a genuinely empty month yields the full {LIVE_INSTALL_MAX_W:.0f} W, "
f"which is correct and is a different answer",
near(good_tr.headroom_w(B), LIVE_MAX_W))
near(good_tr.headroom_w(B), LIVE_INSTALL_MAX_W))
check("the 80 % warning fraction is likewise None when nothing was observed",
gone_tr.warning_frac(B) is None and good_tr.warning_frac(B) == 0.0)
# And a real peak reduces headroom, so "always None" does not pass this part.
good.record_block(_CB(B, LIVE_MAX_W * 0.9, None))
print(f" after one {LIVE_MAX_W * 0.9:.0f} W quarter: "
good.record_block(_CB(B, LIVE_INSTALL_MAX_W * 0.9, None))
print(f" after one {LIVE_INSTALL_MAX_W * 0.9:.0f} W quarter: "
f"headroom {good_tr.headroom_w(B):.0f} W, "
f"warning {good_tr.warning_frac(B) * 100:.0f} % of the limit")
check("a real observed peak gives a real headroom, so this part is not passed "
"by a store that answers None to everything",
near(good_tr.headroom_w(B), LIVE_MAX_W * 0.1, 1e-6))
near(good_tr.headroom_w(B), LIVE_INSTALL_MAX_W * 0.1, 1e-6))
check(f"...and it is over §9.1's 80 % warning threshold",
good_tr.warning_frac(B) > 0.8)
@@ -534,7 +547,7 @@ check(f"...and it is over §9.1's 80 % warning threshold",
corrupt_path = TMP / "corrupt.db"
corrupt_path.write_bytes(b"this is not a database" * 64)
corrupt = PeakStore(str(corrupt_path))
c_r = PeakTracker(corrupt, cap_w=LIVE_MAX_W).peak(B)
c_r = PeakTracker(corrupt, cap_w=LIVE_INSTALL_MAX_W).peak(B)
print(f" a corrupt database file -> {c_r.state}")
check("a corrupt database reads NOT_OBSERVED and does not raise into the "
"control loop (§6 fail-open)", c_r.state == NOT_OBSERVED)
@@ -668,6 +681,65 @@ check(f"...and on a BALANCED load NET and SUM coincide ({b_vals[POLICY_NET]:.0f}
f"so a balanced fixture could not have told them apart",
near(b_vals[POLICY_NET], b_vals[POLICY_SUM], 1e-6))
# --- TEST-13 item 1: the POLICY ARGUMENT'S PLUMBING, not just billed_w() ------
# `PeakStore.record_block(block, policy)` really does call `billed_w(block,
# policy)` - the product code is correct and is not what this adds. What was
# missing is that NO CHECK COULD TELL that call apart from a hardcoded
# `billed_w(block, POLICY_NET)`. Mutating it to exactly that left all 17 suites
# green, twice measured (TARIFF-01's reviewer, re-run through the purge harness
# for TEST-15 and again here).
#
# The reason is this section's own subject, one level up. `billed_w()`
# short-circuits to `block.offtake_avg_w` whenever `per_phase_offtake_avg_w` is
# absent, and EVERY block that reached a store anywhere in this file was
# single-phase or built with `per_phase_offtake_avg_w=None` - so all three
# policies collapsed onto one number and the argument was unobservable at the
# call site. The checks above grade the FUNCTION on an unbalanced fixture; they
# say nothing about whether its CALLER forwards what it was handed. That is the
# same shape as WITNESS-02's span normalisation and TARIFF-01's own DST window:
# a stimulus evaluated where the quantity it grades is degenerate.
#
# So the stimulus here is `blk` - the unbalanced three-phase block from the top
# of this section, whose three reductions were asserted three lines up to be
# three DIFFERENT numbers. A `record_block()` that ignores its argument stores
# one policy's figure under all three names and at least two of these
# round-trips go red.
#
# Which direction the defect runs in, because that is what makes it worth
# plumbing-testing at all: NET is the SMALLEST of the three on this fixture (the
# exporting phase nets off against the other two). A store that silently billed
# NET while its caller asked for MAX would under-record the month's peak, and an
# under-recorded peak is maximum headroom for SAFETY-07 - the same
# under-guarding direction as item 4's `getattr(..., 0.0)` default.
_banked = {}
for _pol in (POLICY_NET, POLICY_SUM, POLICY_MAX):
_st = fresh_store(f"policy-{_pol}")
_st.record_block(blk, _pol)
_read = _st.peak(month=month_key(blk.start))
_derived = _st.recompute_month(month_key(blk.start))
_banked[_pol] = _read.peak_w
check(f"record_block(block, {_pol!r}) banks {vals[_pol]:.0f} W - the store "
f"applies the reduction it was HANDED, not one of its own",
_read.is_observed and near(_read.peak_w, vals[_pol]))
check(f"...and re-deriving from the 15-min tier gives the same {_pol!r} "
f"figure, so BOTH writes in that one transaction used that reduction",
_derived.is_observed and near(_derived.peak_w, vals[_pol]))
_st_def = fresh_store("policy-default")
_st_def.record_block(blk)
check(f"...and record_block() with NO policy argument banks the NET figure "
f"({vals[POLICY_NET]:.0f} W), matching billed_w()'s own shipped default",
near(_st_def.peak(month=month_key(blk.start)).peak_w, vals[POLICY_NET]))
# The anti-degeneracy pin, stated over the BANKED numbers rather than over
# `vals`, because it is the banked ones this triple is made of. If a future
# fixture change ever made two of these coincide, the triple above would start
# passing under a hardcoded policy and would be silently back where it started.
print(f" banked through the store: "
+ ", ".join(f"{k}={v:.0f} W" for k, v in _banked.items()))
check("the three BANKED figures are three distinct numbers, so this triple is "
"not itself degenerate - it can only pass if the argument is read",
len({round(v, 6) for v in _banked.values() if v is not None}) == 3)
# ==============================================================================
print()
@@ -739,7 +811,7 @@ under = 0
for path in REPLAY:
st9 = fresh_store("replay-" + path.stem)
ing = P1Ingest(phases=1, max_age_s=MAX_HOLD_S)
tr9 = PeakTracker(st9, cap_w=SHIPPED_CAP_W or LIVE_MAX_W)
tr9 = PeakTracker(st9, cap_w=SHIPPED_CAP_W or LIVE_INSTALL_MAX_W)
first = last = None
with gzip.open(path, "rt", encoding="utf-8") as fh:
for line in fh:
@@ -753,7 +825,7 @@ for path in REPLAY:
span_h = (last - first).total_seconds() / 3600.0
qs = [w for _, w in st9.blocks_in(sorted(months)[0])] if months else []
peak = max(qs) if qs else 0.0
ok_q = sum(1 for w in qs if w <= (SHIPPED_CAP_W or LIVE_MAX_W))
ok_q = sum(1 for w in qs if w <= (SHIPPED_CAP_W or LIVE_INSTALL_MAX_W))
total_q += len(qs)
under += ok_q
replay_days += span_h / 24.0
@@ -808,7 +880,7 @@ class _Pub:
class _Hass:
async def limits(self, entity):
return (-LIVE_MAX_W, LIVE_MAX_W, 1.0)
return (-LIVE_INSTALL_MAX_W, LIVE_INSTALL_MAX_W, 1.0)
async def number(self, entity, invert=False):
return None
@@ -824,7 +896,7 @@ def built(db_path, opts=None):
return Controller(dict(
{"setpoint_entity": "number.sp", "meter_source": "ha_signed",
"p1_net_entity": "sensor.net", "meter_phases": 1,
"max_w": LIVE_MAX_W, "gain": 0.6, "slew_w": 1000, "deadband_w": 15,
"max_w": LIVE_INSTALL_MAX_W, "gain": 0.6, "slew_w": 1000, "deadband_w": 15,
"target_grid_w": 0, "step_w": 10, "heartbeat_s": 10,
"stale_input_s": 15}, **(opts or {})),
_Hass(), _Store(), _Pub(), stop=asyncio.Event(),
@@ -863,7 +935,12 @@ check("...and syncing the same quarter again banks nothing new, so the count "
check("...and the peak is unchanged by the repeat",
near(c.peak.peak(B).peak_w, 4998.0, 1e-6))
rows = [r for r in c.checks() if "capacity-tariff" in r["text"] or "peak" in r["text"]]
# ⚠️ `when=B`, AND THAT ARGUMENT IS THE TICKET (TEST-17). Without it `checks()`
# reads the peak for `datetime.now()`'s month while this fixture banked its
# quarter in August, so every check below passed in August and failed from
# 2026-09-01 - on a commit nobody had touched. The suite must grade the month
# it created, not the month the machine happens to be running in.
rows = [r for r in c.checks(when=B) if "capacity-tariff" in r["text"] or "peak" in r["text"]]
peak_rows = [r for r in rows if "peak" in r["text"] and "quarter(s) banked" in r["text"]]
print(" status row: " + (peak_rows[0]["text"] if peak_rows else "(none)"))
check("the status page carries exactly one capacity-tariff peak row",
@@ -879,7 +956,7 @@ check("...and it is FLAGGED, because 4998 W is over §9.1's 80 % warning point "
# The half that matters: the same page with a store that cannot answer.
c2 = built(TMP / "no-such-dir" / "nope.db")
u_rows = [r for r in c2.checks() if "capacity-tariff peak" in r["text"]]
u_rows = [r for r in c2.checks(when=B) if "capacity-tariff peak" in r["text"]]
print(" status row (unreadable store): "
+ (u_rows[0]["text"] if u_rows else "(none)"))
check("an unreadable store gets its OWN row, saying UNREADABLE", len(u_rows) == 1)
@@ -891,6 +968,58 @@ check("...and the healthy row and the unreadable row are different text",
bool(u_rows) and bool(peak_rows)
and u_rows[0]["text"] != peak_rows[0]["text"])
# --- TEST-17: the page must be graded at a stated time, and prove it ----------
# Three ways this can regress, so three checks. The first two would both go
# green again if `checks()` quietly went back to reading the clock, which is
# exactly the mutation this section could not previously detect.
# ⚠️ SELECTED ON "quarter(s) banked", NOT ON "peak". The NO_RECORD row reads
# "2026-10: no completed quarter recorded yet - ..." and contains neither the
# word "peak" nor "capacity-tariff" - only the UNREADABLE branch prefixes the
# family name. Filtering these rows the way the checks above do would drop the
# row and then grade its absence, which is the very mistake this ticket fixes.
# (That asymmetry in the row's own text is worth a look on its own; it is what
# made the original filter brittle. Not changed here - it is product text with
# other suites reading it.)
_peak_rows = lambda rows: [r for r in rows if "quarter(s) banked" in r["text"]]
_later = B + timedelta(days=45) # same fixture, a later billing month
_other_peak = _peak_rows(c.checks(when=_later))
print(f" the SAME controller read at {_later.date()}: "
+ (_other_peak[0]["text"] if _other_peak else "(no peak row)"))
check("asked for a LATER month, the same controller reports that month's "
"absence of a quarter, not August's 4998 W - the row follows `when`",
bool(_other_peak) and "4998 W" not in _other_peak[0]["text"]
and "no completed quarter recorded yet" in _other_peak[0]["text"])
check("...and that is NO_RECORD, distinguishable from BOTH an observed peak and "
"an unreadable store - a month with no quarter is not a broken instrument",
bool(_other_peak) and bool(peak_rows)
and "UNREADABLE" not in _other_peak[0]["text"]
and _other_peak[0]["text"] != peak_rows[0]["text"])
check("...and it is not FLAGGED, because an empty month is not an exceedance",
bool(_other_peak) and _other_peak[0]["ok"] and not _other_peak[0]["warn"])
# The mutation guard. `checks()` ignoring `when` is the whole defect, and it is
# invisible to every check above whenever the machine's clock happens to sit in
# the fixture's own month - which is how this shipped. Grading two DIFFERENT
# reference months against each other cannot be satisfied by a clock at all.
check("the peak row differs between two reference months, so a `checks()` that "
"dropped `when` and read datetime.now() would fail HERE regardless of "
"what day the suite is run on",
bool(peak_rows) and bool(_other_peak)
and peak_rows[0]["text"] != _other_peak[0]["text"])
# And the production meaning is unchanged: no argument still means today.
_now_peak = _peak_rows(c.checks())
_today_is_fixture_month = month_key(datetime.now(timezone.utc)) == month_key(B)
check("calling checks() with NO argument still reads the month being billed "
"today - the live status page's meaning is untouched",
bool(_now_peak) and (bool(peak_rows)
and _now_peak[0]["text"] == peak_rows[0]["text"]
if _today_is_fixture_month
else "no completed quarter recorded yet"
in _now_peak[0]["text"]))
# THE MEASUREMENT IS OF DELIVERED POWER (SAFETY-20). Graded on the parsed
# SYNTAX, not on the text: the module docstring argues this at length and names
# every forbidden word while doing so, so a grep over the source would be
@@ -906,24 +1035,106 @@ _names |= {n.name for n in _ast.walk(_tree)
_FORBIDDEN = {"setpoint", "write_setpoint", "target", "Decision", "i_clamped",
"clamped", "Claim", "resolve", "P_PEAK", "arbiter"}
_found = sorted(_names & _FORBIDDEN)
_imports = sorted(m.module or "" for m in _ast.walk(_tree)
if isinstance(m, _ast.ImportFrom))
# ⚠️ THE IMPORT HALF WALKS `Import` TOO, AND READS THE IMPORTED NAMES - TEST-13
# item 2. It used to be `m.module for m in walk(_tree) if isinstance(m,
# ImportFrom)`, matched against a literal list of six spellings, and that is
# blind to TWO OF PYTHON'S THREE import forms:
#
# * `from . import arbiter as _ab` is an `ImportFrom` whose `.module` is
# **None** - the dots live in `.level` and the module name lives in
# `.names` - so the old grader collected `""` and matched nothing;
# * `import app.arbiter` is an `ast.Import` node, a different class the walk
# filtered out entirely and therefore never looked at.
#
# Neither was a live exposure: the `_names` half above catches any USE of either
# alias, because reaching anything through it produces an `Attribute` whose
# `.attr` is a forbidden name. The defect was in the SENTENCE. A check that
# prints "it imports nothing from arbiter, clamp or control" while verifying
# that for one spelling out of three is worse than one that claims less, because
# the next reader stops looking. So: collect every module any import statement
# names, in all three forms, and match per dotted SEGMENT - `app.arbiter` and
# `.arbiter` must not be able to hide behind a package prefix either.
_FORBIDDEN_MODULES = {"arbiter", "clamp", "control"}
def _imported_modules(tree):
"""Every module path an import statement in `tree` names, all three forms."""
out = set()
for node in _ast.walk(tree):
if isinstance(node, _ast.Import):
# `import app.arbiter`, `import app.arbiter as x` - the whole
# dotted path is the module.
out |= {a.name for a in node.names}
elif isinstance(node, _ast.ImportFrom):
base = node.module or "" # None for `from . import arbiter`
if base:
out.add(base) # `from .arbiter import resolve`
# ...and in the `module is None` form the MODULE is in .names, so
# the names have to be joined on whether or not there is a base.
out |= {f"{base}.{a.name}" if base else a.name for a in node.names}
return out
def _forbidden_imports(mods):
# Segment-wise, not substring: `arbitrage` contains no forbidden segment and
# must not be flagged, while `app.arbiter` must be.
return sorted(m for m in mods
if _FORBIDDEN_MODULES & {p for p in m.split(".") if p})
_imports = sorted(_imported_modules(_tree))
print(f" tariff.py evaluates {len(_names)} distinct names and imports "
f"from {_imports or ['(stdlib only)']}")
f"{sorted({m.split('.')[0] for m in _imports}) or ['(nothing)']}")
check(f"none of them is a command-side name {sorted(_FORBIDDEN)} - the utility "
f"bills what FLOWED, so this reads the meter and nothing else"
+ (f"; found {_found}" if _found else ""), not _found)
check("...and it imports nothing from arbiter, clamp or control: it files no "
"claim, applies no clamp, and commands nothing - SAFETY-07's job",
not [m for m in _imports if m in ("arbiter", "clamp", "control",
".arbiter", ".clamp", ".control")])
# ...and the guard is not vacuous: the same grader run over main.py, which DOES
# command, must light up.
_main = {n.attr for n in _ast.walk(
_ast.parse((HERE / "app" / "main.py").read_text(encoding="utf-8")))
if isinstance(n, _ast.Attribute)}
check(f"the same grader over main.py finds {sorted(_main & _FORBIDDEN)}, so it "
f"is capable of failing", bool(_main & _FORBIDDEN))
check("...and it imports nothing from arbiter, clamp or control in ANY of the "
"three import spellings: it files no claim, applies no clamp, and "
"commands nothing - SAFETY-07's job",
not _forbidden_imports(_imports))
# The import grader graded. Every one of these is a real way to reach the
# command side from this module, and the first two are the ones the previous
# version let through; the last two it already caught and must keep catching.
_EVASIONS = ["from .arbiter import resolve",
"from . import arbiter as _ab",
"import app.arbiter",
"from app.control import compute",
"import app.clamp as _c"]
_missed = [e for e in _EVASIONS
if not _forbidden_imports(_imported_modules(_ast.parse(e)))]
check(f"...and that import grader is not spelling-blind: all {len(_EVASIONS)} "
f"ways of importing the command side are caught"
+ (f"; MISSED {_missed}" if _missed else ""), not _missed)
# ...and it is not simply flagging everything, which would make the line above
# free. The last three are the reason the match is per SEGMENT and not `f in m`:
# `clamps`, `arbiters` and `controller` all CONTAIN a forbidden word and none of
# them is the command side. `controller` is not hypothetical - this package is
# `goodwe_controller`, and a substring grader pointed at a path rather than a
# module name would refuse the whole repository.
_INNOCENT = ["import json", "from datetime import datetime, timezone",
"from . import arbitrage", "from .price import Uncertainty",
"from zoneinfo import ZoneInfo",
"import clamps", "from .arbiters import x",
"from . import controller"]
_false = [i for i in _INNOCENT
if _forbidden_imports(_imported_modules(_ast.parse(i)))]
check("...and it does not fire on innocent imports whose names merely CONTAIN a "
"forbidden word (`clamps`, `arbiters`, `controller`) - a substring match "
"would have"
+ (f"; FALSELY FLAGGED {_false}" if _false else ""), not _false)
# ...and neither half is vacuous: the same two graders run over main.py, which
# DOES command, must both light up. main.py carries all three import forms.
_main_tree = _ast.parse((HERE / "app" / "main.py").read_text(encoding="utf-8"))
_main = {n.attr for n in _ast.walk(_main_tree) if isinstance(n, _ast.Attribute)}
_main_imports = _forbidden_imports(_imported_modules(_main_tree))
check(f"the same NAME grader over main.py finds {sorted(_main & _FORBIDDEN)}, "
f"so it is capable of failing", bool(_main & _FORBIDDEN))
check(f"...and the same IMPORT grader over main.py finds {_main_imports}, so "
f"it is capable of failing on a real module and not only on a fixture",
bool(_main_imports))
# ==============================================================================
+140 -72
View File
@@ -5,11 +5,19 @@ three refusable configurations are refused. The second asserts that everything
on validate.py's "deliberately not refused" list still STARTS - because the way
a validator dies is not by missing a fault, it is by refusing something harmless
until somebody deletes the call.
⚠️ MUTATING THE MODULE THIS FILE GRADES? PURGE `__pycache__` FIRST - or run
`tools/mutation_run.sh`, which does. `python3 -B` alone does NOT save you: it
stops bytecode being WRITTEN, not a stale one being READ, and a size-preserving
edit reverted inside one second is invisible to CPython's staleness test. That
is TEST-15, and it has already turned one live mutation into a false survivor.
Read MUTATION.md before you report a survivor.
"""
import asyncio
import sys
from app.maintenance import MAINT_OPTION_DEFAULTS, MaintConfig
from app.validate import (
ACTUATOR_WRITE_KEYS, FIRMWARE_INGEST_VETO_S, ConfigRefused, refuse,
validate_startup_config,
@@ -27,10 +35,16 @@ def check(name, cond):
def base(**over):
"""A configuration that must start. Everything else is this, spoilt."""
# ⚠️ The maintenance rates are named EXPLICITLY, at the values config.yaml
# ships (MAINT-04). They are not decoration: with the key absent, rule 6
# falls back to main.py's 2500 W, which against this 2000 W ceiling is a
# genuine refusal - so a base() without them would be a config that does
# not start, and every check below would be measuring the wrong thing.
# ships (MAINT-04). Under MAINT-04 that was load-bearing: with the key
# absent, rule 6 fell back to a 2500 W literal that against this 2000 W
# ceiling is a genuine refusal, so a base() without them was a config that
# does not start and every check below would have been measuring the wrong
# thing. CFG-03 closed that - the fallback is now config.yaml's own 2000 -
# so they are here to say out loud what this fixture asks for rather than to
# rescue it. The CFG-03 section at the foot of this file is what asserts
# that absent and present are now THE SAME NUMBER; do not delete these two
# keys, because a base() that agrees with the default by accident is a
# fixture that cannot tell you when the default moves.
o = {"setpoint_entity": "number.goodwe_setpoint", "max_w": 2000,
"soc_entity": "sensor.soc", "batt_entity": "sensor.batt",
"meter_source": "off",
@@ -76,6 +90,40 @@ check("an unreachable device skips the range check rather than assuming",
check("a non-numeric max_w is refused",
why(validate_startup_config(base(max_w="lots"), -5000, 5000), "not a number"))
# --------------------------------------------------------------------------- #
# 1b. SAFETY-20's AC4 decision, PINNED HERE RATHER THAN ONLY WRITTEN DOWN
# --------------------------------------------------------------------------- #
# AC4 asked whether a device rating that disarms SAFETY-18's freeze rail
# additionally warrants a refusal of its own, the way `sign_disagree_w >= max_w`
# is refused. THE ANSWER IS NO, AND THE REASON IS RULE 2 ABOVE: the configuration
# is `max_w` above the device rating, which rule 2 already refuses on the
# identical predicate. A rail-specific rule (`0.95 * max_w > dev_max`) would fire
# on a strict SUBSET of what rule 2 refuses, so it could never be the rule that
# stopped a start.
#
# ⚠️ THAT DECISION HAS A PREMISE, AND THIS IS THE PREMISE, EXECUTED. If rule 2 is
# ever softened to a warning - which is exactly what main.py used to do before
# CFG-01 - the reasoning recorded in validate.py's "deliberately not refused"
# list silently stops being true, and SAFETY-18 is left with only its runtime
# NOT COVERED row. Then somebody has to come back and re-decide AC4.
from app.freeze import RAIL_FRAC # noqa: E402 - imported here, beside its use
_DEV = 4700.0 # the ticket's inverter
_CEIL = 5000.0 # the ticket's configured ceiling
check("SAFETY-20's premise: a rating below max_w disarms the freeze rail, so "
f"{RAIL_FRAC:g} * max_w is unreachable on the ticket's install",
_DEV < RAIL_FRAC * _CEIL)
check("...and rule 2 REFUSES that whole configuration at startup, which is why "
"SAFETY-20 added no rule of its own (AC4)",
len(validate_startup_config(base(max_w=_CEIL), -_DEV, _DEV)) == 1)
check("...on the rating side specifically, not incidentally through some other "
"rule", why(validate_startup_config(base(max_w=_CEIL), -_DEV, _DEV),
"THE DEVICE WINS"))
check("...and the case the refusal CANNOT reach - the rating unread because "
"ESPHome was not up - still starts, which is precisely why SAFETY-20's "
"answer had to be a runtime status row and not a startup gate",
validate_startup_config(base(max_w=_CEIL), None, None) == [])
# --------------------------------------------------------------------------- #
print("2. an actuator to write to")
# A controller with no actuator: write_setpoint() returns on the blank entity,
@@ -338,74 +386,6 @@ check("...and a ceiling already past the billing quarter, so no value the "
"schema still accepts can alarm inside the quarter that bills it",
_hi is not None and _hi > _QUARTER_S)
# --------------------------------------------------------------------------- #
print("the KNOWN cross-file default divergence, pinned rather than commented")
# ⚠️ WHAT THIS GUARDS, AND WHY IT ASSERTS THE BUG RATHER THAN THE FIX.
# config.yaml and validate.py now default maintenance_charge_w to 2000, while
# main.py's two `opts.get(..., 2500)` fallbacks and MaintConfig's dataclass
# default still say 2500. So an options dict with the key ABSENT is ACCEPTED by
# rule 6 at 2000 and then built by main.py at 2500 - which is a contradiction:
#
# validate_startup_config -> [] (accepted)
# MaintConfig().charge_w -> 2500.0
# arbiter -> 0.0 W, contradiction=True
#
# That is the bug rule 6 exists to catch, passing rule 6. It is unreachable on a
# Supervisor install (every key is always supplied from config.yaml) but fully
# reachable from sim/inject.py and from tests - which is exactly where anyone
# debugging maintenance works.
#
# The fix is ONE SOURCE OF TRUTH for option defaults. That is a bigger change
# than this ticket and it lands in main.py, which another ticket is live in - so
# the divergence is RECORDED here instead of closed. The check therefore passes
# on the mismatch and FAILS when either side moves, in EITHER direction:
#
# - config.yaml moves -> FAIL: re-decide what the fallback should be
# - main.py is fixed to match -> FAIL: the divergence is gone, DELETE this
# check and the ⚠️ block in validate.py
#
# A comment cannot do that, and "a comment where a check belonged" is this
# repo's most repeated defect.
_APP = os.path.join(os.path.dirname(os.path.abspath(__file__)), "app")
def _read(*parts):
with open(os.path.join(*parts), encoding="utf-8") as fh:
return fh.read()
# Every literal fallback for this key in main.py, whatever the call shape.
_main_falls = [float(m) for m in re.findall(
r'\.get\(\s*"maintenance_charge_w"\s*,\s*(-?\d+(?:\.\d+)?)\s*\)',
_read(_APP, "main.py"))]
# ...and MaintConfig's own dataclass default, which is the one that bites when
# main.py is bypassed entirely (a Maintenance built straight from defaults).
_dc_falls = [float(m) for m in re.findall(
r"^\s*charge_w:\s*float\s*=\s*(-?\d+(?:\.\d+)?)\s*$",
_read(_APP, "maintenance.py"), re.M)]
check(f"main.py's fallbacks are still found and still 2500 {_main_falls}",
len(_main_falls) == 2 and set(_main_falls) == {2500.0})
check(f"MaintConfig's default is still found and still 2500 {_dc_falls}",
len(_dc_falls) == 1 and set(_dc_falls) == {2500.0})
check(f"...and config.yaml still ships 2000, so the divergence is UNCHANGED "
f"(shipped {_shipped['maintenance_charge_w']:.0f}, code 2500)",
_shipped["maintenance_charge_w"] == 2000.0)
# ⚠️ And the consequence itself, through the REAL code rather than through the
# numbers above - so that if someone "fixes" this by changing a literal without
# understanding it, the thing that goes red is the behaviour, not the transcript.
from app.maintenance import MaintConfig # noqa: E402
_absent = {k: v for k, v in base().items() if k != "maintenance_charge_w"}
_built = MaintConfig().charge_w
check("with the key ABSENT the validator accepts...",
validate_startup_config(_absent, -5000, 5000) == [])
check(f"...while the code would build {_built:.0f} W against a "
f"{_absent['max_w']:.0f} W ceiling...", _built > _absent["max_w"])
_r = _charge(_absent["max_w"], _built)
check("...which the arbiter resolves to 0 W as a contradiction - the hole, "
"asserted so it cannot widen unnoticed",
_r.target_w == 0.0 and _r.contradiction)
# --------------------------------------------------------------------------- #
print("max_w must be a positive magnitude")
# Schema-blocked on a real install, but validate_startup_config() is also
@@ -566,6 +546,94 @@ try:
except TypeError:
check("a Controller with no stop Event is rejected at construction", True)
# --------------------------------------------------------------------------- #
print("CFG-03: the key ABSENT is the SAME NUMBER everywhere, through real code")
# ⚠️ WHAT THIS REPLACES, AND WHY IT IS THE OPPOSITE ASSERTION. MAINT-04 left a
# TRIPWIRE here whose PASSING CONDITION WAS THE BUG: it asserted that
# config.yaml said 2000 while main.py's two `opts.get(..., 2500)` fallbacks and
# MaintConfig's dataclass default said 2500, and it went red if EITHER side
# moved - including when somebody closed the divergence. That check has been
# DELETED, as it and validate.py's ⚠️ block both instructed, and this is what
# stands in its place: the same four consumers, exercised the same way, now
# agreeing.
#
# The four are the four the defect ran through. The validator ACCEPTS a dict
# with the key missing; main.py BUILDS a MaintConfig from that same dict; the
# dataclass answers on its own with no dict at all; and the arbiter is what
# turns their disagreement into a number an operator can see. Any three of them
# agreeing was never the property that mattered.
_absent = {k: v for k, v in base().items()
if not k.startswith("maintenance_")}
_ship_charge = _shipped["maintenance_charge_w"]
_ship_drain = _shipped["maintenance_discharge_w"]
check("the validator still ACCEPTS a dict with every maintenance key missing - "
"the fixture is the reachable one, not a refusal in disguise",
validate_startup_config(_absent, -5000, 5000) == [])
# 1. the mirror against the shipped file. Read, not transcribed: a transcription
# is the thing that drifted.
check(f"the ONE in-code mirror equals what config.yaml ships "
f"(charge {MAINT_OPTION_DEFAULTS['maintenance_charge_w']}, "
f"shipped {_ship_charge:.0f})",
float(MAINT_OPTION_DEFAULTS["maintenance_charge_w"]) == _ship_charge
and float(MAINT_OPTION_DEFAULTS["maintenance_discharge_w"]) == _ship_drain)
# 2. MaintConfig on its own - the one that bites when main.py is bypassed
# entirely, which is sim/inject.py and most of this suite.
check(f"MaintConfig() answers the shipped number, not a third one "
f"({MaintConfig().charge_w:.0f} W)",
MaintConfig().charge_w == _ship_charge
and MaintConfig().discharge_w == _ship_drain)
# 3. main.py's own path, through a real Controller rather than through a regex
# over its source. A source scan can only say the literal is gone; this says
# the object an operator's install actually runs on holds the right number.
_ctl_absent = Controller(_absent, None, _Store2(), _Pub2(), stop=asyncio.Event())
print(f" a Controller built from a dict with NO maintenance key: "
f"charge_w={_ctl_absent.maint.cfg.charge_w:.0f} W, "
f"discharge_w={_ctl_absent.maint.cfg.discharge_w:.0f} W")
check("main.py builds the shipped number from a dict that does not contain it",
_ctl_absent.maint.cfg.charge_w == _ship_charge
and _ctl_absent.maint.cfg.discharge_w == _ship_drain)
# ...and it is the SAME number when the operator supplies it explicitly, which
# is what "the default is not a special case" means.
_ctl_named = Controller(base(), None, _Store2(), _Pub2(), stop=asyncio.Event())
check("...and an explicit key builds the identical config, so absent and "
"present are not two code paths",
_ctl_named.maint.cfg == _ctl_absent.maint.cfg)
# 4. the arbiter - the consequence itself. Under MAINT-04 this pair was
# (2000, 2500) and resolved to 0 W with contradiction=True; that was the
# ACCEPTED-then-contradicted hole. The rates come out of the built config,
# not out of a literal, so if the single source moves this moves with it.
_r_ok = _charge(float(_absent["max_w"]), _ctl_absent.maint.cfg.charge_w)
print(f" arbiter with that config: {_r_ok.explain()}")
check("the arbiter CHARGES instead of contradicting itself - the hole MAINT-04 "
"pinned open is closed at the only place it was ever reachable",
_r_ok.target_w == -_ship_charge and not _r_ok.contradiction)
_r_drain = _drain(float(_absent["max_w"]), _ctl_absent.maint.cfg.discharge_w)
check("...and the drain SET is not clamped either, so the twin key the card "
"did not name is closed too",
_r_drain.target_w == _ship_drain and not _r_drain.contradiction)
# 5. nothing typed a number behind the mirror's back. Rule 6's fallback and
# main.py's are the two sites the divergence lived at, so they are the two
# sites a scan is worth running over.
_srcs = {name: open(os.path.join(os.path.dirname(os.path.abspath(__file__)),
"app", name), encoding="utf-8").read()
for name in ("main.py", "validate.py", "maintenance.py")}
_literals = {name: re.findall(
r'"(maintenance_[a-z_]+)"\s*,\s*(-?\d+(?:\.\d+)?)\s*[,)]', src)
for name, src in _srcs.items()}
check(f"no numeric fallback for any maintenance_* key survives in main.py, "
f"validate.py or maintenance.py {_literals}",
not any(_literals.values()))
check("...and MaintConfig's dataclass defaults carry no numeric literal either "
"- they are indexed out of the mirror",
not re.search(r"^\s*(charge_w|discharge_w):\s*float\s*=\s*-?\d",
_srcs["maintenance.py"], re.M))
# --------------------------------------------------------------------------- #
print()
if fails:
+12 -3
View File
@@ -8,6 +8,13 @@ person switches it off.
The headline validation is not here - it is `sim/replay_sign.py` in the infra
repo, which drives this module over the two captured bus days. This file is the
table-driven half: boundaries, timers, the latch, and the arming gate.
⚠️ MUTATING THE MODULE THIS FILE GRADES? PURGE `__pycache__` FIRST - or run
`tools/mutation_run.sh`, which does. `python3 -B` alone does NOT save you: it
stops bytecode being WRITTEN, not a stale one being READ, and a size-preserving
edit reverted inside one second is invisible to CPython's staleness test. That
is TEST-15, and it has already turned one live mutation into a false survivor.
Read MUTATION.md before you report a survivor.
"""
import sys
@@ -204,13 +211,15 @@ TABLE = [
Claim.limit("maintenance", P_MAINT_SHAPE, hi=0.0, reason="charge-only"),
MAXW], 900, False),
# ⚠️ THE CASE `winner == \"loop\"` ALONE WOULD HAVE GOT WRONG. 1500 W, not
# the default 2500 W: at max_w 2000 a -2500 hi against a -2000 lo is an
# arbiter contradiction, not a charge - see main.py.
# 2500 W: at max_w 2000 a -2500 hi against a -2000 lo is an arbiter
# contradiction, not a charge. That pair was the SHIPPED default until
# MAINT-04 refused it and CFG-03 gave the default one source of truth; it is
# kept below as a case rather than as a configuration.
("cheap-window charge REDIRECTS the loop while it still 'wins'",
[Claim.set("loop", P_LOOP, 500),
Claim.limit("maintenance", P_MAINT_SHAPE, hi=-1500, reason="cheap-window"),
MAXW], 500, False),
("...and the contradiction at the shipped defaults is not following either",
("...and the contradiction when charge_w exceeds max_w is not following either",
[Claim.set("loop", P_LOOP, 500),
Claim.limit("maintenance", P_MAINT_SHAPE, hi=-2500, reason="cheap-window"),
MAXW], 500, False),
+95
View File
@@ -0,0 +1,95 @@
#!/bin/sh
# The house mutation harness (TEST-15). `tools/mutation_run.sh [TREE] [test_*.py ...]`
#
# WHY THIS EXISTS. Nearly every safety claim in this repository was verified by
# mutation: change the shipped module, run the suite, watch it go red, revert,
# watch it go green. FCST-03's developer found that the middle two steps can be
# a lie. CPython decides a `.pyc` is still valid from (source size, source mtime
# TRUNCATED TO WHOLE SECONDS). Revert `self.provisional` to `here.provisional`
# and neither term moves - same length, same second - so the interpreter loads
# the bytecode it already has. Confirmed by disassembly: the source read `here`,
# the running code loaded `self`. The mutation "survived" because it never ran.
#
# ⚠️ `python3 -B` IS NOT THE FIX, AND NEITHER IS PYTHONDONTWRITEBYTECODE=1.
# Both stop bytecode being WRITTEN. Neither stops a stale `.pyc` that is already
# on disk from being READ - measured, and graded by test_bytecode.py part 2.
# The load-bearing half is the PURGE. `-B` is here so the run leaves no cache
# behind for the NEXT mutation to inherit.
#
# ⚠️ NOT A SLEEP. One-second mtime resolution is the mechanism, not the enemy;
# the answer is to stop trusting mtime, not to make every edit wait a second.
# A sleep also only covers the edit you remembered to slow down.
#
# It prints a fingerprint of the tree it is about to grade, because the other
# half of a mutation report is WHICH SOURCE produced it: a report that cannot
# say what was on disk is the same unverifiable claim in a different dress.
# Diff two fingerprints and the mutated file is the line that changed.
set -eu
TREE=""
case "${1-}" in
"" ) : ;;
-h|--help ) sed -n '2,30p' "$0"; exit 0 ;;
* ) if [ -d "$1" ]; then TREE=$1; shift; fi ;;
esac
if [ -z "$TREE" ]; then
# Default: the add-on directory this script ships in, so `tools/mutation_run.sh`
# works from anywhere. An explicit TREE is what lets the infra repo's replay
# harnesses purge $GOODWE_ADDON_REPO before they grade it - see MUTATION.md.
TREE=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
fi
PY=${PY:-python3}
cd "$TREE"
# CI-01's rule, for the same reason: a loop over an empty glob exits 0, and a
# green run that examined nothing is worse than a red one.
if [ $# -eq 0 ]; then set -- test_*.py; fi
if [ ! -f "$1" ]; then
echo "mutation_run: no test_*.py under $TREE - NOTHING has been graded." >&2
exit 1
fi
echo "== purge"
find . -name '__pycache__' -type d -prune -exec rm -rf {} + 2>/dev/null || true
find . -name '*.pyc' -type f -exec rm -f {} + 2>/dev/null || true
left=$(find . -name '__pycache__' -type d -o -name '*.pyc' -type f | head -5)
if [ -n "$left" ]; then
# A read-only tree cannot hold a cache written during this run either, so this
# is only reachable when the purge itself failed on a tree that HAS one - the
# one state where continuing would grade unknown bytecode.
echo "mutation_run: could not purge, and a cache remains:" >&2
echo "$left" >&2
exit 1
fi
echo " no bytecode cache under $TREE"
echo "== tree graded (sha256, bytes)"
find app -name '*.py' 2>/dev/null | sort | while read -r f; do
printf ' %s %8d %s\n' "$(sha256sum "$f" | cut -c1-16)" "$(wc -c < "$f")" "$f"
done
echo "== run ($PY -B)"
rc=0
for f in "$@"; do
start=$(date +%s)
if "$PY" -B "$f" > /tmp/mutation_run.out 2>&1; then
echo " PASS $f ($(( $(date +%s) - start ))s)"
else
echo " FAIL $f ($(( $(date +%s) - start ))s)"
tail -40 /tmp/mutation_run.out
rc=1
fi
done
# -B was asked for; check it was honoured rather than assuming. A cache here
# would be inherited by the next mutation in the batch, which is exactly the
# state this script exists to prevent.
after=$(find . -name '__pycache__' -type d -o -name '*.pyc' -type f | head -5)
if [ -n "$after" ]; then
echo "mutation_run: a bytecode cache appeared DURING the run - the next" >&2
echo "mutation in this batch would inherit it:" >&2
echo "$after" >&2
rc=1
fi
exit $rc