Compare commits

...
33 Commits
Author SHA1 Message Date
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
glenn schrooyenandClaude Opus 5 04292c4a08 DATA-01: thirty days of the real meter, and what AC 3 actually measures
checks / unit (pull_request) Successful in 3m36s
TARIFF-01 and SAFETY-07 both merged with AC 3 - "monthly peak held under
the soft limit in >= 95 % of intervals over a 30-day simulation replay" -
honestly unmet, because two days of capture existed and it was believed
nothing longer could be produced. That belief was a true statement about
the past read as a claim about the future: HA's recorder still held the
whole month, and the reason nobody found out is that the 2026-08-25
export was a one-off script that left no artefact.

So the exporter is committed and runnable now.
scenarios/p1-net-30d-2026-08/ is 2026-08-01 to 2026-08-30, 485,841
samples, 30/30 days read, 0 failed, 4.13 MB gzipped, in the schema the
two committed days already fixed.

VERIFIED AGAINST THE DAYS THAT EXIST. `--verify` re-fetches 2026-08-20
and 2026-08-23 by this exact route and reproduces both committed files
BYTE FOR BYTE after decompression (865,024 B / 15,600 samples and
894,387 B / 16,351 samples). The gzip containers differ by design: this
exporter writes mtime 0 so its output is reproducible, where the one-off
wrote a wall clock.

A FAILED READ IS NOT AN OBSERVATION. A day whose read fails writes no
file, is recorded "read": "FAILED", and the run exits non-zero; the
entity is proved to exist through /api/states before any empty day is
believed, because a typo would otherwise answer 200 [] thirty times and
produce a consistent dataset of nothing. Nothing is interpolated, so the
month's 13 gaps (1291 s, 99.95 % covered) and its 3 `unavailable`
samples stay visible as holes.

SIZE: COMMITTED, DELIBERATELY, AND MEASURED. A git bundle of the whole
history goes from 1.58 MB (release/1.0 @ 86c43eb) to 5.28 MB - +3.70 MB,
x3.3 - and a Home Assistant supervisor clones that on every install.
Downsampling was not on the table: meter_max_age_s is 30 s, so any
coarser resample turns real coverage into modelled meter-gap and moves
the number being measured. "Outside the repo with a pointer" is what
already happened and is why this card exists. The files sit in a
SUBDIRECTORY so the non-recursive globs in test_tariff.py part 9 and
test_peakguard.py part 6 do not pick them up - CI keeps replaying the two
small days instead of growing ~50 s per PR.

AC 3, MEASURED OVER 30 DAYS (tools/replay_ac3.py, which must reproduce
test_peakguard part 6's 189/190 to be believed):

  uncontrolled  2847/2879 = 98.89 % of quarters at or under 3500 W
  guarded       2850/2879 = 98.99 %
  month peak    5029.8 W -> 4107.3 W

Met on the ">= 95 % of intervals" reading - and the uncontrolled figure
is the finding, because a month with no controller at all passes it. Not
met on the other reading of the same sentence: 4107.3 W is still over the
soft limit. The guard pulls 31 of the 32 over-cap quarters down but lands
only 3 under the cap, because CEILING_MONTH_PEAK defends the running
month peak rather than the cap once one is set. Both suites' honesty
notes are corrected to point at the month instead of at its absence.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015VXjA3LWccN1rJsk3okyPC
2026-08-31 11:15:02 +02:00
admin 86c43eba24 DATA-02: twelve months of real Belgian day-ahead prices, closing OPT-04 AC4 (#24)
8760 hourly EPEX BE clearings from the Energy-Charts API (Fraunhofer ISE), CC BY 4.0 from Bundesnetzagentur | SMARD.de, committed with attribution and a fetcher that refuses to write if the licence stops saying CC BY 4.0. Raw wholesale with all_in false and the markup/levy/VAT assumption labelled as an assumption; the additive terms cancel out of every daily spread, so trade counts turn on the VAT multiplier alone. DST handled by iterating in UTC and rendering through price.brussels(): 25 points on 2025-10-26, 23 on 2026-03-29. app/ diff is zero lines - nothing tuned. Section 7B asserts that the real year cannot grade section 17, so the synthetic year stays.
2026-08-31 11:12:49 +02:00
glenn schrooyenandClaude Opus 5 d57122ec74 DATA-02: a real Belgian price year, so AC4 stops being unmeetable
checks / unit (pull_request) Successful in 3m36s
OPT-04 reported AC4 - "net-positive across 12 months of replayed prices" -
as NOT MET and replayed a synthetic year, because scenarios/ held only P1
meter captures. Right call, wrong diagnosis: the criterion was being carried
beside a 30-day METER criterion as though both needed waiting. EPEX BE
day-ahead is public data, not a capture. It needed a fetch.

8760 hourly points, 2025-09-01 to 2026-09-01 Brussels-local, canonical three
fields. Licence checked BEFORE committing: Energy-Charts publishes the BE
zone under CC BY 4.0 from Bundesnetzagentur | SMARD.de and other zones under
private-use-only terms, so this one is redistributable with attribution. The
fetcher refuses to write a file whose per-response license_info stops saying
so. Cross-checked against SMARD's own 4996/DE: 96 of 96 quarter-hours, max
difference 0.00 EUR/MWh.

Raw wholesale, and the file says so. all_in: false, with the markup/tax
assumption carried as numbers to APPLY rather than numbers applied -
TARIFF-02's trap in data form. Section 7B applies it in one visible place and
asserts arithmetically that its additive terms cancel out of every daily
spread, so the trade count turns on the VAT multiplier alone; the raw replay
is run too, so how much rests on the guess is reported (110 vs 88).

DST by construction: iterate in UTC, render through price.brussels().
2025-10-26 is 25 points, 2026-03-29 is 23, verified by counting per Brussels
day rather than asserting 24, and by checking October's 02:00 appears twice
at two offsets with two prices while March's never appears. Both bugs the
point-and-gap accounting caught were real: a UTC-bounded window made the
first day 22 hours, and an inclusive-end off-by-one dropped the last day
silently. A day nobody asked for is not a day with no prices.

THE RESULT, AT THE SHIPPED DEFAULT, WHATEVER IT IS. At 0.10 widened 1.5x to
0.1500: 110 round trips, +24.88 EUR net of the cycle cost. Unwidened, 173.
Nothing tuned - the threshold and the 2.5/1.5 factors are untouched.

And what the owner's decision now has under it: the four reports that a
static ~0.0840 spread does not clear 0.10 all STAND. What was missing is that
a dynamic site clears the widened requirement on 121 of 365 days, median
all-in spread 0.1130, so a median day would clear at 0.0754 - 156 trips,
+35.42 EUR. Reported, not applied.

The synthetic year stays, because the real one cannot grade section 17: not
one of 365 days has a negative DEAREST hour, so a zero there counts something
that could not happen. 7B asserts that degeneracy rather than reporting the
zero.

Size measured, not assumed: 893 KB plain but 74.6 KB as a git object against
56.5 KB gzipped. Git already compresses; 18 KB is not worth making the
provenance block - the licence claim a reviewer must check - unreadable in a
diff.

Nothing wired into the add-on; generic_dayahead is still the live path.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015VXjA3LWccN1rJsk3okyPC
2026-08-31 11:01:42 +02:00
admin 4601682815 SAFETY-24: an energy floor under the peak guard's forced discharge (#21)
SAFETY-07 could command a discharge to hold a billed quarter down and nothing below it consulted the state of charge - the BMS was the sole energy backstop. decide() now takes soc and soc_floor, and discharge_permitted() is the one place the question is answered: public, no default arguments, and consulted only AFTER a forced discharge is actually being asked for. The denied action is a 0 W floor - one-directional, forbids charging, structurally cannot cap the discharge the loop is already doing.

Reviewed independently. The trade-off is ruled honest and was made a check rather than a footnote: on a pack deliberately sized so the floor must bind, the worst quarter goes 4338 -> 5030 W while end SoC goes 9.6 -> 20.0 % and cycles pinned at the BMS cut-out go 1227 -> 0. Reproduced on the reviewer's own replay, including the 304.2 Wh withheld against 292.8 Wh between the two floors - half a cycle at the rail apart, so the floor is doing the arithmetic it claims.

The guard's central guarantee was re-derived across 19,800 combinations of load x elapsed x battery x SoC x floor: 0 negative floors, 0 claims with hi other than +inf, 0 decisions both floor-limited and saturated, 0 arbiter resolutions lowered or contradicted. Rule 8's <= is right: at equality the EMS floor could never be the thing that stops the discharge.

Eleven author mutations plus nine reviewer ones, all red under python -B with a purged __pycache__ and real byte deltas. One survivor is an equivalent mutant and provably so: a float(soc or 100) defaulting above the call site is dead code, because a Controller with no SoC never reaches decide() at all - inputs_ok is False and cycle() stops at the safety claim first. That property is now asserted on the service call, replacing an assertion whose sentence was wider than its check.

Merged after two rebases. The second one broke a grader neither card could have seen alone: test_peakguard graded the FIRST .decide( in main.py and required exactly one, which stopped being true when OPT-04 added arbitrage.decide(). It failed loudly rather than grading the wrong call. Fixed by selecting peakguard.decide by qualified name and requiring exactly one of that, verified still red on a decoy and on the maintenance_soc_floor swap.

Follow-ups filed as SAFETY-27, not addressed here: arbitrage_soc_floor has no rule-8 twin against bms_soc_floor, and this card's own 'revisit if a third floor appears' trigger has fired.
2026-08-31 10:24:36 +02:00
glenn schrooyenandClaude Opus 5 9234016419 Merge release/1.0 (OPT-04) into SAFETY-24, and fix one grader the merge broke
checks / unit (pull_request) Successful in 3m36s
OPT-04 landed after the previous rebase. Conflicts were CHANGELOG.md and one
IMPORT LINE in validate.py; both refusal blocks and both option sets survive
untouched, and DOCS.md, main.py and config.yaml auto-merged.

⚠️ AND THE MERGE BROKE A CHECK THAT NEITHER CARD COULD HAVE SEEN ALONE.
test_peakguard.py graded "the first `.decide(` call in main.py" and asserted
there was exactly one. That was true when SAFETY-24 was written; OPT-04 added
`arbitrage.decide(...)`, so the merged tree had two and the assertion failed.
It failed loudly rather than grading the wrong call - the guard did its job -
but it cannot ship red.

Fixed by selecting the call by QUALIFIED NAME (`peakguard.decide`) instead of
by position, and requiring exactly one of THAT. Other modules may now call
their own decide(); this grader can no longer be moved by one of them. Verified
still discriminating: a decoy `peakguard.decide` added to main.py turns it red
on 7 assertions, and the `maintenance_soc_floor` swap still turns it red on 6.

Also folded in the review's wording finding. An assertion read "a CONTROLLER
whose SoC entity does not answer hands decide() None" while driving no
Controller. The wiring property is stronger than the one claimed, and is now
asserted on the SERVICE CALL: a Controller with no SoC never reaches the guard
at all, because `inputs_ok` is False and cycle() stops at the safety claim
first - so a `float(soc or 100)` defaulting line above the call site cannot
disarm the floor. The original decide()-level check is kept, reworded to say
what it actually grades.

Full suite green on the merged tree: 15 files.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015VXjA3LWccN1rJsk3okyPC
2026-08-31 07:39:40 +02:00
admin b7272169b1 SAFETY-26: pin the negative-price boundary from below, not just from above (#23)
Closes the survivor found reviewing OPT-04: price < 0 weakened to < -0.001 left every suite green while a -0.0005 EUR/kWh sell hour discharged. Pinned as a sweep rather than a point - five magnitudes spanning >10000x down to -0.000001, the last place the canonical 6-decimal format expresses - with the well-formedness of each stimulus asserted first so section 17 is the only rung that can refuse, and the same five sign-flipped asserted to discharge so it is a boundary at exactly zero. app/ untouched.
2026-08-31 07:37:46 +02:00
glenn schrooyenandClaude Opus 5 a1376e44e4 Merge release/1.0 (FCST-03) into SAFETY-24 - CHANGELOG only
checks / unit (pull_request) Successful in 3m28s
FCST-03 landed while this was in review, so both branches had prepended an
Unreleased stanza. Only CHANGELOG.md conflicted, exactly as predicted;
app/, config.yaml, validate.py and DOCS.md all auto-merged, and this card
touches neither price_forecast.py nor static_tariff.py.

Both stanzas kept verbatim, SAFETY-24's above FCST-03's - no text from
either author edited. Full suite green on the merged tree: 14 files.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015VXjA3LWccN1rJsk3okyPC
2026-08-31 00:43:58 +02:00
glenn schrooyenandClaude Opus 5 e709554857 SAFETY-24: an energy floor under the peak guard's forced discharge
checks / unit (pull_request) Successful in 3m29s
SAFETY-07 can command a discharge to hold a billed quarter down, and
nothing below it consulted the state of charge. On the 2026-08-20 replay
it asks for 878 Wh in a day. Relying on the BMS is not absurd - it is a
real floor and it works - but it is the pack's protection rather than the
operator's, and a month of aggressive quarters leaves the battery
repeatedly at that cut-out with no EMS-side record of why. The first
symptom is a pack never available when wanted, which is indistinguishable
from the SoC drift MAINT-01 exists to correct.

decide() now takes soc and soc_floor, both required and neither
defaulted, and discharge_permitted() is the one place the question is
answered. Above the floor nothing changes. At or below it the guard files
a 0 W floor instead of a sized one - one-directional, so charging stays
blocked and no discharge is capped - and reports floor_limited with the
reason it bound. It is not a trip: every stop in 11.2's table still
outranks the claim, and the floor is never negative, so 9.1's asymmetry
survives as a property of the object (0 negative floors over 1296 swept
combinations, SoC included).

The SoC is graded only after `wanted > 0` is established, so it is never
evaluated where it governs nothing. An unreadable SoC is floor-limited,
not a full battery - a full battery is exactly the value that would
disarm the floor, and this project shipped that defaulting once already.

Failing to shave is not silent: one notification per episode
(goodwe_peak_soc_floor), distinct from the saturation alarm because the
two ask for opposite operator actions, plus its own status row and an
action-log line.

Verified by replay. The 2026-08-20 capture is driven against a modelled
pack sized from the day's own measured appetite, so it genuinely
exhausts: without the floor it reaches the BMS cut-out and holds there
for 1227 guard cycles; with it the pack stops at 20.0 % and never touches
the BMS. The energy withheld equals the energy between the two floors to
within one cycle at the rail. The honest half is reported too - the worst
quarter goes 4338 W -> 5030 W, because a floor-limited guard shaves less
on purpose.

Two new options, mirrored once in peakguard.PEAK_OPTION_DEFAULTS
(TARIFF-02's pattern), imported by validate.py and main.py rather than
typed as literals and pinned to config.yaml by a check that reads the
file - so CFG-03 still tracks three places. validate.py rule 8 refuses
peak_soc_floor <= bms_soc_floor at startup, in CFG-01/MAINT-04's manner.
maintenance_soc_floor is deliberately not reused and not renamed: it is a
drain target, not a spend limit, and the rename is recorded as a decision
to revisit if a third floor appears.

Eleven mutations of the shipped source were run against the checks; all
eleven go red and there are no survivors.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015VXjA3LWccN1rJsk3okyPC
2026-08-31 00:29:36 +02:00
70 changed files with 52441 additions and 358 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.
+692
View File
@@ -2,6 +2,698 @@
## Unreleased
**`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
30-day simulation replay"* - honestly unmet, on the belief that only two days of
capture existed and nothing longer could be produced. That belief came from a
true statement about the past being read as one about the future: HA's recorder
still held the whole month. `scenarios/p1-net-30d-2026-08/` is 2026-08-01 to
2026-08-30, **485,841 samples, 30/30 days read, 0 failed, 4.13 MB gzipped**, in
the same schema as the two days that were already there.
`tools/export_p1_history.py` is the exporter, committed and runnable - the
2026-08-25 one-off was not, and that is exactly why the data was thought
unobtainable. It reads day-at-a-time, retries, and **never lets a failed read
look like an empty hour**: a day whose read fails writes no file, is recorded as
`"read": "FAILED"`, and the run exits non-zero; the entity is proved to exist
before any empty day is believed. Nothing is interpolated, so the month's 13
gaps (1291 s, 99.95 % covered) and its 3 `unavailable` samples stay visible.
`--verify` re-fetches the two committed days by the same route and reproduces
them **byte for byte** after decompression.
`tools/replay_ac3.py` runs the month. Over 30 days the criterion measures
**98.89 % uncontrolled and 98.99 % guarded**, so it is met on that reading - and
the uncontrolled figure is the finding: a month with no controller at all passes
it. On the other reading of the same sentence it is not met - the guard takes
August's peak from **5029.8 W to 4107.3 W**, still over the 3500 W soft limit,
because once a month peak is set `CEILING_MONTH_PEAK` defends that peak rather
than the cap. Neither number is hidden; both are in that directory's README.
The size decision is committed and measured, not absorbed: a `git bundle` of
the whole history goes from **1.58 MB to 5.28 MB** (+3.70 MB, x3.3), which a
Home Assistant supervisor clones on every install. Downsampling was not
available - `meter_max_age_s` is 30 s, so any coarser resample converts real
coverage into modelled meter-gap and moves the number being measured.
The thirty files sit in a SUBDIRECTORY on purpose: `test_tariff.py` part 9 and
`test_peakguard.py` part 6 glob `scenarios/p1-net-*.jsonl.gz` non-recursively,
so CI keeps replaying the two small days and does not grow ~50 s per PR. Both
files' honesty notes are corrected to point at the month.
**OPT-04's AC4 is met: twelve months of real EPEX BE day-ahead prices are now in
the repository, and the strategy has been replayed against them (DATA-02).**
AC4 asked for "net-positive across 12 months of replayed prices". OPT-04 shipped
it as NOT MET and replayed a synthetic year instead, because `scenarios/` held
only P1 meter captures. That was the right call at the time and the wrong
diagnosis of why: the criterion was being carried alongside a 30-day *meter*
criterion as though both needed waiting, and EPEX BE day-ahead is **public data,
not a capture**. It needed a fetch, not a month.
`scenarios/epex-be-dayahead-2025-09-01_2026-09-01.json` — **8760 hourly points**,
2025-09-01 to 2026-09-01 Brussels-local, in §9.3's canonical three-field shape.
`scenarios/fetch_epex_be.py` produced it and `--verify` re-derives every claim it
makes about itself without touching the network.
**Licensing was checked before anything was committed.** The source is
Fraunhofer ISE's Energy-Charts API, which publishes the **BE** zone under
**CC BY 4.0 from Bundesnetzagentur | SMARD.de** and other zones under
private-use-only terms — so this zone is redistributable with attribution and the
data is committed rather than left as a script plus a checksum. The fetcher
**refuses to write a file** whose per-response `license_info` stops saying
CC BY 4.0. Cross-checked against the upstream: SMARD's own `4996/DE` series
matched this feed on all 96 quarter-hours of 2026-04-10, maximum difference
0.00 EUR/MWh.
**The figures are raw wholesale and the file says so.** `"all_in": false`, with
the markup/tax assumption carried in `provenance.all_in_assumption` as *numbers
to apply* rather than numbers already applied — TARIFF-02's double-counting trap
in data form. `test_arbitrage.py` section 7B applies it in one visible place and
**asserts arithmetically** that its two additive terms cancel out of every daily
spread, so the trade counts depend on the VAT multiplier alone and not on the
guessed markup. The same replay is run on raw wholesale as well, so how much of
the answer rests on the guess is reported (110 trades all-in, 88 raw).
**DST is handled by construction, not by a special case.** The fetcher iterates
in UTC and renders through `price.brussels()`, so **2025-10-26 comes out 25
points and 2026-03-29 comes out 23** — verified by counting per Brussels day
rather than asserting 24, and by checking that October's 02:00 appears twice at
`+02:00` and `+01:00` with two different prices while March's 02:00 does not
appear at all. The window is bounded at *local* midnight: bounding it at 00:00
UTC produced a 22-hour first day, and a 24-hour day silently missing from the
end, both of which the point-and-gap accounting caught.
**The result, at the shipped default, whatever it is.** At
`cycle_cost_threshold_eur` **0.10** widened by FCST-03's no-weather **1.5×** to a
required 0.1500 EUR/kWh, the real year completes **110 round trips** and is
**net-positive at +24.88 EUR** of benefit net of the cycle cost (2 kWh a trade).
Unwidened it completes 173. **Nothing was tuned:** the shipped default and the
2.5/1.5 factors are untouched, and every figure comes out of the same `decide()`.
**What the product owner's open decision now has under it.** The four
independent reports that a static day/night spread of ~0.0840 does not clear
0.10 **all stand** — a static-tariff site still never trades. What was missing
was the other half: a *dynamic* site's daily spread clears the widened
requirement on **121 of 365 days**, median daily all-in spread **0.1130**. The
threshold at which a median day would clear is **0.0754**, and at that value the
same year completes 156 trips for +35.42 EUR. Both numbers are reported; neither
is applied.
**And the synthetic year stays, because the real one cannot grade §17.** Not one
of the 365 real days has a negative *dearest* hour — 372 negative wholesale hours
and 0 days where the strategy would have sold into one — so "0 discharges into a
negative-price hour" over real prices is a count of something that could not
happen, and deleting the guard would not change it. Section 7B asserts that
degeneracy instead of quietly reporting the zero; section 7's generator is still
the only thing here that puts a negative price where the strategy would sell.
**Size, measured rather than assumed.** Plain JSON: 893 KB in the working tree
but **74.6 KB as a git object**, against 56.5 KB for a committed `.json.gz`. Git
already compresses blobs, so gzipping saves 18 KB and costs a reviewer the
ability to read the provenance block — including the licence claim they are
meant to check — in the diff. Plain, and `load()` still accepts `.gz` for a
future dataset that earns it.
**Nothing is wired into the add-on.** `generic_dayahead` remains the live fetch
path; nothing under `app/` imports the script, and the dataset is for replay.
**The capacity-peak guard's forced discharge now has an EMS-side energy floor
(SAFETY-24).** SAFETY-07 can command a discharge to hold a billed quarter down,
and nothing below it consulted the state of charge — `soc_floor` belongs to the
maintenance cycle, and freeze.py already recorded that for the grid-following
loop "the BMS is the sole energy backstop". On the 2026-08-20 replay the guard
asks for **878 Wh in a day**. Relying on the BMS is not absurd — it is a real
floor and it works — but it is the pack's protection rather than the operator's,
and a month of aggressive quarters leaves the battery repeatedly at that cut-out
with no EMS-side record of why.
`decide()` now takes `soc` and `soc_floor`, both **required** and neither
defaulted. Above the floor nothing changes. At or below it the guard files a
**0 W** floor instead of a sized one — one-directional, so charging stays blocked
and no discharge is capped — and reports `floor_limited` with the reason it
bound. It is not a trip: every stop in §11.2's table still outranks the claim,
and the floor can never be negative, so §9.1's "discharge and export are never
capped by the peak guard" survives as a property of the object (swept: 0 negative
floors across 1296 combinations of load, elapsed, battery, SoC and floor).
**Failing to shave is not silent.** A floor-limited cycle raises one notification
per episode (`goodwe_peak_soc_floor`), distinct from the saturation alarm because
the two ask the operator for opposite things, and renders its own status row.
An **unreadable SoC is floor-limited, not a full battery** — a full battery is
exactly the value that would disarm the floor, and this project has shipped that
defaulting once before (`| float(100)` in the stage-5 loop).
**Verified by replay, not by argument.** The 2026-08-20 capture is driven against
a modelled pack sized from the day's own measured appetite, so it genuinely
exhausts: without the floor it reaches the BMS cut-out and sits there for 1227
guard cycles; with it the pack stops at 20.0 % and never touches the BMS. The
energy withheld equals the energy between the two floors to within one cycle at
the rail. The honest half is reported too — the worst quarter goes from 4338 W to
5030 W, because a floor-limited guard shaves less on purpose.
**Two new options, mirrored once.** `peak_soc_floor` (20) and `bms_soc_floor`
(10), whose defaults live in `peakguard.PEAK_OPTION_DEFAULTS` — TARIFF-02's
pattern — imported by `validate.py` and `main.py` rather than typed as literals,
and pinned to `config.yaml` by a check that reads the file. CFG-03 still tracks
three places. `validate.py` rule 8 refuses `peak_soc_floor <= bms_soc_floor` at
startup, in CFG-01/MAINT-04's manner. `maintenance_soc_floor` is deliberately
**not** reused and deliberately **not** renamed: it is a drain target, not a
spend limit, and the rename is recorded as a decision to revisit if a third
floor ever appears.
**Price arbitrage - the first strategy that trades on a price (OPT-04).**
Four cards built the price stack and nothing traded on it. `app/arbitrage.py`
is §10.1's priority 3: charge in the cheapest published hour, discharge in the
@@ -0,0 +1,276 @@
# SAFETY-25 — does the grid-following loop get a reserve floor?
**Status: OPEN. This is a memo, not a decision.** It sets out the options, what
each costs, what each protects, and a recommendation. **The choice belongs to the
product owner**, because it decides whether this house's battery is allowed to
discharge to its BMS cut-out on a sustained-load evening, and that moves real
energy.
Filed with SAFETY-25. 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 the
same PR** and did not wait on this, because it is required whichever way the
answer goes.
*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.*
---
## 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
**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.
+110 -3
View File
@@ -420,7 +420,7 @@ help - see "Why the tuning is what it is".
| `maintenance_start_hour` | 10 | Hour of day a due cycle begins |
| `maintenance_discharge_w` | 2000 | Drain rate (exports the surplus). Above `max_w` it is **clamped** to `max_w` — the drain phase SETs the setpoint and the arbiter bounds it, saying so on the status page (`limited by supervised(max_w)`). Warned about, not refused: the cycle still completes, just slower |
| `maintenance_charge_w` | 2000 | Charge ceiling, capped again by peak headroom. Must stay **at or below `max_w`** or the cheap-window shaping (`hi = -maintenance_charge_w`) contradicts the supervised limit (`lo = -max_w`), the arbiter resolves it to **0 W**, and maintenance silently never charges in a cheap window — **the add-on refuses to start** |
| `maintenance_soc_floor` | 11 | Drain target — stay just above the inverter's own floor |
| `maintenance_soc_floor` | 11 | Drain target — stay just above the inverter's own floor. ⚠️ **This is not `peak_soc_floor`.** It is the depth the monthly recalibration deliberately goes to, once, on purpose; `peak_soc_floor` is the depth a money-saving discharge may never reach on any day. The right values differ (11 vs 20 as shipped), which is why they are two keys |
| `maintenance_soc_target` | 99 | Charge target |
| `maintenance_hold_min` | 120 | Hold at full so the BMS can balance |
@@ -430,6 +430,8 @@ 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.** ⚠️ 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 |
On a capacity-tariff site the maintenance charge is capped by the headroom left
@@ -530,11 +532,98 @@ projected over — raises one notification (`goodwe_peak_saturated`), because th
is the one state where the money will be spent and shedding load is the only
thing left that changes the bill.
**No new option.** The ceiling is `peak_cap_w`, which already shipped. The
**No new option for the CEILING.** It is `peak_cap_w`, which already shipped. The
coverage threshold is `meter_max_age_s`, the freeze predicate is
`meter_freeze_s`, and the achievable discharge comes from `max_w` and the device
rating — every one of them a key that already exists.
#### The energy floor under the forced discharge (`peak_soc_floor`)
The guard above can **command a discharge**, and until SAFETY-24 nothing in the
add-on bounded how far down it took the pack — the BMS was the only backstop.
On the 2026-08-20 replay the guard asks for **878 Wh in a day**.
That is not absurd: the BMS floor is real and it works. But it is *the pack's*
protection, not *yours*. A month of aggressive quarters can leave the battery
repeatedly parked at that cut-out with no record on this side of why, and the
first symptom — a battery that is never available when you want it — looks
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 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
the only thing left that changes the bill. Failing to shave is never silent —
the euro figure is the whole point of the guard.
- **An unreadable SoC is treated as floor-limited, not as a full battery.** A
full battery is exactly the value that would disarm this floor.
- **`bms_soc_floor` (10 %)** is the pack's own cut-out — register `0x0560` on the
reference GW5000S-BP, consistent with DoD 90. It exists so the add-on can
**refuse to start** when `peak_soc_floor` is at or below it: such a floor can
never be the thing that stops the discharge, and a guard that advertises a
backstop it does not have is the one thing this project will not ship. Equal is
refused too — equal buys zero margin.
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.
**Whether it should stay that way is an open product decision**, recorded with its
options, costs and a recommendation in
[`DECISIONS/SAFETY-25-loop-soc-floor.md`](DECISIONS/SAFETY-25-loop-soc-floor.md).
Until it is answered, this section is the honest statement of what you have.
### The winding-loop alarm (the output clamp)
Every setpoint this add-on writes is clamped to `max_w` before it leaves the
@@ -603,7 +692,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
@@ -629,6 +729,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
+178 -15
View File
@@ -18,6 +18,14 @@ 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; whether the loop gets
a reserve of its own is an open product decision, not an oversight.
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 +159,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 +265,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 +278,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 +354,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 +399,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
+256 -27
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.
#
@@ -229,14 +226,29 @@ class Controller:
# the action log and the notification fire on transitions rather than
# once per cycle for a quarter of an hour.
#
# ⚠️ NO CONFIG OF ITS OWN, for the reason the clamp watchdog gives ~90
# lines up and TARIFF-01 repeats: the ceiling is `peak_cap_w`, already
# shipped and already validated, and every other term is read off
# something the arbiter or the averager already owns. CFG-03 still
# tracks three places, not four.
# ⚠️ THE CEILING HAS NO CONFIG OF ITS OWN, for the reason the clamp
# watchdog gives ~90 lines up and TARIFF-01 repeats: it is `peak_cap_w`,
# already shipped and already validated, and every other term of the
# projection is read off something the arbiter or the averager already
# owns.
#
# ⚠️ SAFETY-24'S FLOOR DOES HAVE ONE, AND IT COULD NOT NOT HAVE. How far
# down the guard may spend the pack for money is a number only the site
# 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 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
self._peak_floor_limited = False
self._maint_shape_suspended = False
# Set by amain() once the transport is built, so the status page can show
# what only the transport knows (homewizard_local's unchanged_s). Stays
@@ -534,9 +546,26 @@ class Controller:
cap_w=float(self.o.get("peak_cap_w", 3500)),
reading=self.peak.peak(now),
achievable_w=min(max_w, abs(float(dev_top))),
# ⚠️ SAFETY-24. `self.soc` IS THE MEASURED READING AND MAY BE None,
# and it is handed over as None rather than defaulted here. An early
# draft of the stage-5 loop read SoC as `| float(100)` and thereby
# invented a full battery (NOTES.md 4.4b); a full battery is
# precisely the value that disarms this floor. decide() treats None
# as floor-limited, which is the direction that costs a shave rather
# than the pack.
soc=self.soc,
soc_floor=float(self.o.get(
"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)
@@ -664,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"
@@ -754,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 --------------------
@@ -780,6 +823,16 @@ class Controller:
# method assigned above and nothing since has touched.
await self.check_peak_saturated()
# --- SAFETY-24's alarm, and it is the OTHER way the money gets spent --
# Same boundary argument as check_peak_saturated(): it grades
# `self.peak_guard`, which cycle() assigned above and nothing since has
# touched. Kept as its own method rather than folded into that one,
# because the two states are mutually exclusive and want OPPOSITE
# operator actions - saturation says "shed load, the inverter is already
# flat out"; this says "the pack is at its floor and this quarter is not
# being shaved at all".
await self.check_peak_floor_limited()
# --- TARIFF-01, and it is LAST on purpose -----------------------------
# Banking a quarter is bookkeeping about a moment that has already
# happened; a slow SD card must never sit between the meter and the
@@ -924,6 +977,93 @@ class Controller:
f"thing that changes the bill."),
})
async def check_peak_floor_limited(self) -> None:
"""SAFETY-24. Alarm when the EMS SoC floor stops the guard shaving.
⚠️ FAILING TO SHAVE MUST NOT BE SILENT, AND THAT IS THE WHOLE POINT.
The guard exists for one euro figure - the capaciteitstarief bills the
month's single worst quarter - so a cycle in which it CHOSE not to shave
is a cycle in which money is being spent on purpose. Under-shaving
quietly would leave the operator with a bill and a status page full of
green.
The distinction from check_peak_saturated() is the operator's action,
which is why these are two notifications and not one:
saturated the guard asked for everything the inverter has and it
was not enough. SHED LOAD - the controller has already
done all it can, and it is still discharging.
floor-limited the guard asked for NOTHING, because the pack is at or
under the EMS floor, or its SoC could not be read.
Nothing is being discharged for this quarter at all.
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.
"""
g = self.peak_guard
limited = bool(g is not None and g.floor_limited)
was, self._peak_floor_limited = self._peak_floor_limited, limited
if not limited or was:
return
# No prefix: `reason` already opens with PEAK GUARD FLOOR-LIMITED, and
# a second copy is the kind of stutter that makes a 40-line action log
# read like boilerplate. The saturated path needs its prefix because its
# reason carries the word in the middle of a sentence, not at the front.
self.log_event(g.reason)
_LOG.error(
"SAFETY-24 - %s. The controller is STILL RUNNING and charging is "
"still blocked, but it is not discharging to hold this quarter, so "
"the quarter will set or raise the month's billed capacity peak. "
"Shed load, or lower peak_soc_floor if this pack can afford it.",
g.reason)
# A fixed notification_id, and a DIFFERENT one from every other alarm
# here - check_meter_frozen() gives the reasoning. A battery at its
# 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",
"message": (
f"{g.reason}.\n\nTHIS QUARTER WILL GO OVER THE "
f"{g.ceiling_w:.0f} W ceiling and will set or raise the "
f"month's billed capaciteitstarief peak, because the peak guard "
f"is not allowed to discharge any further: {g.soc_floor_reason}."
f" This is not a controller fault - it is the EMS-side energy "
f"floor (peak_soc_floor) doing what it is set to do, and it sits "
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.\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:
"""SAFETY-18. Alarm on a meter that answers forever without changing.
@@ -939,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)
@@ -1174,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:
@@ -1223,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()
@@ -1265,6 +1454,40 @@ class Controller:
elif _pg.saturated:
out.append({"ok": False, "warn": False,
"text": "PEAK GUARD SATURATED - " + _pg.reason})
elif _pg.floor_limited:
# SAFETY-24. NOT ok, like saturation: in both states the money
# 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,
"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:
@@ -1370,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
+244 -14
View File
@@ -246,19 +246,116 @@ validate.py are untouched by this ticket, exactly as TARIFF-01 left them, and
mismatch trap 14's own warning box describes.
------------------------------------------------------------------------------
⚠️ WHAT THIS GUARD DOES NOT HAVE: AN ENERGY BACKSTOP. SEE SAFETY-24.
SAFETY-24: THE ENERGY BACKSTOP THIS GUARD SHIPPED WITHOUT
The graded branch can FORCE DISCHARGE, and nothing in this file or in the loop
below it consults the state of charge - `soc_floor` belongs to the maintenance
cycle, and freeze.py already records that for the grid-following loop "the BMS
is the sole energy backstop". On the 2026-08-20 replay the guard asks for 878 Wh
in a day. Against a pack sitting near 9 % that is not nothing, and the guard will
keep asking as long as the meter says the quarter is over the ceiling.
SAFETY-07 left this file saying, in its own words, that the graded branch can
FORCE DISCHARGE and that nothing below it consults the state of charge - "the
BMS is the sole energy backstop" (freeze.py). On the 2026-08-20 replay the guard
asks for 878 Wh in a day, and it keeps asking for as long as the meter says the
quarter is over the ceiling. That is the behaviour working as designed, and it
is unbounded from below by anything in the EMS.
That is deliberate for THIS card and it is filed as SAFETY-24. It is also the
reason this must not go to a client install before SAFETY-24 lands: on the
reference site the BMS is a known quantity and an operator is present, and on a
client site neither is true.
⚠️ STATE THE RISK FAIRLY, because overstating it is how a real one gets ignored.
Relying on the BMS is not absurd: it is a genuine floor and it works. But it is
THE PACK's protection, not the OPERATOR's. A month of aggressive quarters can
leave the battery repeatedly parked at that floor with no EMS-side record of
why, and the first symptom - a pack that is never available when it is wanted -
is indistinguishable from the SoC drift MAINT-01 exists to correct.
So `decide()` now takes `soc` and `soc_floor`, and `discharge_permitted()` is
the one place the question is answered. Four things about the shape of it:
1. IT IS NOT A TRIP, AND IT MUST NOT BECOME ONE. SAFETY-07's claim is a LIMIT
and every stop in 11.2's table still outranks it. This floor is about
ENERGY - how far down the guard may spend the pack for money - not about
last-resort safety. The action when it binds is therefore to stop ASKING
for more discharge, not to command anything.
2. THE ACTION IS `floor_w = 0.0`, WHICH IS THE BLIND BRANCH'S ACTION FOR THE
BLIND BRANCH'S REASON. Zero is one-directional: it forbids CHARGING, which
can only ever lower delivered offtake, and it forbids nothing else. It
cannot pull the loop off a discharge it is already doing, because a `lo`
limit structurally cannot cap discharge - the property this module's whole
shape rests on, and one a NEGATIVE floor would destroy. Nothing here can
produce a negative floor: the only two values `floor_w` ever takes are 0.0
and `min(wanted, achievable)` with `wanted > 0` already established.
⚠️ AND IT DOES NOT BOUND THE LOOP. Self-consumption may still drain the
pack past this floor, exactly as SAFETY-18 recorded. That is not fixed
here and must not be claimed: this card bounds THE PEAK GUARD's OWN forced
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 decision itself is the product owner's and is open.
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
governs nothing, and would report "floor-limited" on a quiet afternoon
where the guard was never going to discharge anyway.
4. AN UNREADABLE SoC IS NOT A FULL BATTERY. `soc=None` is floor-limited, not
permitted. This is `PeakReading`'s lesson in the one place it bites
hardest: a full battery is exactly the value that would disarm this floor,
so a failed read defaulting to one would silently restore the unbounded
discharge this card exists to remove. Both new arguments are REQUIRED
keyword-only and neither has a default, which is TEST-14 read as a rule
rather than as a story: a required field that gains a default is how three
separate files in this repo shipped a quiet fallback.
AND FAILING TO SHAVE MUST NOT BE SILENT. The whole point of the guard is the
euro figure, so a floor-limited cycle carries `floor_limited=True` and main.py
raises ONE notification on the edge, saying the quarter will be exceeded - the
same shape, and the same argument, as `saturated`. The two are mutually
exclusive by construction: a floor-limited decision asks for nothing, so it
cannot have run out of inverter.
------------------------------------------------------------------------------
CFG-03: TWO NEW OPTIONS, MIRRORED ONCE, AND WHY BOTH ARE NEEDED
SAFETY-07 added none and said so. This card cannot: an EMS-side floor is a
number only the site knows, and refusing one set below the pack's own cut-out
means knowing that cut-out too.
* `peak_soc_floor` - the EMS floor. ⚠️ NOT `maintenance_soc_floor`. That is
the maintenance cycle's DRAIN TARGET: the depth a monthly recalibration
deliberately goes to, once, under supervision. This is the depth a
money-saving discharge may never reach, on any day of the month. Sharing
one key would couple two features whose right values differ and would widen
CFG-03 rather than narrow it.
* `bms_soc_floor` - the pack's own cut-out (register 0x0560 on the reference
unit, 10 %). It is here so validate.py rule 8 can REFUSE a `peak_soc_floor`
at or below it. That configuration is CFG-01 rule (a): the operator states
a floor, the BMS enforces a different one, and the status page reports an
energy backstop that can never bind.
Both defaults are mirrored ONCE, in `PEAK_OPTION_DEFAULTS` below, which is
TARIFF-02's `PRICE_OPTION_DEFAULTS` pattern - imported by validate.py and by
main.py, pinned to config.yaml by test_peakguard.py rather than transcribed.
This module still reads no option itself: `decide()` takes both as ARGUMENTS,
makes no `.get()` call, and the mirror is a default table, not a read.
⚠️ A DECISION RECORDED, NOT A RENAME DONE. Now that a second SoC floor exists,
`maintenance_soc_floor` is the ambiguous name of the two - it reads like "the
SoC floor" and is not. Renaming it is an option migration on a live install for
a clarity gain, so the decision recorded here is: KEEP IT, and carry the
distinction in DOCS.md and in this comment. Revisit if a THIRD floor appears -
a loop-side guard would be the third - at which point the migration buys enough
to be worth its cost.
------------------------------------------------------------------------------
AND IT READS NO PER-PHASE QUANTITY, ON PURPOSE
@@ -287,8 +384,50 @@ BLIND_FROZEN = "SAFETY-18: the meter is answering without changing"
CEILING_CAP = "peak_cap_w"
CEILING_MONTH_PEAK = "the month's banked peak"
# SAFETY-24. Why the forced discharge may not be sized. Reasons, not booleans,
# for BLIND_*'s reason: the status page, the action log and the operator
# 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"
# ⚠️ CFG-03. THE ONE IN-CODE MIRROR OF config.yaml FOR THIS CARD'S OPTIONS, and
# it is TARIFF-02's `PRICE_OPTION_DEFAULTS` pattern for TARIFF-02's reason: the
# add-on already carries option defaults in three places (config.yaml's
# `options:`, config.yaml's `schema:`, and main.py's literal `.get()`
# fallbacks), and a fourth is the open ticket. validate.py and main.py both
# import THIS dict rather than typing a literal, and test_peakguard.py pins it
# to config.yaml by READING the file - so a drift goes red instead of shipping.
#
# ⚠️ NOT A READ. `decide()` takes both values as arguments and this module makes
# no `.get()` call at all; the dict is a default table for its two callers.
PEAK_OPTION_DEFAULTS = {
# The EMS-side floor on SAFETY-07's forced discharge, in percent.
#
# 20 is DERIVED from the two numbers this repository already has, not
# chosen. The reference pack is 300 Ah at 51.2 V with DoD 90 - 13.8 kWh
# usable, the figure validate.py's rule 6 note already quotes - and the
# 2026-08-20 replay models 878 Wh of guard discharge in a day, which is
# 6.4 % of that. A floor 10 points above the pack's own 10 % cut-out
# therefore leaves the guard roughly 1.6 of its worst observed days of room
# before it stops, which is the smallest margin that lets the guard do its
# job on a bad day and still never reach the BMS.
"peak_soc_floor": 20,
# The pack's OWN cut-out, in percent: what the BMS enforces regardless of
# anything here. On the reference unit this is register 0x0560, read as 10,
# and it is consistent with DoD 90 on a full pack. It exists so validate.py
# rule 8 can refuse a `peak_soc_floor` at or below it - see that rule.
"bms_soc_floor": 10,
}
@dataclass(frozen=True)
class PeakDecision:
@@ -309,9 +448,19 @@ class PeakDecision:
excess_w: float = 0.0
wanted_w: float | None = None # the floor before `achievable_w` clamped it
saturated: bool = False
# SAFETY-24. True when a forced discharge WAS wanted and the EMS-side SoC
# floor refused to size it. Mutually exclusive with `saturated` by
# construction: this branch asks for nothing, so it cannot have run out of
# inverter. `soc_floor_reason` says WHICH of the two ways it bound.
floor_limited: bool = False
soc: float | None = None
soc_floor: float | None = None
soc_floor_reason: str | None = None
reason: str = ""
def explain(self) -> str:
if self.floor_limited:
return self.reason
if not self.engaged:
if self.projected_w is None:
return f"peak guard idle - {self.reason}"
@@ -383,7 +532,44 @@ def blindness(projection, max_hold_s, frozen: bool) -> str | None:
return None
def decide(projection, *, batt_w, cap_w, reading, achievable_w,
def discharge_permitted(soc, soc_floor) -> str | None:
"""SAFETY-24. May the guard size a forced discharge, or why may it not?
Returns None when it may, and otherwise the REASON it may not - which the
decision, the status page, the action log and the operator notification all
carry, because "floor-limited" on its own tells nobody what to do.
THE ONE PLACE THIS QUESTION IS ANSWERED, and it is public for the reason
`freeze.looks_frozen()`, `watchdog.loop_is_following()` and
`shaping_suspended()` are: a safety predicate transcribed into its own check
is one copy plus a future disagreement about what the check means, and the
copy that drifts is always the grading one.
⚠️ `soc is None` IS NOT PERMISSION. A failed read is not an observation, and
a FULL BATTERY is exactly the value that would disarm this floor - so a
`float(soc or 100)` here would restore the unbounded discharge this card
removes, silently, on the one install whose SoC sensor is misnamed. There is
deliberately no default argument on either parameter.
⚠️ AND `soc_floor is None` IS NOT PERMISSION EITHER, for the same reason one
step further out: a caller that has no floor configured has not thereby been
granted an unbounded one.
Boundary: `<=`, not `<`. A pack sitting exactly ON the floor has already
spent everything this guard was allowed to spend; permitting one more cycle
there would make the floor mean "one cycle below the floor".
"""
if soc is None:
return FLOOR_SOC_UNREADABLE
if soc_floor is None:
return ("no peak guard SoC floor is configured, so there is nothing to "
"bound a forced discharge with")
if float(soc) <= float(soc_floor):
return FLOOR_AT_SOC_FLOOR
return None
def decide(projection, *, batt_w, cap_w, reading, achievable_w, soc, soc_floor,
max_hold_s=None, frozen: bool = False) -> PeakDecision:
"""The whole guard. Pure: no clock, no I/O, no state carried between calls.
@@ -395,6 +581,13 @@ def decide(projection, *, batt_w, cap_w, reading, achievable_w,
claim can NEVER produce `lo > hi` in the resolver - a
contradiction there resolves to 0 W, which would park the
battery in the exact minute it should be discharging hardest.
`soc` SAFETY-24. MEASURED state of charge, percent. None when the
sensor for it did not answer - which is floor-limited, not
permission.
`soc_floor` SAFETY-24. The percent below which this guard may not spend
the pack for money. REQUIRED, and deliberately without a
default: a default here would be CFG-03's fourth defaults
site and TEST-14's quiet fallback in one line.
"""
ceiling, from_where = quarter_ceiling_w(cap_w, reading)
ceil_top = abs(float(achievable_w))
@@ -454,12 +647,41 @@ def decide(projection, *, batt_w, cap_w, reading, achievable_w,
wanted_w=wanted,
reason="the load is under the level this quarter can afford")
# SAFETY-24 - AND ONLY HERE. `wanted > 0` is now established, so a forced
# discharge really is being asked for and the SoC is the quantity that
# decides whether it may be sized. Asked one line earlier it would grade a
# number that governs nothing on every quiet cycle of the day, and would
# report "floor-limited" over a guard that was never going to discharge.
denied = discharge_permitted(soc, soc_floor)
if denied is not None:
# 0.0, not `wanted`, and not a negative number. Zero forbids CHARGING -
# one-directional, cannot cost pack energy - and forbids nothing else;
# a `lo` limit structurally cannot cap the discharge the loop is already
# doing. See the module note: this bounds THE GUARD's forced discharge,
# not the grid-following loop, which still has no SoC guard.
return PeakDecision(
engaged=True, floor_w=0.0, ceiling_w=ceiling,
ceiling_from=from_where, projected_w=projected, excess_w=ex,
wanted_w=wanted, floor_limited=True, soc=soc, soc_floor=soc_floor,
soc_floor_reason=denied,
reason=(
f"PEAK GUARD FLOOR-LIMITED: the quarter projects "
f"{projected:.0f} W against a {ceiling:.0f} W ceiling "
f"({from_where}) and {wanted:+.0f} W of discharge would hold "
f"it, but {denied}"
+ ("" if soc is None else f" ({float(soc):.0f} %")
+ ("" if soc is None or soc_floor is None
else f" vs {float(soc_floor):.0f} %")
+ ("" if soc is None else ")")
+ " - commanding no forced discharge, so THIS QUARTER WILL GO "
"OVER THE CEILING. Charging stays blocked (floor 0 W)"))
floor = min(wanted, ceil_top)
saturated = floor < wanted
return PeakDecision(
engaged=True, floor_w=floor, ceiling_w=ceiling, ceiling_from=from_where,
blind=None, projected_w=projected, excess_w=ex, wanted_w=wanted,
saturated=saturated,
saturated=saturated, soc=soc, soc_floor=soc_floor,
reason=(
f"PEAK GUARD: quarter projects {projected:.0f} W against a "
f"{ceiling:.0f} W ceiling ({from_where}) with "
@@ -513,5 +735,13 @@ def claim(decision: PeakDecision) -> Claim | None:
"""
if not decision.engaged or decision.floor_w is None:
return None
# Three reasons, not two. A `lo = 0 W` claim reaches the arbiter from THREE
# different states now - blind, floor-limited, and a genuine floor that
# happens to be zero - and the arbiter's explain() is what an operator reads
# when the battery stops charging. Spelling them the same way would make the
# SAFETY-24 case indistinguishable from the SAFETY-18 one on the one line
# that gets read.
return Claim.limit(SOURCE, P_PEAK, lo=float(decision.floor_w),
reason=("blind" if decision.blind else "quarter peak"))
reason=("blind" if decision.blind
else "SoC floor" if decision.floor_limited
else "quarter peak"))
+104 -21
View File
@@ -131,6 +131,25 @@ NOT READY banner already names the problem, (b) does not apply.
installed base is on a fixed or static tariff. Refusing to start without a
price feed would lock those sites out of the add-on entirely.
8. `peak_soc_floor` at or below `bms_soc_floor`. [(a)]
SAFETY-24, and the same shape as 1, 4, 5 and 6. The peak guard can COMMAND
a discharge to hold a billed quarter down (SAFETY-07), and `peak_soc_floor`
is the EMS-side bound on how far down it may take the pack. The BMS has its
own cut-out and enforces it regardless. Set the EMS floor at or below that
cut-out and THE BMS WINS: the EMS bound can never be the thing that stops
the discharge, so the add-on carries an energy backstop that is incapable
of binding while its status page reports one - rule 5's "a disarmed guard
that advertises itself as armed", on the guard whose failure mode is a pack
that is quietly never available when it is wanted.
⚠️ `<=`, NOT `<`, and the equality case is the interesting one. At exactly
equal, the EMS floor and the pack's cut-out act at the same percent, so the
EMS floor buys ZERO margin - it can never prevent the pack reaching the BMS
limit, which is the entire thing this option exists to prevent. That is not
"close to the rail", it is the disarmed case with an extra step. Rule 6
permits equality because equality there leaves one reachable point that
works; here it leaves none.
WHAT IS DELIBERATELY *NOT* REFUSED, because it is untidy rather than unsafe:
- `integrator_max_w` above `max_w`. DOCS.md is right that the only thing the
@@ -151,12 +170,41 @@ 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
an ordering would be inventing a relationship the system does not have.
"""
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
from .static_tariff import ProfileInvalid, parse_static_profile
@@ -332,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")
@@ -370,6 +415,38 @@ def validate_startup_config(opts: dict, dev_min=None, dev_max=None) -> list[str]
# --- 7. two price sources on one site ------------------------------------
problems.extend(_price_problems(opts))
# --- 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 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",
PEAK_OPTION_DEFAULTS["bms_soc_floor"])
if soc_floor is None or bms_floor is None:
problems.append(
"peak_soc_floor and bms_soc_floor must both be numbers (got "
f"{opts.get('peak_soc_floor')!r} / {opts.get('bms_soc_floor')!r})")
elif soc_floor <= bms_floor:
problems.append(
f"peak_soc_floor is {soc_floor:.0f} % but the pack's own cut-out "
f"(bms_soc_floor) is {bms_floor:.0f} %, so SAFETY-07's forced "
"discharge has no EMS-side bound at all - THE BMS WINS, and it is "
"the pack's protection rather than yours. The guard would report a "
"SoC floor on its status page while being incapable of ever being "
"the thing that stops the discharge, and the symptom of that is a "
"battery repeatedly sitting at the BMS limit with no record of why "
f"- which looks exactly like the SoC drift the maintenance cycle "
f"exists to correct. Raise peak_soc_floor above {bms_floor:.0f} % "
f"(the shipped default is "
f"{PEAK_OPTION_DEFAULTS['peak_soc_floor']:.0f} %), or correct "
"bms_soc_floor if it does not match this pack.")
# --- warnings: real, but not worth refusing over -------------------------
integ = opts.get("integrator_max_w")
integ_w = None if not integ else _number(opts, "integrator_max_w", None)
@@ -388,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.
+82
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
@@ -163,6 +178,57 @@ options:
peak_forecast_entity: ""
peak_cap_w: 3500
# --- SAFETY-24: the energy backstop under SAFETY-07's forced discharge -----
# The peak guard can COMMAND a discharge to hold a billed quarter under
# peak_cap_w. Until this card it was bounded from below by nothing but the
# pack's own BMS cut-out - a real floor, but the PACK's protection rather than
# the OPERATOR's. On the 2026-08-20 replay the guard asks for 878 Wh in a day.
#
# peak_soc_floor is the percent below which that discharge is not sized. When
# it binds the guard reports FLOOR-LIMITED, keeps charging blocked (a 0 W
# floor), and the add-on raises ONE notification saying the quarter will be
# exceeded - failing to shave is never silent, because the euro figure is the
# whole point of the guard.
#
# ⚠️ THIS IS NOT maintenance_soc_floor AND MUST NOT BE MERGED WITH IT.
# maintenance_soc_floor is the DRAIN TARGET of the monthly recalibration: the
# depth the cycle deliberately goes to, once a month, on purpose. This is the
# depth a money-saving discharge may never reach on any day. The right values
# differ, and sharing one key would couple two features that want to move
# independently.
#
# ⚠️ 20 IS DERIVED, NOT PICKED. The reference pack is 13.8 kWh usable and the
# 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
# DoD 90. It is here so validate.py can REFUSE a peak_soc_floor at or below
# it: such a floor can never bind, the BMS wins, and the status page would
# report an energy backstop that does not exist.
bms_soc_floor: 10
# ⚠️ THE OLD PRICE PATH, AND IT IS NOT DEAD YET. These two entities are the
# add-on delegating the whole price question to Home Assistant: main.py reads
# both and derives ONE BOOLEAN, `cheap = now <= avg`, which is consumed by
@@ -332,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)
@@ -343,6 +419,12 @@ schema:
peak_forecast_entity: str?
peak_cap_w: int(500,15000)
# SAFETY-24. No "off" value: a guard that can command a discharge does not get
# a supported way to have no energy bound at all. The ranges OVERLAP on
# purpose - the schema cannot express "above bms_soc_floor", so validate.py
# rule 8 is what refuses the pair, with a message naming both numbers.
peak_soc_floor: int(5,60)
bms_soc_floor: int(0,50)
price_now_entity: str?
price_avg_entity: str?
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,551 @@
#!/usr/bin/env python3
"""DATA-02: fetch 12 months of EPEX BE day-ahead prices, in §9.3's shape.
python3 scenarios/fetch_epex_be.py --start 2025-09-01 --end 2026-09-01 \
--out scenarios/epex-be-dayahead-2025-09-01_2026-09-01.json
Run from `goodwe_controller/`. Rewrites the output file from scratch; the
committed dataset is exactly what this produces, and `--verify` re-derives every
claim the file makes about itself without going to the network.
WHAT THIS IS NOT
================
NOT wired into the add-on, and it must never be. `price.py`'s `GenericDayAhead`
is the live path and it has its own egress check; this is a one-shot archival
fetch that produces a file for REPLAY, run by hand by a developer. Nothing under
`app/` imports it.
THE SOURCE, AND WHY THIS ONE
============================
`https://api.energy-charts.info/price?bzn=BE` - Fraunhofer ISE's Energy-Charts
API. No key, no registration.
⚠️ THE LICENCE WAS CHECKED BEFORE ANY DATA WAS COMMITTED, because for this
source it is NOT uniform across bidding zones. The API's own OpenAPI document
(`https://api.energy-charts.info/openapi.json`, /price) splits the zones in two:
"The data for the following bidding zones is licensed as CC BY 4.0 from
Bundesnetzagentur | SMARD.de and is published without changes:
AT, BE (Belgium), CH, CZ, DE-LU, ..."
"The data for the other bidding zones is for private and internal use only.
The utilization of any data, whether in its raw or derived form, for
external or commercial purposes is expressly prohibited. Should you require
licensing for market-related data, please direct your inquiries to the
original data providers, including but not limited to EPEX SPOT SE."
BE is in the FIRST list, so redistribution is permitted with attribution and the
dataset is committed rather than left as a fetch script and a checksum. Every
response also carries the licence per-response in `license_info`, and this
script REFUSES to write a file if that field ever stops saying CC BY 4.0 - a
licence checked once by a human and assumed forever is a licence that changes
silently. Had BE been in the second list, the correct output of this card would
have been this script and a checksum and no data.
Attribution, carried in the dataset's own `provenance` block and reproduced
here: data CC BY 4.0, Bundesnetzagentur | SMARD.de, retrieved via Energy-Charts
(Fraunhofer ISE), https://energy-charts.info, published without changes.
Cross-checked against the upstream on 2026-08-31: SMARD's own chart_data series
`4996/DE` over 2026-04-10 matched this API's BE series on all 96 quarter-hours
with a maximum absolute difference of 0.00 EUR/MWh. "Published without changes"
is a claim worth checking once; `--verify` does not repeat it, because it is a
claim about the SOURCE and not about the file.
RAW WHOLESALE, AND THE ASSUMPTION THAT IS NOT BAKED IN
======================================================
⚠️ WHAT COMES BACK IS RAW WHOLESALE, EUR/MWh, DAY-AHEAD AUCTION CLEARING PRICE.
It is NOT all-in: no supplier markup, no distribution or transmission tariff, no
levies, no VAT. §9.3's canonical point is all-in, and TARIFF-02's whole trap is
a figure that already contains a component being handed to something that adds
it again.
So this file does NOT add one. `eur_per_kwh` in the output is the wholesale
figure converted from EUR/MWh, `provenance.all_in` is `false` beside it, and the
markup/tax assumption a consumer needs lives in `provenance.all_in_assumption`
as NUMBERS TO APPLY rather than numbers already applied. test_arbitrage.py
section 7 applies them where a reader can watch it happen.
The assumption's SHAPE is the part that is not arbitrary, and it decides which
conclusions depend on the guessed numbers at all:
all_in(h) = (wholesale(h) + markup + network_and_levies) * (1 + vat)
* The two ADDITIVE terms cancel out of a spread: max - min is unchanged by
them. So how often a day clears `cycle_cost_threshold_eur` does NOT depend
on the markup guess - only on the VAT multiplier.
* They do NOT cancel out of §17's negative-price guard, which compares ONE
hour's all-in price against zero. A wholesale hour at -0.02 EUR/kWh is
comfortably positive all-in once ~0.12 of fixed charges is added.
Both are asserted arithmetically in section 7 rather than believed, and the
trade count is reported on the raw spread as well, so a reader can see exactly
how much of the answer rests on the guess.
The numbers themselves (2026 Belgian residential dynamic contract, order of
magnitude) are a STATED GUESS, labelled as one everywhere they appear. They are
not a measurement and this card had nothing to measure them with.
HOURS, QUARTER-HOURS, AND THE SEAM IN THE MIDDLE OF THE YEAR
============================================================
⚠️ THE SOURCE CHANGES RESOLUTION PART-WAY THROUGH ANY RECENT 12 MONTHS. EPEX
day-ahead moved to a 15-minute market time unit in October 2025 and the feed
follows: 2025-09-10 comes back as 24 hourly points, 2025-12-10 as 96
quarter-hourly ones. An importer that assumed either one silently loses three
quarters of the year, or reads a quarter as an hour.
The canonical format is hourly, so quarter-hours are aggregated: an hour's price
is the unweighted mean of its four quarters. That is a STATED APPROXIMATION of
the hourly product, not the hourly product, and it errs in the direction that
matters here - averaging discards intra-hour variation, so the observed spread
is a LOWER bound on what a 15-minute strategy would see.
`provenance.resolution` records how many hours came from each source shape.
⚠️ AND A PARTIAL HOUR IS DROPPED, NOT AVERAGED OVER WHAT ARRIVED. An hour with
three of four quarters is an hour nobody published a complete price for; the
mean of three would be an invented number carrying no flag. Dropped hours are
listed in `provenance.gaps` with their timestamps, because a missing hour in a
feed is not a zero price, and a zero price is exactly the value that would make
everything look free.
SIZE: WHY THIS IS PLAIN JSON AND NOT A `.gz`, MEASURED
======================================================
The directory's existing captures are gzipped, so the default would have been to
gzip this too. Measured on the committed file instead of assumed:
working tree, plain JSON 893 171 bytes
what GIT actually stores for it (zlib, loose object) 74 590 bytes
what git would store for a committed `.json.gz` 56 504 bytes
⚠️ GIT ALREADY COMPRESSES BLOBS, so gzipping buys 18 KB - 24 % of an object
that is already 75 KB, in a repository whose three existing P1 captures cost
27 KB, 136 KB and 140 KB. Eighteen kilobytes is not worth making the provenance
block unreadable in a pull request, and the licence claim in that block is
precisely the thing a reviewer of this card has to read and check. Plain JSON
also greps, diffs line-by-line when a future refetch changes something, and is
what `--verify` opens. `load()` still handles `.gz` for a future dataset large
enough to want it; this one is not.
The P1 captures are gzipped for the opposite reason and it is not an
inconsistency: they are hundreds of thousands of telegram lines that no human
reads, and there is no metadata in them to review.
TIME
====
Every instant is carried as UTC and rendered with `app.price.brussels()`, the
module that already owns the EU DST rule without a tz database. There is no
second answer to that question here and there must not be: the point of
`brussels()` is that the 02:00-03:00 hour which happens twice in October is two
instants, and a 24-slot local-hour importer collapses them.
So a year is 8760 hours only if it contains no transition, or contains both and
they cancel - 25 in October, 23 in March. `--verify` therefore asserts the
PER-DAY counts, not the total, because the total is exactly the number a broken
importer also produces.
"""
import argparse
import gzip
import hashlib
import json
import os
import sys
import time
import urllib.error
import urllib.request
from collections import Counter, defaultdict
from datetime import datetime, timedelta, timezone
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from app.price import brussels # noqa: E402
API = "https://api.energy-charts.info/price"
BZN = "BE"
LICENCE_MUST_CONTAIN = "CC BY 4.0"
UTC = timezone.utc
ATTRIBUTION = ("Data licensed CC BY 4.0 by Bundesnetzagentur | SMARD.de, "
"retrieved via the Energy-Charts API (Fraunhofer ISE), "
"https://energy-charts.info. Published without changes.")
# ⚠️ A GUESS, LABELLED AS ONE, AND APPLIED BY THE CONSUMER - NOT HERE.
# Order-of-magnitude 2026 Belgian residential dynamic contract. Nothing in this
# repository measured any part of it.
ALL_IN_ASSUMPTION = {
"form": "all_in = (wholesale + markup + network_and_levies) * (1 + vat)",
"markup_eur_per_kwh": 0.020,
"network_and_levies_eur_per_kwh": 0.100,
"vat_fraction": 0.06,
"status": "ASSUMPTION, NOT MEASURED. Stated so a consumer applies it "
"deliberately; the committed eur_per_kwh has none of it applied.",
"note": "The two additive terms cancel out of any spread, so an arbitrage "
"trade count depends on vat_fraction only. They do NOT cancel out "
"of the negative-price guard (17), which compares one hour's "
"all-in price against zero.",
}
PACE_S = 3.0 # between chunks, unconditionally
RETRIES = 6
def _get(url: str) -> dict:
"""One GET, backing off on 429 and 5xx.
⚠️ THIS IS A FREE PUBLIC SERVICE AND IT RATE-LIMITS. The first run of this
script was refused with 429 on its fifth chunk. Backing off is the polite
behaviour; it is also the correct one, because the alternative - catching
the error and carrying on - would produce a file that is silently missing a
month and says nothing about it. A refused request is not an empty month.
"""
req = urllib.request.Request(
url,
headers={"User-Agent": "goodwe-addon/DATA-02 (one-shot archival fetch)"})
wait = 5.0
for attempt in range(1, RETRIES + 1):
try:
with urllib.request.urlopen(req, timeout=90) as r:
return json.loads(r.read().decode("utf-8"))
except urllib.error.HTTPError as e:
if e.code not in (429, 500, 502, 503, 504) or attempt == RETRIES:
raise
print(f" HTTP {e.code}; backing off {wait:.0f}s "
f"(attempt {attempt}/{RETRIES})", file=sys.stderr)
time.sleep(wait)
wait *= 2
raise SystemExit(f"unreachable: {url}")
def local_midnight_utc(day: str) -> datetime:
"""The INSTANT at which Brussels midnight begins on `day` (YYYY-MM-DD).
⚠️ THE WINDOW IS LOCAL, NOT UTC, AND THE FIRST RUN OF THIS SCRIPT PROVED WHY.
Bounding it at 00:00 UTC starts the year at 02:00 CEST, which makes the first
Brussels day 22 hours long - and 22 is not one of the two lengths a
transition produces, so `report()` refused the file. A dataset whose first
day is short is a dataset whose "days per year" arithmetic is quietly wrong
everywhere downstream.
Derived from `brussels()` by trying the only two offsets Belgium has and
keeping the one that round-trips, rather than by restating the EU rule here.
"""
for hours in (1, 2):
guess = datetime.fromisoformat(f"{day}T00:00:00").replace(
tzinfo=timezone(timedelta(hours=hours))).astimezone(UTC)
if brussels(guess).isoformat() == f"{day}T00:00:00+0{hours}:00":
return guess
raise SystemExit(f"no Brussels midnight for {day!r} - brussels() disagrees "
f"with itself, which is a bug in price.py, not here.")
def _months(start: datetime, end: datetime):
"""[start, end) in month-sized chunks, so a bad chunk names its own window."""
a = start
while a < end:
b = min(end, (a.replace(day=1) + timedelta(days=32)).replace(day=1))
yield a, b
a = b
def fetch(start: datetime, end: datetime):
"""Raw {unix_second: EUR/MWh} over [start, end), deduplicated.
⚠️ A `null` price is DROPPED, never coerced. The API returns null for an
interval it holds no result for, and `or 0.0` is the version of this line
that ships a year of free electricity.
"""
seen, licences, nulls = {}, Counter(), 0
for a, b in _months(start, end):
# ⚠️ THE API'S `end` IS AN INCLUSIVE LOCAL DAY, AND THE WINDOW'S IS AN
# EXCLUSIVE INSTANT. Ask for the day containing the LAST hour of the
# chunk, derived from the instant rather than by subtracting a calendar
# day from the bound: `b - 1 day` drops the final local day whenever the
# window ends at local midnight, which is exactly how this window ends.
# The first run lost 2026-08-31 that way, silently - 8736 points instead
# of 8760 - and the points-plus-gaps accounting in report() is what
# noticed. A day nobody asked for is not a day with no prices.
first = brussels(a).date().isoformat()
last = brussels(b - timedelta(hours=1)).date().isoformat()
url = f"{API}?bzn={BZN}&start={first}&end={last}"
d = _get(url)
lic = str(d.get("license_info", ""))
licences[lic] += 1
if LICENCE_MUST_CONTAIN not in lic:
raise SystemExit(
f"REFUSING TO WRITE. {url} came back under licence {lic!r}, "
f"which does not say {LICENCE_MUST_CONTAIN!r}. The BE zone was "
f"redistributable when this card ran; if that has changed, the "
f"right output is this script and a checksum, not the data.")
unit = str(d.get("unit", ""))
if "MWh" not in unit:
raise SystemExit(
f"REFUSING TO WRITE. {url} reports unit {unit!r}, not EUR/MWh. "
f"A silent unit change is a factor of 1000 on every price.")
for t, p in zip(d["unix_seconds"], d["price"]):
if p is None:
nulls += 1
continue
if start.timestamp() <= t < end.timestamp():
seen[int(t)] = float(p)
print(f" {a.date()} .. {b.date()} {len(d['price']):5d} intervals",
file=sys.stderr)
time.sleep(PACE_S)
return seen, licences, nulls
def to_hourly(raw: dict):
"""Hourly means keyed by UTC hour. Returns (hours, gaps, shape_counts).
An hour is emitted only when every interval the source used for it arrived:
1 of 1 where the source was hourly, 4 of 4 where it was quarter-hourly.
Anything else is a gap and is named as one.
"""
buckets = defaultdict(dict)
for t, p in raw.items():
buckets[t - (t % 3600)][t % 3600] = p
hours, gaps, shapes = {}, [], Counter()
for h in sorted(buckets):
got = buckets[h]
if set(got) == {0}:
shapes["hourly"] += 1
hours[h] = got[0]
elif set(got) == {0, 900, 1800, 2700}:
shapes["quarter_hourly_mean"] += 1
hours[h] = sum(got.values()) / 4.0
else:
gaps.append({
"hour_utc": datetime.fromtimestamp(h, UTC).isoformat(),
"intervals_present": sorted(got),
"why": "incomplete hour - dropped rather than averaged over "
"what arrived; a partial read is not an observation",
})
return hours, gaps, shapes
def canonical(hours: dict) -> list:
"""9.3 points. THREE FIELDS, rendered at the Brussels offset for the instant."""
return [{"start": brussels(datetime.fromtimestamp(h, UTC)).isoformat(),
"eur_per_kwh": round(hours[h] / 1000.0, 6) + 0.0,
"provisional": False}
for h in sorted(hours)]
def expected_hours(start: datetime, end: datetime) -> int:
"""Whole hours in the window. Derived, rather than 8760 typed in."""
return int((end - start).total_seconds() // 3600)
def per_local_day(points) -> Counter:
"""Points per BRUSSELS calendar day - the count that exposes a DST bug."""
n = Counter()
for p in points:
n[p["start"][:10]] += 1
return n
def digest(points) -> str:
"""A checksum over the POINTS, so reformatting the envelope does not move it."""
h = hashlib.sha256()
for p in points:
h.update(f"{p['start']}|{p['eur_per_kwh']:.6f}|{int(p['provisional'])}\n"
.encode())
return h.hexdigest()
def load(path: str) -> dict:
op = gzip.open if path.endswith(".gz") else open
with op(path, "rt", encoding="utf-8") as f:
return json.load(f)
def report(doc, *, start=None, end=None) -> int:
"""Re-derive every claim the file makes about itself. Returns failures."""
pts = doc["prices"]
prov = doc["provenance"]
bad = 0
def ck(name, cond):
nonlocal bad
print(f" {'ok ' if cond else 'FAIL'} {name}")
if not cond:
bad += 1
ck(f"the checksum over the {len(pts)} points matches the recorded one "
f"({prov['sha256_of_points'][:16]}...)",
digest(pts) == prov["sha256_of_points"])
ck("every point has exactly the three canonical fields and nothing else",
all(set(p) == {"start", "eur_per_kwh", "provisional"} for p in pts))
ck("every start carries a UTC offset, and it is +01:00 or +02:00 - a naive "
"timestamp here is a wall clock plus an assumption",
bool(pts) and all(p["start"][-6:] in ("+01:00", "+02:00") for p in pts))
ck("the series is strictly increasing in time, so no instant is duplicated",
all(datetime.fromisoformat(a["start"]) < datetime.fromisoformat(b["start"])
for a, b in zip(pts, pts[1:])))
ck("consecutive points are exactly one hour apart AS INSTANTS, so the two "
"02:00s of the October day are two hours rather than one",
all((datetime.fromisoformat(b["start"])
- datetime.fromisoformat(a["start"])) == timedelta(hours=1)
for a, b in zip(pts, pts[1:])))
days = per_local_day(pts)
odd = {d: n for d, n in days.items() if n != 24}
ck(f"exactly two Brussels days are not 24 hours long, and they are the "
f"transitions: {sorted(odd.items())}",
sorted(odd.values()) == [23, 25] and len(odd) == 2)
spring = [d for d, n in odd.items() if n == 23]
autumn = [d for d, n in odd.items() if n == 25]
ck(f"the 23-hour day {spring} is in March and the 25-hour day {autumn} is "
f"in October, which is the direction the EU rule actually runs",
len(spring) == 1 and len(autumn) == 1
and spring[0][5:7] == "03" and autumn[0][5:7] == "10")
if autumn:
twice = [p["start"] for p in pts
if p["start"].startswith(autumn[0] + "T02")]
ck(f"...and 02:00 on {autumn[0]} occurs TWICE at two different offsets "
f"{twice} - exactly the case a 24-slot local-hour array collapses",
len(twice) == 2 and twice[0][-6:] == "+02:00"
and twice[1][-6:] == "+01:00")
ck(f"...and the two carry DIFFERENT prices, so the 25th hour is a real "
f"observation and not the same one written down twice",
len({p["eur_per_kwh"] for p in pts
if p["start"].startswith(autumn[0] + "T02")}) == 2)
if spring:
ck(f"...and 02:00 on {spring[0]} does not occur at all, because that "
f"wall clock reading never happened in Belgium",
not any(p["start"].startswith(spring[0] + "T02") for p in pts))
if start and end:
want = expected_hours(start, end)
ck(f"{len(pts)} points for a window of {want} whole hours, and the "
f"{len(prov['gaps'])} recorded gaps account for the difference "
f"exactly", len(pts) + len(prov["gaps"]) == want)
# ⚠️ A ZERO IS NOT AUTOMATICALLY A DEFECT HERE, AND SAYING IT WAS WOULD BE
# THE WRONG LESSON. The Belgian market really does clear at 0.00 EUR/MWh in
# solar-glut hours; this window contains such hours. What must be impossible
# is a zero that arrived by COERCION - a dropped read turned into a free
# hour. That is excluded structurally rather than by outlawing the value:
# nulls are dropped, incomplete hours become gaps, and the accounting above
# shows points + gaps covering every hour of the window, so every emitted
# point stands for intervals the source actually published.
zeros = [p["start"] for p in pts if p["eur_per_kwh"] == 0.0]
ck(f"the {len(zeros)} hours priced at exactly zero match the count recorded "
f"at build time, so no zero appeared between the fetch and the file",
len(zeros) == prov["exact_zero_hours"])
ck("...and none of them is a coerced read: every emitted hour is backed by "
"published intervals, which is what the points-plus-gaps accounting "
"above establishes",
len(prov["gaps"]) == 0 or all("intervals_present" in g
for g in prov["gaps"]))
ck("the figures are declared RAW WHOLESALE, and the all-in assumption is "
"recorded as an assumption rather than applied",
prov["all_in"] is False
and "ASSUMPTION" in prov["all_in_assumption"]["status"])
return bad
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("--start", default="2025-09-01")
ap.add_argument("--end", default="2026-09-01",
help="exclusive; both bounds are BRUSSELS-local midnights")
ap.add_argument("--out", default=None)
ap.add_argument("--verify", default=None,
help="re-derive the claims of an existing file; no network")
a = ap.parse_args()
if a.verify:
doc = load(a.verify)
print(f"verifying {a.verify}")
s = datetime.fromisoformat(doc["provenance"]["window_utc"]["start"])
e = datetime.fromisoformat(doc["provenance"]["window_utc"]["end"])
bad = report(doc, start=s, end=e)
print("OK" if not bad else f"{bad} FAILED")
return 1 if bad else 0
start = local_midnight_utc(a.start)
end = local_midnight_utc(a.end)
out = a.out or f"scenarios/epex-be-dayahead-{a.start}_{a.end}.json"
print(f"fetching {BZN} day-ahead {start.date()} .. {end.date()}",
file=sys.stderr)
raw, licences, nulls = fetch(start, end)
hours, gaps, shapes = to_hourly(raw)
pts = canonical(hours)
doc = {
"provenance": {
"card": "DATA-02",
"what": "EPEX BE day-ahead auction clearing prices, hourly",
"source": f"{API}?bzn={BZN} (Energy-Charts API, Fraunhofer ISE)",
"upstream": "Bundesnetzagentur | SMARD.de",
"licence": "CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/)",
"licence_checked": "before committing anything; the API's OpenAPI "
"document lists BE among the CC BY 4.0 zones and "
"the remaining zones as private/internal use "
"only, so redistribution of THIS zone is "
"permitted with attribution",
"licence_as_returned": sorted(licences),
"attribution": ATTRIBUTION,
"cross_check": "SMARD chart_data 4996/DE over 2026-04-10 matched "
"this feed on all 96 quarter-hours, max abs "
"difference 0.00 EUR/MWh (2026-08-31)",
"retrieved_utc": datetime.now(UTC).replace(microsecond=0).isoformat(),
"fetched_by": "scenarios/fetch_epex_be.py",
"window_utc": {"start": start.isoformat(), "end": end.isoformat()},
"unit": "EUR per kWh (source publishes EUR/MWh; divided by 1000)",
"all_in": False,
"all_in_note": "RAW WHOLESALE. No supplier markup, no network or "
"transmission tariff, no levies, no VAT. 9.3's "
"canonical point is all-in and this is NOT; the "
"consumer applies the assumption below, visibly.",
"all_in_assumption": ALL_IN_ASSUMPTION,
"resolution": {
"note": "EPEX day-ahead moved to a 15-minute market time unit "
"in Oct 2025, part-way through this window.",
"hours_from_hourly_source": shapes["hourly"],
"hours_from_quarter_hourly_mean": shapes["quarter_hourly_mean"],
"aggregation": "unweighted mean of the four quarters; a stated "
"approximation of the hourly product, and a "
"LOWER bound on the spread a 15-minute strategy "
"would have seen",
},
"timezone": "starts rendered at the Brussels offset by "
"app.price.brussels(); instants carried in UTC, so the "
"transition days come out 23 and 25 points by "
"construction rather than by a special case",
"nulls_dropped": nulls,
"gaps": gaps,
"gaps_note": "hours the source did not publish completely. Dropped, "
"never zero-filled: a missing hour is not a free hour.",
"points": len(pts),
"exact_zero_hours": sum(1 for p in pts if p["eur_per_kwh"] == 0.0),
"negative_hours": sum(1 for p in pts if p["eur_per_kwh"] < 0),
"zero_note": "REAL CLEARINGS AT 0.00 EUR/MWh, not dropped reads. "
"Nulls are dropped and incomplete hours become gaps, "
"so points + gaps == hours in the window and no point "
"stands in for something that failed to arrive.",
"sha256_of_points": digest(pts),
},
"prices": pts,
}
with open(out, "w", encoding="utf-8", newline="\n") as f:
json.dump(doc, f, indent=1, ensure_ascii=False)
f.write("\n")
print(f"wrote {out} {len(pts)} points {os.path.getsize(out)} bytes",
file=sys.stderr)
print(f"verifying {out}")
return 1 if report(doc, start=start, end=end) else 0
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,167 @@
# 30 days of P1 net power — 2026-08-01 … 2026-08-30
`sensor.p1_meter_active_power` out of Home Assistant's recorder, one gzipped
JSONL file per **local** day (Europe/Brussels), same schema as the two files one
directory up:
{"t": "2026-08-22T22:00:00+00:00", "w": -25.0}
**485,841 samples, 30/30 days read, 0 days failed, 4.13 MB gzipped.**
Produced by `tools/export_p1_history.py`; `manifest.json` here carries the
per-day counts, sha256 of every file, and every gap.
python3 tools/export_p1_history.py --days 30 --end-date 2026-08-30 \
--out-dir scenarios/p1-net-30d-2026-08
## Why this exists
[[TARIFF-01]] AC 3 and [[SAFETY-07]] AC 3 both ask for *"monthly peak held under
the soft limit in >= 95 % of intervals over a 30-day simulation replay"*, and
both were merged with the criterion honestly unmet because only two days of
capture existed. `test_tariff.py`'s docstring still recorded the reason as
"nothing longer was ever captured" — which was true about the past and was
quietly read as a statement about the future. It was not one. Probed on
2026-08-31, HA's recorder answered a 20-minute window with 230 samples at 30
days back and 0 at 45, so the whole month was still there and was exported the
same day. **The window rolls: 2026-08-01 leaves the recorder around 2026-09-15.**
## The size decision — COMMITTED, deliberately, at 4.13 MB
Three options were on the table. This one was taken and the cost is stated
rather than absorbed, and it is measured rather than estimated - a
`git bundle` of the whole history before and after this commit:
release/1.0 @ 86c43eb 1.58 MB
DATA-01 5.28 MB +3.70 MB, x3.3
A full clone of this repository therefore more than triples, and a Home
Assistant supervisor clones it on every add-on install and update. That is the
price; the paragraphs below are why it was judged worth paying rather than
avoided by making the data worse or making it disappear.
* **Downsampling is not available.** It is not a matter of taste: the shipped
`meter_max_age_s` is **30 s**, which is the age past which the controller's
own ingest stops counting a held reading as coverage. Any resample coarser
than 30 s therefore converts real coverage into modelled meter-gap and changes
the very number AC 3 measures. Resampling at or under 30 s saves almost
nothing against a 5 s cadence.
* **"Outside the repo with a pointer" is what already happened, and it is why
this card exists.** The two committed days came from the infra repo's private
`sim/scenarios/`, the one-off export script was thrown away, and three cards
then deferred an acceptance criterion on the belief that the data could not be
produced again. `test_tariff.py` states the general rule verbatim: *a
regression fixture CI cannot see is not a regression fixture.* CI's token is
minted for this repository only.
* **So: committed** — but in a SUBDIRECTORY, which is load-bearing. Both
`test_tariff.py` part 9 and `test_peakguard.py` part 6 do
`(HERE / "scenarios").glob("p1-net-*.jsonl.gz")`, which does not recurse. Drop
these thirty files beside the two and CI grows sixty full-day
replays - about 50 s of pure compute - on every PR forever, `test_tariff.py`'s
`check(... replay_days < 30)` starts failing, and both files' honesty notes
become false. In `p1-net-30d-2026-08/` they are visible to CI, invisible to
the globs, and the two committed days keep their job as the small fixtures the
suites grade against.
They are also written once and never edited, so git stores one already-deflated
blob per day with no delta churn.
## Gaps are visible, never interpolated
Nothing is filled, carried forward or resampled. A hole in the recorder is a
hole here — consecutive `t` values further apart than the cadence — which is
exactly what the controller's freshness rule already reads as *no coverage*, so
a missing hour replays as a missing hour rather than as an hour of whatever the
last sample said.
**13 gaps over 30 s, 1291 s in total: 99.950 % of the month is covered.**
All of them are listed in `manifest.json` and by
`python3 tools/replay_ac3.py <dir> --report-gaps`. The longest is 263 s on
2026-08-11.
Three samples in the month carried the state `unavailable` rather than a number
(2026-08-18 02:03:54Z and 04:10:41Z, 2026-08-25 01:52:02Z). There is no float to
write and the committed schema has no slot for a non-number, so they are absent
from the series and recorded individually in `manifest.json` under
`non_numeric_states`. Each one sits inside a gap that is already listed, which
is the honest rendering: the meter was not reporting a power then.
**A failed read is never an empty hour.** If a day's read fails, the exporter
writes NO FILE, records `"read": "FAILED"` with the error, and exits non-zero —
so a missing day is unreadable-and-known rather than silently zero. The entity
is also proved to exist through `/api/states` before any day is trusted, because
a typo would otherwise answer `200 []` thirty times and produce a beautifully
consistent dataset of nothing. On this run: 30 read, 0 failed, 0 empty.
## AC 3, measured
cd goodwe_controller
python3 tools/replay_ac3.py scenarios/p1-net-30d-2026-08
485841 samples, 2879 closed quarters (30.0 days' worth)
month 2026-08: peak 5029.8 W uncontrolled -> 4107.3 W guarded
TARIFF-01 AC 3 (UNCONTROLLED): 2847/2879 = 98.89 % of quarters at or under 3500 W
SAFETY-07 AC 3 (GUARDED): 2850/2879 = 98.99 %
guard cycles 143810, engaged on the measurement 1542, blind 195,
saturated 0, modelled discharge 8060 Wh
2879 rather than 2880 quarters: the last quarter of 2026-08-30 closes only when
a telegram past its boundary arrives, and that telegram is 2026-08-31's.
### What the numbers actually say — three findings, not a pass
1. **AC 3 is met on the ">= 95 % of intervals" reading, and the criterion turns
out to be nearly insensitive.** The UNCONTROLLED month — no controller, no
peak shaving, nothing running — already scores 98.89 %. A criterion that a
house passes by doing nothing does not discriminate between a working guard
and an absent one. That is a finding about the acceptance criterion, and it
is reported rather than filed as a win.
2. **On the other reading of the same sentence, AC 3 is NOT met.** "Monthly peak
held under the soft limit" taken as *the peak itself* fails: the guard pulls
August's peak from **5029.8 W to 4107.3 W** (-922.5 W, -18.3 %), which is
real money on a Belgian capacity tariff, but 4107.3 W is still over the
3500 W soft limit. Both readings are printed by the tool; neither is hidden.
3. **The guard stops defending the soft limit once the month's peak is set, and
that is by design.** `quarter_ceiling_w` uses `CEILING_MONTH_PEAK`: the
billed quantity is the month's maximum, so a quarter under an
already-recorded peak costs nothing extra and the guard does not spend the
battery on it. The month's 32 over-cap quarters fall on four nights
(2026-08-17, -18, -20, -21); **31 of them are pulled down** — 7494 W of
quarter-average removed in total, 8060 Wh of modelled discharge — but only
**3 land under 3500 W**, because by then the ceiling being defended is the
running month peak (~4107 W), not the soft limit. The single untouched
quarter, 2026-08-18T08:15Z at 4039.7 W, is the same rule seen from the other
side: the running peak was already 4833 W, so 4039.7 W added nothing to the
bill and the guard correctly stayed out. AC 3's wording asks the guard for
something its own tariff logic deliberately does not optimise.
Also worth an eye: **195 blind engagements** over 143,810 cycles — the guard
acting on a projection it could not fully cover. On the two committed days that
count was 5. It scales with the gaps above.
## Verification of the exporter
`tools/export_p1_history.py --verify` re-fetches a committed day by the exact
route used here and diffs it against the file:
python3 tools/export_p1_history.py \
--verify scenarios/p1-net-2026-08-20.jsonl.gz \
scenarios/p1-net-2026-08-23.jsonl.gz
Both days come back **byte-identical after decompression** — 865,024 B /
15,600 samples and 894,387 B / 16,351 samples — and the copies of those two days
inside this directory are byte-identical to the committed ones too. The gzip
CONTAINERS differ by design: a gzip header carries an mtime and a stored
filename, and this exporter writes mtime 0 so its own output is reproducible,
where the 2026-08-25 one-off wrote a wall-clock mtime. Content equality is the
claim; container equality would only assert that two files were written at the
same second.
`tools/replay_ac3.py` is checked the same way rather than trusted: pointed at
`scenarios/` it must reproduce `test_peakguard.py` part 6's published totals,
and `--expect` makes it a hard check.
python3 tools/replay_ac3.py scenarios --expect 189/190
reproduces 189/190 quarters, the 5029.8 W billed quarter, the 3485.3 W guarded
result and the 878 Wh of modelled discharge that part 6 prints.
@@ -0,0 +1,767 @@
{
"generated": "2026-08-31T08:42:40.614548+00:00",
"generator": "tools/export_p1_history.py",
"source": "http://192.168.2.158:8123/api/history/period",
"entity": "sensor.p1_meter_active_power",
"timezone": "Europe/Brussels",
"gap_threshold_s": 30.0,
"format": "{\"t\": <ISO-8601 UTC>, \"w\": <float watts>} per line, gzip",
"days": [
{
"date": "2026-08-01",
"window": [
"2026-08-01T00:00:00+02:00",
"2026-08-02T00:00:00+02:00"
],
"read": "OK",
"http_bytes": 1128060,
"attempts": 1,
"samples": 16511,
"non_numeric_states": [],
"first": "2026-07-31T22:00:00+00:00",
"last": "2026-08-01T21:59:56.268499+00:00",
"gaps": [],
"covered_span_s": 86396.3,
"mean_cadence_s": 5.233,
"file": "p1-net-2026-08-01.jsonl.gz",
"bytes_gz": 140531,
"bytes_raw": 913203,
"sha256_raw": "120de2a0b7eb552281dac4bc1f8fd76d947ba72d1f5b426d9dcdd85ec103bd06",
"sha256_gz": "e09bdee349dd3668a073b7fd77974e639c269ec37e73e81a9706cadde083f064"
},
{
"date": "2026-08-02",
"window": [
"2026-08-02T00:00:00+02:00",
"2026-08-03T00:00:00+02:00"
],
"read": "OK",
"http_bytes": 1115387,
"attempts": 1,
"samples": 16303,
"non_numeric_states": [],
"first": "2026-08-01T22:00:00+00:00",
"last": "2026-08-02T21:59:55.191360+00:00",
"gaps": [],
"covered_span_s": 86395.2,
"mean_cadence_s": 5.3,
"file": "p1-net-2026-08-02.jsonl.gz",
"bytes_gz": 141404,
"bytes_raw": 903234,
"sha256_raw": "9ab4891c0abf9d621fa528848fc3a874687843804768e8aeab6a88f7bb04b679",
"sha256_gz": "94774139b3e19d04bcda3ac5ea988dd4d645e99004f90b917c6b0bf3fbac21cb"
},
{
"date": "2026-08-03",
"window": [
"2026-08-03T00:00:00+02:00",
"2026-08-04T00:00:00+02:00"
],
"read": "OK",
"http_bytes": 1123668,
"attempts": 1,
"samples": 16424,
"non_numeric_states": [],
"first": "2026-08-02T22:00:00+00:00",
"last": "2026-08-03T21:59:55.255808+00:00",
"gaps": [],
"covered_span_s": 86395.3,
"mean_cadence_s": 5.261,
"file": "p1-net-2026-08-03.jsonl.gz",
"bytes_gz": 144202,
"bytes_raw": 909942,
"sha256_raw": "13f8dd904a31b5b67fcfde04f6afc49c34c3a9504617278d79d87516fcd6441f",
"sha256_gz": "e1bc0cb0e271cbc8d896aee97aa0f5c18e49e78905d1aaf137904a768047c7bc"
},
{
"date": "2026-08-04",
"window": [
"2026-08-04T00:00:00+02:00",
"2026-08-05T00:00:00+02:00"
],
"read": "OK",
"http_bytes": 1108582,
"attempts": 1,
"samples": 16286,
"non_numeric_states": [],
"first": "2026-08-03T22:00:00+00:00",
"last": "2026-08-04T21:59:58.729138+00:00",
"gaps": [],
"covered_span_s": 86398.7,
"mean_cadence_s": 5.305,
"file": "p1-net-2026-08-04.jsonl.gz",
"bytes_gz": 136505,
"bytes_raw": 896650,
"sha256_raw": "a65cd9d1ceda61e5a40043edb401c2154feea2b36bd3221710df808d778eabce",
"sha256_gz": "c19b19ac890f4caad4140cb27d2fe6f3e972545f664127e5d9f457e711ad8c88"
},
{
"date": "2026-08-05",
"window": [
"2026-08-05T00:00:00+02:00",
"2026-08-06T00:00:00+02:00"
],
"read": "OK",
"http_bytes": 1136556,
"attempts": 1,
"samples": 16655,
"non_numeric_states": [],
"first": "2026-08-04T22:00:00+00:00",
"last": "2026-08-05T21:59:56.189152+00:00",
"gaps": [],
"covered_span_s": 86396.2,
"mean_cadence_s": 5.188,
"file": "p1-net-2026-08-05.jsonl.gz",
"bytes_gz": 142561,
"bytes_raw": 919827,
"sha256_raw": "dd327685c6f322bfaa49bc5bf228301e790e5a96fd7c23c487b845e44a962db4",
"sha256_gz": "5ff7a1336c49ba38b8058820181dd8ed9c2b8db41b5a3a52412a5a3d8c515332"
},
{
"date": "2026-08-06",
"window": [
"2026-08-06T00:00:00+02:00",
"2026-08-07T00:00:00+02:00"
],
"read": "OK",
"http_bytes": 1124419,
"attempts": 1,
"samples": 16412,
"non_numeric_states": [],
"first": "2026-08-05T22:00:00+00:00",
"last": "2026-08-06T21:59:57.192711+00:00",
"gaps": [],
"covered_span_s": 86397.2,
"mean_cadence_s": 5.265,
"file": "p1-net-2026-08-06.jsonl.gz",
"bytes_gz": 142313,
"bytes_raw": 910849,
"sha256_raw": "7cd1fe8315e24dc6391693c49d6306b0c0cf9b6c3a478e457da921001cea930c",
"sha256_gz": "9108f169d645b9da07d4ae310666a1365ea07275ff311cd60adad1b702edbf11"
},
{
"date": "2026-08-07",
"window": [
"2026-08-07T00:00:00+02:00",
"2026-08-08T00:00:00+02:00"
],
"read": "OK",
"http_bytes": 1087531,
"attempts": 1,
"samples": 15952,
"non_numeric_states": [],
"first": "2026-08-06T22:00:00+00:00",
"last": "2026-08-07T21:59:58.195053+00:00",
"gaps": [],
"covered_span_s": 86398.2,
"mean_cadence_s": 5.416,
"file": "p1-net-2026-08-07.jsonl.gz",
"bytes_gz": 135979,
"bytes_raw": 879941,
"sha256_raw": "e0f67a9214980e2fd4893208cb402165065dadce2105ce1581c6b1d49952f39a",
"sha256_gz": "b70b84f3743d1d84055c911bcd5589cb8f0371e8916bde741308c5bb50702c29"
},
{
"date": "2026-08-08",
"window": [
"2026-08-08T00:00:00+02:00",
"2026-08-09T00:00:00+02:00"
],
"read": "OK",
"http_bytes": 1058569,
"attempts": 1,
"samples": 15468,
"non_numeric_states": [],
"first": "2026-08-07T22:00:00+00:00",
"last": "2026-08-08T21:59:52.805887+00:00",
"gaps": [],
"covered_span_s": 86392.8,
"mean_cadence_s": 5.586,
"file": "p1-net-2026-08-08.jsonl.gz",
"bytes_gz": 134025,
"bytes_raw": 857271,
"sha256_raw": "0be14ca7593b4c7d68570115cc26e24f6a26ab87fe3c168a8b942b167e8d4f68",
"sha256_gz": "d93dcc8ca3eae03af13b9ae36acd5ab1eaa1e7ee93c237d386e8ded1c61f5906"
},
{
"date": "2026-08-09",
"window": [
"2026-08-09T00:00:00+02:00",
"2026-08-10T00:00:00+02:00"
],
"read": "OK",
"http_bytes": 1059349,
"attempts": 1,
"samples": 15508,
"non_numeric_states": [],
"first": "2026-08-08T22:00:00+00:00",
"last": "2026-08-09T21:59:58.178998+00:00",
"gaps": [],
"covered_span_s": 86398.2,
"mean_cadence_s": 5.572,
"file": "p1-net-2026-08-09.jsonl.gz",
"bytes_gz": 135697,
"bytes_raw": 857531,
"sha256_raw": "f4793799173c502fcee5f78e2d9b0dcc984b5d2d8bd2fc0db0cd0f8d403733b3",
"sha256_gz": "2fea6c5c8b1452d72ad5aa3b0ae9755bb2ea08071514c08b1a3b1155ef457cf1"
},
{
"date": "2026-08-10",
"window": [
"2026-08-10T00:00:00+02:00",
"2026-08-11T00:00:00+02:00"
],
"read": "OK",
"http_bytes": 1066721,
"attempts": 1,
"samples": 15594,
"non_numeric_states": [],
"first": "2026-08-09T22:00:00+00:00",
"last": "2026-08-10T21:59:59.170056+00:00",
"gaps": [],
"covered_span_s": 86399.2,
"mean_cadence_s": 5.541,
"file": "p1-net-2026-08-10.jsonl.gz",
"bytes_gz": 136682,
"bytes_raw": 863785,
"sha256_raw": "ff5c3fa419505127a51acc56dfc13e8437e4ec2c13a11c8d8b2d6c3e20e2410e",
"sha256_gz": "4fd30e495f4e6d1c8501d05c23f9891ac34364d86a9c55ac825d52b2ebb31023"
},
{
"date": "2026-08-11",
"window": [
"2026-08-11T00:00:00+02:00",
"2026-08-12T00:00:00+02:00"
],
"read": "OK",
"http_bytes": 1056281,
"attempts": 1,
"samples": 15371,
"non_numeric_states": [],
"first": "2026-08-10T22:00:00+00:00",
"last": "2026-08-11T21:59:58.608150+00:00",
"gaps": [
{
"from": "2026-08-11T08:00:14.121653+00:00",
"to": "2026-08-11T08:02:54.427007+00:00",
"seconds": 160.305
},
{
"from": "2026-08-11T17:04:18.517592+00:00",
"to": "2026-08-11T17:08:41.759777+00:00",
"seconds": 263.242
}
],
"covered_span_s": 86398.6,
"mean_cadence_s": 5.621,
"file": "p1-net-2026-08-11.jsonl.gz",
"bytes_gz": 133711,
"bytes_raw": 856244,
"sha256_raw": "67c2a740019f8908405b96b3436cd953af27baead2957acc7c1dcf10b37ac94e",
"sha256_gz": "4f8c553edc9051644bd7baa659f6f92a8b5f5ce12a0410c8b5235d1e6c3084c9"
},
{
"date": "2026-08-12",
"window": [
"2026-08-12T00:00:00+02:00",
"2026-08-13T00:00:00+02:00"
],
"read": "OK",
"http_bytes": 1124945,
"attempts": 1,
"samples": 16432,
"non_numeric_states": [],
"first": "2026-08-11T22:00:00+00:00",
"last": "2026-08-12T21:59:58.648966+00:00",
"gaps": [],
"covered_span_s": 86398.6,
"mean_cadence_s": 5.258,
"file": "p1-net-2026-08-12.jsonl.gz",
"bytes_gz": 136903,
"bytes_raw": 911115,
"sha256_raw": "73c8a1626640226ddffb32d564557d1cbe57a15367ea1ba3632934e15a1413dc",
"sha256_gz": "acec87065b7de2c605db00504ec5a9b3c99584620dfb3b67194e2cf9464d6a5f"
},
{
"date": "2026-08-13",
"window": [
"2026-08-13T00:00:00+02:00",
"2026-08-14T00:00:00+02:00"
],
"read": "OK",
"http_bytes": 1126742,
"attempts": 1,
"samples": 16473,
"non_numeric_states": [],
"first": "2026-08-12T22:00:00+00:00",
"last": "2026-08-13T21:59:57.562043+00:00",
"gaps": [],
"covered_span_s": 86397.6,
"mean_cadence_s": 5.245,
"file": "p1-net-2026-08-13.jsonl.gz",
"bytes_gz": 136221,
"bytes_raw": 912379,
"sha256_raw": "1d9a16c529174bd8c74625a742c46d98de4acf7a045f83df8bdbac22fa86e8e7",
"sha256_gz": "adfef36f629decf54c625f2dbfe6b4dab9441218c42557c90ac7f6d331943a59"
},
{
"date": "2026-08-14",
"window": [
"2026-08-14T00:00:00+02:00",
"2026-08-15T00:00:00+02:00"
],
"read": "OK",
"http_bytes": 1124413,
"attempts": 1,
"samples": 16427,
"non_numeric_states": [],
"first": "2026-08-13T22:00:00+00:00",
"last": "2026-08-14T21:59:55.611487+00:00",
"gaps": [],
"covered_span_s": 86395.6,
"mean_cadence_s": 5.26,
"file": "p1-net-2026-08-14.jsonl.gz",
"bytes_gz": 135570,
"bytes_raw": 910648,
"sha256_raw": "dc1417881e54fe215e9fcd4ed643d2482a277d61f8f27f25e2ff1e2cba29f7a8",
"sha256_gz": "d4eff781cd16a83fd1be9e643fee5bb5d5897e7d45bb9865972a7304d92c84a4"
},
{
"date": "2026-08-15",
"window": [
"2026-08-15T00:00:00+02:00",
"2026-08-16T00:00:00+02:00"
],
"read": "OK",
"http_bytes": 1124461,
"attempts": 1,
"samples": 16516,
"non_numeric_states": [],
"first": "2026-08-14T22:00:00+00:00",
"last": "2026-08-15T21:59:56.581991+00:00",
"gaps": [],
"covered_span_s": 86396.6,
"mean_cadence_s": 5.231,
"file": "p1-net-2026-08-15.jsonl.gz",
"bytes_gz": 137670,
"bytes_raw": 909539,
"sha256_raw": "f07a242faed68313512e0363d914846522ff839315ad80b55689072ac74e8a69",
"sha256_gz": "082314c6003c2208752acc4614b9809f06735d01e216b935ea94faf578c5598e"
},
{
"date": "2026-08-16",
"window": [
"2026-08-16T00:00:00+02:00",
"2026-08-17T00:00:00+02:00"
],
"read": "OK",
"http_bytes": 1127871,
"attempts": 1,
"samples": 16552,
"non_numeric_states": [],
"first": "2026-08-15T22:00:00+00:00",
"last": "2026-08-16T21:59:59.527710+00:00",
"gaps": [],
"covered_span_s": 86399.5,
"mean_cadence_s": 5.22,
"file": "p1-net-2026-08-16.jsonl.gz",
"bytes_gz": 138347,
"bytes_raw": 912481,
"sha256_raw": "a44e5d961600a539ddf824d5d211ef319833666b7598e5939a6cdf2cb1e3581f",
"sha256_gz": "8f6511e52f5be9187f422021abc93a5fa8b698b4c785877d69d15dd6de106fd8"
},
{
"date": "2026-08-17",
"window": [
"2026-08-17T00:00:00+02:00",
"2026-08-18T00:00:00+02:00"
],
"read": "OK",
"http_bytes": 1133721,
"attempts": 1,
"samples": 16627,
"non_numeric_states": [],
"first": "2026-08-16T22:00:00+00:00",
"last": "2026-08-17T21:59:59.685699+00:00",
"gaps": [
{
"from": "2026-08-17T17:27:00.599126+00:00",
"to": "2026-08-17T17:28:20.389628+00:00",
"seconds": 79.791
}
],
"covered_span_s": 86399.7,
"mean_cadence_s": 5.197,
"file": "p1-net-2026-08-17.jsonl.gz",
"bytes_gz": 140214,
"bytes_raw": 917356,
"sha256_raw": "70cce79b3732f292f7f58f0b2655bdb4a00a20a6530f1f50dac62ef5f039788b",
"sha256_gz": "e2f9b461c4db7902e1a3d30b439ebc11ebcd9618a72d12f10e5131f38fb437bf"
},
{
"date": "2026-08-18",
"window": [
"2026-08-18T00:00:00+02:00",
"2026-08-19T00:00:00+02:00"
],
"read": "OK",
"http_bytes": 1074019,
"attempts": 1,
"samples": 15699,
"non_numeric_states": [
{
"t": "2026-08-18T02:03:54.417106+00:00",
"state": "unavailable"
},
{
"t": "2026-08-18T04:10:41.786299+00:00",
"state": "unavailable"
}
],
"first": "2026-08-17T22:00:00+00:00",
"last": "2026-08-18T21:59:54.501766+00:00",
"gaps": [
{
"from": "2026-08-18T02:02:59.633845+00:00",
"to": "2026-08-18T02:04:38.694366+00:00",
"seconds": 99.061
},
{
"from": "2026-08-18T04:09:54.292049+00:00",
"to": "2026-08-18T04:11:38.500238+00:00",
"seconds": 104.208
}
],
"covered_span_s": 86394.5,
"mean_cadence_s": 5.504,
"file": "p1-net-2026-08-18.jsonl.gz",
"bytes_gz": 135894,
"bytes_raw": 869570,
"sha256_raw": "68cd44ac56099ee38f0bba4c32d7d17d33b92d28a99d27419f53c22374491ca6",
"sha256_gz": "d6c97508f805aff040d2b4ed4e06c0e7373db2ea6227c7d79ef24c8c79074115"
},
{
"date": "2026-08-19",
"window": [
"2026-08-19T00:00:00+02:00",
"2026-08-20T00:00:00+02:00"
],
"read": "OK",
"http_bytes": 989720,
"attempts": 1,
"samples": 14549,
"non_numeric_states": [],
"first": "2026-08-18T22:00:00+00:00",
"last": "2026-08-19T21:59:56.556610+00:00",
"gaps": [
{
"from": "2026-08-19T01:33:29.599224+00:00",
"to": "2026-08-19T01:34:01.653383+00:00",
"seconds": 32.054
}
],
"covered_span_s": 86396.6,
"mean_cadence_s": 5.939,
"file": "p1-net-2026-08-19.jsonl.gz",
"bytes_gz": 126345,
"bytes_raw": 800369,
"sha256_raw": "0f11ce0cee43cbd7bdb08dc48b202e58c442157ac08b2cda5b64bbab9bd56300",
"sha256_gz": "13d61b7da903877c8ae7813b833cb5836ec04a1cf1efd0e1fa87e916bef95fd5"
},
{
"date": "2026-08-20",
"window": [
"2026-08-20T00:00:00+02:00",
"2026-08-21T00:00:00+02:00"
],
"read": "OK",
"http_bytes": 1068038,
"attempts": 1,
"samples": 15600,
"non_numeric_states": [],
"first": "2026-08-19T22:00:00+00:00",
"last": "2026-08-20T21:59:56.742604+00:00",
"gaps": [
{
"from": "2026-08-20T02:11:56.607373+00:00",
"to": "2026-08-20T02:12:38.840458+00:00",
"seconds": 42.233
},
{
"from": "2026-08-20T20:42:04.623102+00:00",
"to": "2026-08-20T20:43:41.666543+00:00",
"seconds": 97.043
}
],
"covered_span_s": 86396.7,
"mean_cadence_s": 5.539,
"file": "p1-net-2026-08-20.jsonl.gz",
"bytes_gz": 139693,
"bytes_raw": 865024,
"sha256_raw": "2612153963951dd13fe310ad7fbb5bec2e195db56fd99fd963134c8badae25ba",
"sha256_gz": "362f2ee3d9d7f23f9051ba78993c5af7443dabb3b5f16339efc673444720c892"
},
{
"date": "2026-08-21",
"window": [
"2026-08-21T00:00:00+02:00",
"2026-08-22T00:00:00+02:00"
],
"read": "OK",
"http_bytes": 1118002,
"attempts": 1,
"samples": 16383,
"non_numeric_states": [],
"first": "2026-08-20T22:00:00+00:00",
"last": "2026-08-21T21:59:57.771588+00:00",
"gaps": [],
"covered_span_s": 86397.8,
"mean_cadence_s": 5.274,
"file": "p1-net-2026-08-21.jsonl.gz",
"bytes_gz": 139105,
"bytes_raw": 904809,
"sha256_raw": "933d9a6899f59c128d0d9b84d6944cea63b1ad58dc57ac52e3e476f9c616f07b",
"sha256_gz": "a563581a9a3338af173abb99a200db32881ddaf893d2458f5d8de59b5ec6041f"
},
{
"date": "2026-08-22",
"window": [
"2026-08-22T00:00:00+02:00",
"2026-08-23T00:00:00+02:00"
],
"read": "OK",
"http_bytes": 1129094,
"attempts": 1,
"samples": 16520,
"non_numeric_states": [],
"first": "2026-08-21T22:00:00+00:00",
"last": "2026-08-22T21:59:56.913786+00:00",
"gaps": [
{
"from": "2026-08-21T23:05:20.035692+00:00",
"to": "2026-08-21T23:07:51.147719+00:00",
"seconds": 151.112
},
{
"from": "2026-08-21T23:07:56.966604+00:00",
"to": "2026-08-21T23:08:27.695101+00:00",
"seconds": 30.728
}
],
"covered_span_s": 86396.9,
"mean_cadence_s": 5.23,
"file": "p1-net-2026-08-22.jsonl.gz",
"bytes_gz": 141564,
"bytes_raw": 914120,
"sha256_raw": "39ccdf67c806344490f791648822cd2cd14d73ea7cc0b6e8572a1e15e8f74641",
"sha256_gz": "5c46f1879a723f9986d521124200cab839af2a4722b76bc97c6f6f59d0df65a2"
},
{
"date": "2026-08-23",
"window": [
"2026-08-23T00:00:00+02:00",
"2026-08-24T00:00:00+02:00"
],
"read": "OK",
"http_bytes": 1107164,
"attempts": 1,
"samples": 16351,
"non_numeric_states": [],
"first": "2026-08-22T22:00:00+00:00",
"last": "2026-08-23T21:59:56.921115+00:00",
"gaps": [],
"covered_span_s": 86396.9,
"mean_cadence_s": 5.284,
"file": "p1-net-2026-08-23.jsonl.gz",
"bytes_gz": 136277,
"bytes_raw": 894387,
"sha256_raw": "ffb15367bf3c98eff8a5600e4858ac99778b597c03d0a4f6154e6971b8f98a44",
"sha256_gz": "3fa76981758a468ba0aa68b50fe68d5bdb1ef38cd7faec2b6ffdb61c9ddb2db2"
},
{
"date": "2026-08-24",
"window": [
"2026-08-24T00:00:00+02:00",
"2026-08-25T00:00:00+02:00"
],
"read": "OK",
"http_bytes": 1122175,
"attempts": 1,
"samples": 16584,
"non_numeric_states": [],
"first": "2026-08-23T22:00:00+00:00",
"last": "2026-08-24T21:59:57.940474+00:00",
"gaps": [],
"covered_span_s": 86397.9,
"mean_cadence_s": 5.21,
"file": "p1-net-2026-08-24.jsonl.gz",
"bytes_gz": 136834,
"bytes_raw": 906369,
"sha256_raw": "30465d5ff51220201b4a79341e5da7bfc3d88290465b1c9d886ba94eee8dd234",
"sha256_gz": "5103088e047bfcbd9b3f55521f431b01cd27de10c2642e00281a13faa762bdd9"
},
{
"date": "2026-08-25",
"window": [
"2026-08-25T00:00:00+02:00",
"2026-08-26T00:00:00+02:00"
],
"read": "OK",
"http_bytes": 1110567,
"attempts": 1,
"samples": 16451,
"non_numeric_states": [
{
"t": "2026-08-25T01:52:02.104225+00:00",
"state": "unavailable"
}
],
"first": "2026-08-24T22:00:00+00:00",
"last": "2026-08-25T21:59:56.883744+00:00",
"gaps": [
{
"from": "2026-08-25T01:51:25.942719+00:00",
"to": "2026-08-25T01:52:53.203963+00:00",
"seconds": 87.261
}
],
"covered_span_s": 86396.9,
"mean_cadence_s": 5.252,
"file": "p1-net-2026-08-25.jsonl.gz",
"bytes_gz": 135890,
"bytes_raw": 896416,
"sha256_raw": "0e7c86b2b74f2108bc7f5f5d2de2627caaafe473ca4ae18515534dff10526e26",
"sha256_gz": "2a5411c10d8d3b271f133c62c04bd722279b48b08d7376084fbad6cc6dd66d76"
},
{
"date": "2026-08-26",
"window": [
"2026-08-26T00:00:00+02:00",
"2026-08-27T00:00:00+02:00"
],
"read": "OK",
"http_bytes": 1123610,
"attempts": 1,
"samples": 16542,
"non_numeric_states": [],
"first": "2026-08-25T22:00:00+00:00",
"last": "2026-08-26T21:59:58.915457+00:00",
"gaps": [],
"covered_span_s": 86398.9,
"mean_cadence_s": 5.223,
"file": "p1-net-2026-08-26.jsonl.gz",
"bytes_gz": 139301,
"bytes_raw": 908350,
"sha256_raw": "88d72c1b9f51707d62e744f40402de4260a04617875b85c65d2df6079c6c84ca",
"sha256_gz": "0661588fbc0c6c42825b67d483c8818c070405c1002424b3f1d61d8fdadb6370"
},
{
"date": "2026-08-27",
"window": [
"2026-08-27T00:00:00+02:00",
"2026-08-28T00:00:00+02:00"
],
"read": "OK",
"http_bytes": 1122433,
"attempts": 1,
"samples": 16573,
"non_numeric_states": [],
"first": "2026-08-26T22:00:00+00:00",
"last": "2026-08-27T21:59:58.538446+00:00",
"gaps": [
{
"from": "2026-08-27T18:50:29.030586+00:00",
"to": "2026-08-27T18:52:22.938470+00:00",
"seconds": 113.908
}
],
"covered_span_s": 86398.5,
"mean_cadence_s": 5.214,
"file": "p1-net-2026-08-27.jsonl.gz",
"bytes_gz": 138009,
"bytes_raw": 906770,
"sha256_raw": "528ab8ee10a46275d2e91d56ef2ed847e5932fae76a1752e6f2e9828dbfa9865",
"sha256_gz": "5cacc8c5788f43d6e6e2f569445fa82d9edc5a63b1f082f9a1d6a3bb0b404260"
},
{
"date": "2026-08-28",
"window": [
"2026-08-28T00:00:00+02:00",
"2026-08-29T00:00:00+02:00"
],
"read": "OK",
"http_bytes": 1114796,
"attempts": 1,
"samples": 16456,
"non_numeric_states": [],
"first": "2026-08-27T22:00:00+00:00",
"last": "2026-08-28T21:59:58.515555+00:00",
"gaps": [],
"covered_span_s": 86398.5,
"mean_cadence_s": 5.251,
"file": "p1-net-2026-08-28.jsonl.gz",
"bytes_gz": 135917,
"bytes_raw": 900654,
"sha256_raw": "f89838bc9f61af074c17817e4a6eab037318f38fa3c65dad3edfa2106abbc9fb",
"sha256_gz": "97090b605f67dcc1f84dea2c51d4832dfe1c2af497a4f4cfe50ecb51024d9b4c"
},
{
"date": "2026-08-29",
"window": [
"2026-08-29T00:00:00+02:00",
"2026-08-30T00:00:00+02:00"
],
"read": "OK",
"http_bytes": 1092983,
"attempts": 1,
"samples": 16132,
"non_numeric_states": [],
"first": "2026-08-28T22:00:00+00:00",
"last": "2026-08-29T21:59:57.574524+00:00",
"gaps": [
{
"from": "2026-08-29T00:03:20.539844+00:00",
"to": "2026-08-29T00:03:50.569581+00:00",
"seconds": 30.03
}
],
"covered_span_s": 86397.6,
"mean_cadence_s": 5.356,
"file": "p1-net-2026-08-29.jsonl.gz",
"bytes_gz": 134210,
"bytes_raw": 883053,
"sha256_raw": "896d4c9d660be4faabc5a088323e246e257877d5ff6bd0ec084b785480d76e12",
"sha256_gz": "b6f264cd3afba63209123a27490e7e1c3ae70a86731d7ea05ae67f88917f136f"
},
{
"date": "2026-08-30",
"window": [
"2026-08-30T00:00:00+02:00",
"2026-08-31T00:00:00+02:00"
],
"read": "OK",
"http_bytes": 1118895,
"attempts": 1,
"samples": 16490,
"non_numeric_states": [],
"first": "2026-08-29T22:00:00+00:00",
"last": "2026-08-30T21:59:58.533323+00:00",
"gaps": [],
"covered_span_s": 86398.5,
"mean_cadence_s": 5.24,
"file": "p1-net-2026-08-30.jsonl.gz",
"bytes_gz": 138429,
"bytes_raw": 904311,
"sha256_raw": "e704818efb58bb6c505791bc9eab2e9476bf48ff8911d0e79b401fd35b529fa0",
"sha256_gz": "9052fead2418bff3083bec3ae8ce64d6b9f6224b668f4bb510c79775f66c5b79"
}
],
"summary": {
"days_requested": 30,
"days_read": 30,
"days_failed": 0,
"samples": 485841,
"bytes_gz": 4126003,
"empty_days": []
}
}
+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
+301 -32
View File
@@ -20,12 +20,15 @@ WHAT THIS FILE IS DEFENDING, in the order the card's acceptance criteria name it
exist - static_tariff's required `peak_guard_active` interlock and
arbiter.py's clause 2 - both driven end to end, plus the third state
(the guard never ran) that neither of them can express on its own.
AC4 NET-POSITIVE ACROSS 12 MONTHS OF REPLAYED PRICES. ⚠️ SEE SECTION 7. THIS
REPOSITORY HOLDS NO PRICE HISTORY AT ALL - `scenarios/` carries two days
of real METER data and nothing else - so the criterion as written cannot
be met, and it is NOT redefined here into something that can be. What
section 7 does instead is stated there in full, and what it cannot say is
stated with it.
AC4 NET-POSITIVE ACROSS 12 MONTHS OF REPLAYED PRICES. ⚠️ MET AS OF DATA-02,
AND SECTIONS 7 AND 7B DO DIFFERENT HALVES OF IT. 7B replays twelve months
of REAL EPEX BE day-ahead prices - `scenarios/epex-be-dayahead-*.json`,
8760 hours, public data under CC BY 4.0 - through the shipped `decide()`,
and reports the euro figure at the shipped threshold. Section 7 keeps the
SYNTHETIC year, because the real one turns out to be unable to grade §17
at all: not one of its 365 days has a negative DEAREST hour, so a count
of zero negative-price discharges over it grades nothing. 7B asserts that
degeneracy rather than quietly reporting the zero.
THREE RULES THIS FILE HOLDS ITSELF TO, because the reviewer will:
@@ -59,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
@@ -503,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.
# --------------------------------------------------------------------------- #
@@ -786,34 +806,39 @@ check("...and it is still ARMED when arbitrage is idle and the loop wins, so "
print()
print("7. AC4 - 12 months of replayed prices, and what could NOT be measured")
# ⚠️ READ THIS BEFORE READING THE NUMBERS BELOW.
# ⚠️ READ THIS BEFORE READING THE NUMBERS BELOW. THIS SECTION IS THE SYNTHETIC
# YEAR, AND IT IS NOT AC4's EVIDENCE ANY MORE - SECTION 7B IS.
#
# The acceptance criterion is "net-positive across 12 months of replayed prices
# in simulation". THIS REPOSITORY CONTAINS NO PRICE HISTORY. `scenarios/` holds
# three gzipped captures and all three are P1 METER data - two days of net power
# from the reference house plus one age capture. There is no EPEX archive, no
# supplier export, and no CSV of a past year anywhere in the tree.
# When OPT-04 shipped, this repository held no price history: `scenarios/`
# carried three gzipped P1 METER captures and nothing else. AC4 was therefore
# reported NOT MET rather than redefined into something passable, which is what
# TARIFF-01 and SAFETY-07 had both been upheld for doing.
#
# TARIFF-01 and SAFETY-07 both hit an unmeetable criterion and both DECLINED to
# redefine it into one they could pass, and both were upheld for it. So:
# DATA-02 pointed out that the missing ingredient was never a capture. EPEX BE
# day-ahead is PUBLIC DATA; the 30-day meter criterion it was being carried
# beside genuinely needs waiting, and this one only ever needed a fetch. Section
# 7B replays the real year and AC4 is met there.
#
# AC4 IS NOT MET, AND IT IS NOT RESTATED. What follows is not a replay of the
# Belgian market; it is a replay of a SYNTHETIC year, and a euro figure from a
# synthetic year grades the generator that produced it, not the strategy.
# ⚠️ SO WHY IS THE SYNTHETIC YEAR STILL HERE? Because the real one cannot grade
# §17, and 7B proves that rather than assuming it. Across all 365 real days, the
# number whose DEAREST hour is priced below zero is ZERO - raw wholesale and
# all-in alike - so "no discharges into a negative hour" over the real year is a
# count of something that never had the chance to happen. Deleting the guard
# would not change it. This section's generator drives a summer midday block
# negative ON PURPOSE, and it is the only thing in this file that puts a
# negative price where the strategy would otherwise sell.
#
# What the replay is FOR is the half of AC4 that does not need real prices. Net
# positivity here is not an empirical outcome to be hoped for - it is a property
# of the decision rule, and the replay's job is to demonstrate that the property
# holds on every trade the strategy actually chose, over a year of varied days
# including negative-price ones. Stated as an invariant:
# What this section establishes is the half of AC4 that does not need real
# prices, and it is a property of the decision rule rather than an outcome to be
# hoped for:
#
# every executed round trip has (sell - buy) >= required >= threshold,
# so its benefit net of the threshold is >= 0, on every day, always.
#
# That is asserted per trade below, over 365 days. What it does NOT establish -
# and no synthetic series could - is how OFTEN a real Belgian year clears the
# threshold, which is the actual open question and the reason the shipped
# default is a product decision rather than a number this card picked.
# That is asserted per trade below, over 365 varied days including negative ones.
# HOW OFTEN a real Belgian year clears the threshold is the other question, it
# is the one the product owner's open decision turns on, and section 7B is the
# only place in this file that answers it.
def synth_day(n):
"""A synthetic all-in day-ahead day. Deterministic, seeded by day number.
@@ -920,12 +945,256 @@ check("the shipped threshold is strictly more selective than the loose one on "
"the same year - the parameter does what it says, at whatever value the "
"owner sets it to",
len(_sh_trades) < len(_trades))
check("AC4 IS REPORTED AS NOT MET rather than redefined: this file says so in "
"section 7's preamble, and there is no price history in the repository "
"to meet it with",
not any(f.endswith((".csv", ".json.gz"))
and "price" in f.lower()
for f in os.listdir(os.path.join(HERE, "scenarios"))))
check("...and the shipped default was NOT moved to make any of this look "
"better: app/arbitrage.py reads the threshold through price_option() and "
"names no number of its own",
"0.10" not in open(os.path.join(HERE, "app", "arbitrage.py"),
encoding="utf-8").read().split('"""', 2)[2])
# --------------------------------------------------------------------------- #
print()
print("7B. AC4 - twelve months of REAL EPEX BE prices, replayed")
# THE DATASET, AND WHAT IT IS NOT.
#
# `scenarios/epex-be-dayahead-2025-09-01_2026-09-01.json` - 8760 hourly Belgian
# day-ahead auction prices, 2025-09-01 to 2026-09-01 Brussels-local, fetched by
# `scenarios/fetch_epex_be.py` from Fraunhofer ISE's Energy-Charts API, which
# publishes the BE zone under CC BY 4.0 from Bundesnetzagentur | SMARD.de. The
# licence was checked BEFORE the data was committed, because the same API serves
# other zones under private-use-only terms; the script refuses to write a file
# whose per-response `license_info` stops saying CC BY 4.0. Provenance,
# attribution and the DST accounting live in the file's own `provenance` block
# and `fetch_epex_be.py --verify` re-derives every claim in it.
#
# ⚠️ THE FIGURES IN THAT FILE ARE RAW WHOLESALE, NOT ALL-IN, AND THIS SECTION IS
# WHERE THE DIFFERENCE IS MADE VISIBLE. §9.3's canonical point is all-in; the
# committed file says `"all_in": false` and carries the markup/tax assumption as
# NUMBERS TO APPLY rather than numbers already applied - TARIFF-02's
# double-counting trap, avoided by never baking the guess in. `_all_in()` below
# applies it in one place where a reader can watch it happen, and both replays
# are run, so exactly how much of the answer rests on the guess is reported
# rather than hidden.
import json # noqa: E402
from collections import defaultdict # noqa: E402
_DS_PATH = os.path.join(HERE, "scenarios",
"epex-be-dayahead-2025-09-01_2026-09-01.json")
_DS = derived(lambda: json.load(open(_DS_PATH, encoding="utf-8")))
_ASSUME = _DS["provenance"]["all_in_assumption"]
def _all_in(wholesale):
"""The stated assumption, applied HERE and nowhere in the committed data.
all_in = (wholesale + markup + network_and_levies) * (1 + vat), with the
coefficients read from the dataset's own provenance block rather than
retyped - a second copy is a second thing to disagree with the file.
"""
return round((wholesale + _ASSUME["markup_eur_per_kwh"]
+ _ASSUME["network_and_levies_eur_per_kwh"])
* (1.0 + _ASSUME["vat_fraction"]), 6)
def _days(price_of):
"""The dataset as Brussels calendar days of `PricePoint`s, in order.
⚠️ GROUPED BY THE LOCAL DATE IN THE `start` STRING, NOT BY SLICING 24 AT A
TIME. Two of these days are not 24 hours long, which is the whole DST check,
and a fixed stride would put October's 25th hour into the next day and
misalign every day after it.
"""
out = defaultdict(list)
for p in _DS["prices"]:
out[p["start"][:10]].append(
PricePoint(start=datetime.fromisoformat(p["start"]),
eur_per_kwh=price_of(p["eur_per_kwh"]),
provisional=bool(p["provisional"])))
return [out[k] for k in sorted(out)]
_AI_DAYS = derived(lambda: _days(_all_in))
_RAW_DAYS = derived(lambda: _days(lambda w: w))
# ---- the dataset is not degenerate, asserted BEFORE anything is graded ------
_lens = [len(d) for d in _AI_DAYS]
check(f"the replay has {len(_AI_DAYS)} Brussels days and {sum(_lens)} hourly "
f"points, which is a full year rather than a fortnight repeated",
len(_AI_DAYS) == 365 and sum(_lens) == 8760)
check(f"...and the day lengths are {sorted(set(_lens))}, so BOTH DST days are "
f"in it: an importer that produced 24 everywhere would have lost an hour "
f"in October and invented one in March",
sorted(set(_lens)) == [23, 24, 25]
and _lens.count(23) == 1 and _lens.count(25) == 1)
_dst_day = [d for d in _AI_DAYS if len(d) == 25][0]
check("...and the 25-hour day's two 02:00 points are two different INSTANTS at "
"two different offsets, which is what `at()` has to tell apart",
len({p.start for p in _dst_day}) == 25
and {p.start.utcoffset() for p in _dst_day}
== {timedelta(hours=1), timedelta(hours=2)})
_ai_spreads = sorted(round(max(p.eur_per_kwh for p in d)
- min(p.eur_per_kwh for p in d), 6)
for d in _AI_DAYS)
_raw_spreads = sorted(round(max(p.eur_per_kwh for p in d)
- min(p.eur_per_kwh for p in d), 6)
for d in _RAW_DAYS)
_req_shipped = required_spread(_shipped, NO_WEATHER)
_clears = [s for s in _ai_spreads if s > _req_shipped]
check(f"...and the year's daily spreads STRADDLE the shipped requirement of "
f"{_req_shipped:.4f} EUR/kWh - {len(_clears)} of {len(_ai_spreads)} days "
f"clear it - so the threshold is grading something. A year in which every "
f"day cleared, or none did, would grade nothing at any value",
0 < len(_clears) < len(_ai_spreads))
check(f"...and the spreads are not one repeated number: median "
f"{_ai_spreads[len(_ai_spreads) // 2]:.4f}, min {_ai_spreads[0]:.4f}, "
f"max {_ai_spreads[-1]:.4f}",
len(set(_ai_spreads)) > 300 and _ai_spreads[-1] > 4 * _ai_spreads[0])
# ---- the assumption's arithmetic, asserted rather than asserted-about -------
check("the ADDITIVE half of the all-in assumption cancels out of every daily "
"spread, so the trade counts below do not depend on the markup guess at "
"all - only on the VAT multiplier",
all(near(a, r * (1.0 + _ASSUME["vat_fraction"]), 1e-6)
for a, r in zip(_ai_spreads, _raw_spreads)))
# ---- ⚠️ THE DEGENERACY THAT KEEPS SECTION 7 ALIVE --------------------------
_raw_neg_h = sum(1 for d in _RAW_DAYS for p in d if p.eur_per_kwh < 0)
_ai_neg_h = sum(1 for d in _AI_DAYS for p in d if p.eur_per_kwh < 0)
_raw_neg_dear = sum(1 for d in _RAW_DAYS if max(p.eur_per_kwh for p in d) < 0)
_ai_neg_dear = sum(1 for d in _AI_DAYS if max(p.eur_per_kwh for p in d) < 0)
check(f"the real year DOES contain negative hours - {_raw_neg_h} of them at "
f"wholesale, {_ai_neg_h} still negative once the assumed markup and "
f"charges are added - so §17 is a live case on this market and not a "
f"hypothetical", _raw_neg_h > 100 and _ai_neg_h > 0)
check(f"BUT NOT ONE OF THE 365 DAYS HAS A NEGATIVE DEAREST HOUR "
f"({_raw_neg_dear} raw, {_ai_neg_dear} all-in), and the guard is on the "
f"hour being SOLD INTO. So a count of zero negative-price discharges over "
f"this year would be a count of something that could not happen, and "
f"section 7's synthetic year stays because it is the only thing here that "
f"puts a negative price where the strategy would sell",
_raw_neg_dear == 0 and _ai_neg_dear == 0)
def replay_real(days, threshold, unc, *, soc0=50.0, floor=20.0, ceiling=95.0):
"""The shipped `decide()` over the real year. Returns the ledger, nothing else.
One `TariffPlan` per Brussels day, so "the cheapest hour" means the cheapest
hour of that day - the same shape as section 7's replay, and the same shape
a site with a day-ahead feed actually sees.
"""
soc = soc0
trades, holdings, bad, neg_sells = [], [], [], 0
for day in days:
plan = TariffPlan(
PriceRead.series(day, PriceProduct.DAY_AHEAD, "generic_dayahead",
day[0].start), None, "provider")
open_buy = None
for p in day:
d = decide(plan, p.start + timedelta(minutes=30),
peak_guard_active=False, soc=soc,
min_spread_eur_kwh=threshold, uncertainty=unc,
charge_w=MAX_W, discharge_w=MAX_W,
soc_floor_pct=floor, soc_ceiling_pct=ceiling)
if d.action is None:
continue
if d.spread_eur_kwh is None or d.required_eur_kwh is None:
bad.append(p.start)
if d.action == CHARGE:
soc = min(ceiling, soc + STEP_PCT)
open_buy = (p.eur_per_kwh, d)
else:
if p.eur_per_kwh < 0:
neg_sells += 1
soc = max(floor, soc - STEP_PCT)
if open_buy is not None:
trades.append((open_buy[0], p.eur_per_kwh, d))
open_buy = None
else:
holdings.append(p.start)
return trades, holdings, bad, neg_sells
# ⚠️ AT THE SHIPPED THRESHOLD, UNTOUCHED, AND WIDENED BY FCST-03's NO-WEATHER
# FACTOR - the harsher of the two operating states, so the figure reported is
# the conservative one.
_r_trades, _r_held, _r_bad, _r_neg = derived(
lambda: replay_real(_AI_DAYS, _shipped, NO_WEATHER)) or (None,) * 4
_r_kwh = MAX_W / 1000.0
_r_net = round(sum((s - b - _shipped) * _r_kwh for b, s, _ in _r_trades), 2)
check(f"the real year traded at the SHIPPED threshold: {len(_r_trades)} "
f"completed round trips over 365 days of Belgian day-ahead prices - so "
f"the criterion is being graded on trades that happened, not on an empty "
f"ledger that is net-positive by vacuity", len(_r_trades) > 0)
check("...and every one of them carries the spread and the widened requirement "
"it cleared, so the ledger is auditable rather than a count", _r_bad == [])
check(f"...and it did NOT trade every day ({len(_r_trades)} round trips over "
f"365 days), so the threshold selected rather than waved everything "
f"through", len(_r_trades) < 365)
_r_losses = [(b, s) for b, s, _ in _r_trades if s - b < _shipped]
check(f"AC4: every completed round trip on the REAL year cleared the shipped "
f"{_shipped} EUR/kWh - {len(_r_losses)} exceptions of {len(_r_trades)}",
_r_losses == [])
_r_under = [d.spread_eur_kwh for _b, _s, d in _r_trades
if d.spread_eur_kwh < d.required_eur_kwh]
check(f"...and each cleared its own WIDENED requirement of "
f"{_req_shipped:.4f} EUR/kWh, which is the stricter statement §8.3 asks "
f"for", _r_under == [])
check(f"AC4 IS MET: twelve months of REAL replayed EPEX BE prices are "
f"NET-POSITIVE at the shipped default - {_r_net:+.2f} EUR of benefit net "
f"of the cycle cost over {len(_r_trades)} round trips of {_r_kwh:.1f} kWh "
f"each, accumulated from the trades the strategy actually chose",
_r_net > 0)
# ---- what the owner's open decision actually turns on -----------------------
# ⚠️ REPORTED, NOT SETTLED. `cycle_cost_threshold_eur` and FCST-03's 2.5/1.5 are
# the product owner's decision. DATA-02 supplies the input and changes nothing:
# every number below comes out of the same untouched `decide()`.
_r_calm = derived(lambda: replay_real(_AI_DAYS, _shipped, frozenset())[0])
_r_raw = derived(lambda: replay_real(_RAW_DAYS, _shipped, NO_WEATHER)[0])
# The threshold at which the MEDIAN day of this year clears its widened
# requirement. Derived from the observed spreads, not chosen.
_median_spread = _ai_spreads[len(_ai_spreads) // 2]
_suggested = round(_median_spread / widen_factor(NO_WEATHER), 4)
_r_sugg, _, _, _ = derived(
lambda: replay_real(_AI_DAYS, _suggested, NO_WEATHER)) or (None,) * 4
_sugg_net = round(sum((s - b - _suggested) * _r_kwh for b, s, _ in _r_sugg), 2)
print(f" [report] SHIPPED {_shipped} EUR/kWh, widened {widen_factor(NO_WEATHER)}x "
f"to {_req_shipped:.4f}: {len(_r_trades)} round trips, {_r_net:+.2f} EUR "
f"over the year. Unwidened (weather present): {len(_r_calm)} trips. On "
f"RAW wholesale instead of the assumed all-in: {len(_r_raw)} trips, so "
f"the markup/VAT guess moves the count by "
f"{len(_r_trades) - len(_r_raw):+d}.")
print(f" [report] the year's MEDIAN daily all-in spread is "
f"{_median_spread:.4f} EUR/kWh, so the threshold at which a median day "
f"clears its widened requirement is {_suggested} - and at that value the "
f"same year completes {len(_r_sugg)} round trips for {_sugg_net:+.2f} "
f"EUR. THE SHIPPED DEFAULT IS NOT CHANGED BY THIS CARD; both numbers are "
f"reported so the owner can decide between them.")
print(f" [report] and the four-developer finding stands unchanged: a STATIC "
f"day/night spread of ~0.0840 EUR/kWh still does not clear "
f"{_req_shipped:.4f}, so a static-tariff site never trades at the shipped "
f"default. What this year adds is that a DYNAMIC site does - on "
f"{len(_clears)} of its 365 days the spread was there to be taken.")
check("the loose threshold is strictly less selective than the shipped one on "
"the SAME real year - the parameter does what it says at whatever value "
"the owner sets, and neither run tuned anything",
len(_r_sugg) > len(_r_trades) > 0)
check(f"§17 held over the real year too ({_r_neg} discharges into a negative "
f"hour) - but see the degeneracy check above: on this data that zero is "
f"structural, and section 7's synthetic year is what actually grades the "
f"guard", _r_neg == 0)
check("the dataset carries its own provenance, states it is NOT all-in, and "
"keeps the markup/tax figures as an assumption rather than applying "
"them - the TARIFF-02 trap, in data form",
_DS["provenance"]["all_in"] is False
and "ASSUMPTION" in _ASSUME["status"]
and _DS["provenance"]["licence"].startswith("CC BY 4.0"))
# --------------------------------------------------------------------------- #
+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
File diff suppressed because it is too large Load Diff
+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:
+287 -51
View File
@@ -35,16 +35,39 @@ NOT allowed to be tested at:
10. THE WIRING, through the real `Controller` and its real status page.
------------------------------------------------------------------------------
⚠️ AC 3 IS NOT MET, AND PART 9 DOES NOT PRETEND OTHERWISE.
⚠️ PART 9 IS A TWO-DAY MEASUREMENT AND SAYS SO. THE 30-DAY ANSWER IS ELSEWHERE
(DATA-01), AND IT DOES NOT LAND WHERE ANYONE EXPECTED.
AC 3 asks for "the monthly peak held under the soft limit in >= 95 % of
intervals over a 30-day simulation replay". THERE IS NO 30-DAY DATASET. The
infra repo's `sim/scenarios/` holds exactly two days of this house's real meter
- 2026-08-20 (the Illusmart failure day) and 2026-08-23 (the healthy reference)
- exported on 2026-08-25 because they were about to age out of HA's recorder,
and nothing longer was ever captured. `sim/scenarios/README.md` lists the whole
inventory; the rest is RS485 bus frames, OTA witness logs and a 578-row rollback
poll, none of which carries grid power over calendar time.
intervals over a 30-day simulation replay". When this file was written there
were two days of this house's real meter - 2026-08-20 (the Illusmart failure
day) and 2026-08-23 (the healthy reference) - exported on 2026-08-25 because
they were about to age out of HA's recorder.
⚠️ AND THE SENTENCE THAT USED TO STAND HERE, "nothing longer was ever
captured", WAS TRUE ABOUT THE PAST AND WAS READ AS A CLAIM ABOUT THE FUTURE.
It was not one. HA's recorder still held the whole month; DATA-01 probed it on
2026-08-31 (230 samples in a 20-minute window at 30 days back, 0 at 45) and
exported thirty days the same day, into `scenarios/p1-net-30d-2026-08/` with
`tools/export_p1_history.py` - which is committed now precisely because the
2026-08-25 one-off was not, and its absence is what let the belief survive.
Over those thirty days the criterion measures 98.89 % UNCONTROLLED and 98.99 %
guarded, so it is met - and that is a finding about the CRITERION as much as
about the guard, because a month with no controller at all passes it. Read the
other way - the monthly PEAK itself under the soft limit - it is not met: the
guard takes August's peak from 5029.8 W to 4107.3 W, still over 3500 W. Both
numbers, and why they part company, are in
`scenarios/p1-net-30d-2026-08/README.md`.
PART 9 IS DELIBERATELY LEFT GRADING THE TWO COMMITTED DAYS. It is a per-PR
regression check and the thirty days cost about fifty seconds of replay; they
also live one directory down precisely so this file's glob does not pick them
up. `tools/replay_ac3.py` is the thing that runs the month, and it is checked
against part 6 of test_peakguard.py rather than trusted:
python3 tools/replay_ac3.py scenarios --expect 189/190
python3 tools/replay_ac3.py scenarios/p1-net-30d-2026-08
So part 9 replays the two days that exist, reports the percentage over them, and
states the sample size in days next to it. It is a MEASUREMENT, not a verdict:
@@ -60,8 +83,15 @@ export) for the reason `scenarios/p1-age-2026-08-26.jsonl.gz` already is: the
infra repo is private, CI's token is minted for this repository only, and a
regression fixture that CI cannot see is not a regression fixture.
Closing AC 3 needs 30 days of capture. That is TEST-01's replay harness, and it
cannot start before somebody starts recording.
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
@@ -85,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):
@@ -268,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()))
@@ -305,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 "
@@ -385,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))
@@ -413,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
@@ -433,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),
@@ -483,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)
@@ -511,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)
@@ -645,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()
@@ -716,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:
@@ -730,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
@@ -748,9 +843,11 @@ print()
print(f" AC 3 MEASURED: {under}/{total_q} quarters = {PCT:.1f} % under the "
f"{SHIPPED_CAP_W:.0f} W soft limit, over {replay_days:.1f} DAYS of "
f"replay, UNCONTROLLED (no peak shaving was running on either day).")
print(f" AC 3 ASKS FOR 30 DAYS. {replay_days:.1f} days exist. "
f"AC 3 IS NOT MET and this run does not claim it is - see the module "
f"docstring. The figure above is the BASELINE SAFETY-07 has to improve.")
print(f" AC 3 ASKS FOR 30 DAYS and this run is {replay_days:.1f}, so it "
f"does not settle it either way. The 30 days DO now exist - "
f"scenarios/p1-net-30d-2026-08/, DATA-01 - and "
f"tools/replay_ac3.py is what runs them; the figure above is the "
f"BASELINE SAFETY-07 has to improve, on the two days CI replays.")
check("the replay produced a measurable number over a stated sample size, "
"rather than a criterion quietly redefined to fit the data",
total_q > 100 and replay_days < 30)
@@ -783,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
@@ -799,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(),
@@ -838,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",
@@ -854,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)
@@ -866,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
@@ -881,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),
@@ -0,0 +1,455 @@
#!/usr/bin/env python3
"""Export a P1 power signal out of Home Assistant's recorder into the committed
scenario format - one gzipped JSON object per line, one file per LOCAL day.
WHY THIS FILE EXISTS AT ALL
===========================
`scenarios/p1-net-2026-08-20.jsonl.gz` and `p1-net-2026-08-23.jsonl.gz` were
produced once, by hand, and the script was thrown away. The consequence was not
theoretical: TARIFF-01's and SAFETY-07's AC 3 ("monthly peak held under the soft
limit in >= 95 % of intervals over a 30-day simulation replay") were both merged
UNMET on the belief that thirty days could not be produced retroactively - a
belief that was simply wrong, and that survived because nobody could re-run the
export to find out. So the export is a committed, runnable artefact now, and the
next person does not have to re-derive it under time pressure while a retention
window rolls.
python3 tools/export_p1_history.py --days 30 --out-dir /some/where
THE TWO RULES THIS FILE IS BUILT AROUND
=======================================
1. A FAILED READ IS NOT AN OBSERVATION. An HTTP error, a timeout, a truncated
body, a non-JSON body - none of those are "the meter reported nothing that
hour". They are "we do not know what the meter reported that hour", and the
two must never end up looking the same in the output. So:
* every request is retried with backoff;
* a day whose read ultimately fails writes NO FILE and is recorded in the
manifest as `"read": "FAILED"` with the error text, and the process exits
non-zero;
* a day that reads back successfully but EMPTY writes an empty file and is
recorded as `"read": "OK", "samples": 0`. Empty-and-known and
unknown are therefore distinguishable both in the manifest and by the
presence or absence of the file;
* before any day is fetched, the entity is proved to exist through
/api/states/<entity>. Without that check a typo in --entity would return
200 + `[]` for all thirty days and produce a beautifully consistent
dataset of nothing.
2. GAPS ARE VISIBLE, NEVER INTERPOLATED. Nothing here carries a value forward,
fills, resamples or averages. A recorder outage or an HA restart shows up as
what it is: consecutive `t` values further apart than the meter's cadence.
The controller's own ingest already reads that correctly - `meter_max_age_s`
(30 s shipped) is exactly the age past which a held reading stops counting as
coverage - so an hour with no telegrams replays as an hour of NO COVERAGE
rather than as an hour of whatever the last sample said. The manifest lists
every gap over --gap-s so a reader does not have to diff timestamps to find
them.
DAY AT A TIME, AND WHY NOT SMALLER
==================================
One request per local day. That is gentle on a live HA (~1 MB of JSON per day)
and it is also the only chunking that reproduces the committed files: the
history API prepends the state as it stood AT the period start
(`include_start_time_state`), stamped with the start instant. Splitting a day
into six-hour chunks would therefore inject three synthetic boundary samples per
day that no meter ever sent. Days are the natural boundary because the committed
files are local days.
VERIFYING THE EXPORTER
======================
python3 tools/export_p1_history.py --verify scenarios/p1-net-2026-08-20.jsonl.gz
re-fetches that day by this exact route and compares the DECOMPRESSED bytes with
the committed file. Byte equality of the .gz containers is not expected and not
required: a gzip header carries an mtime, and this file writes mtime 0 so its
own output is reproducible. Content equality is the claim that matters.
"""
from __future__ import annotations
import argparse
import gzip
import hashlib
import json
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime, timedelta, timezone
from pathlib import Path
try: # py3.9+; the add-on image has it
from zoneinfo import ZoneInfo
except ImportError: # pragma: no cover
ZoneInfo = None # type: ignore
DEFAULT_URL = "http://192.168.2.158:8123"
DEFAULT_ENTITY = "sensor.p1_meter_active_power"
DEFAULT_TZ = "Europe/Brussels"
# The shipped meter_max_age_s. A hole longer than this is a hole the controller
# itself would refuse to see through, which makes it the honest gap threshold.
DEFAULT_GAP_S = 30.0
class ReadFailed(RuntimeError):
"""The read did not happen. NOT the same thing as an empty result."""
# ---------------------------------------------------------------------------
# transport
def _get(url: str, token: str, timeout: float):
req = urllib.request.Request(url, headers={
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
})
with urllib.request.urlopen(req, timeout=timeout) as resp:
if resp.status != 200:
raise ReadFailed(f"HTTP {resp.status}")
return resp.read()
def fetch_json(url: str, token: str, *, timeout: float, retries: int,
backoff: float, log=print):
"""GET and parse, or raise ReadFailed. Never returns a partial answer."""
last = None
for attempt in range(1, retries + 1):
try:
raw = _get(url, token, timeout)
except urllib.error.HTTPError as exc:
last = f"HTTP {exc.code} {exc.reason}"
except Exception as exc: # URLError, timeout, ...
last = f"{type(exc).__name__}: {exc}"
else:
try:
return json.loads(raw.decode("utf-8")), len(raw), attempt
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
# A truncated body looks exactly like this. It is a failure.
last = f"unparseable body ({len(raw)} bytes): {exc}"
if attempt < retries:
wait = backoff * attempt
log(f" read failed ({last}); retry {attempt + 1}/{retries} "
f"in {wait:.0f} s")
time.sleep(wait)
raise ReadFailed(last or "unknown")
def assert_entity_exists(base: str, entity: str, token: str, *, timeout: float,
retries: int, backoff: float, log=print):
"""Prove the entity is real BEFORE trusting any empty day.
Without this, `--entity sensor.typo` answers 200 + [] for every day and the
exporter cheerfully writes thirty empty files.
"""
url = f"{base}/api/states/{urllib.parse.quote(entity)}"
doc, _, _ = fetch_json(url, token, timeout=timeout, retries=retries,
backoff=backoff, log=log)
if not isinstance(doc, dict) or doc.get("entity_id") != entity:
raise ReadFailed(f"{entity} is not a known entity")
return doc
# ---------------------------------------------------------------------------
# one day
def day_bounds(day: datetime, tz):
start = datetime(day.year, day.month, day.day, tzinfo=tz)
return start, start + timedelta(days=1)
def history_url(base: str, entity: str, start: datetime, end: datetime) -> str:
q = urllib.parse.urlencode({
"filter_entity_id": entity,
"end_time": end.isoformat(),
"minimal_response": "",
})
return (f"{base}/api/history/period/"
f"{urllib.parse.quote(start.isoformat())}?{q}")
def rows_from(doc, entity: str):
"""HA's shape -> [(iso_t, state_str)], plus the states that are not numbers.
`minimal_response` returns the first record in full and the rest as
{state, last_changed}. An entity that went unavailable reports the string
"unavailable" (or "unknown") where a number belongs. Those are dropped from
the numeric series - there is no float to write and the committed schema has
no slot for a non-number - but every one is returned here so it lands in the
manifest. Dropping them is what MAKES the outage visible: the series simply
has no samples across it, which is the same thing the meter falling silent
looks like, and is what the controller's freshness rule already handles.
"""
if not isinstance(doc, list):
raise ReadFailed(f"expected a list, got {type(doc).__name__}")
if not doc:
return [], []
series = doc[0]
if not isinstance(series, list):
raise ReadFailed("history series is not a list")
good, bad = [], []
for rec in series:
eid = rec.get("entity_id")
if eid is not None and eid != entity:
raise ReadFailed(f"unexpected entity {eid!r} in the response")
t = rec.get("last_changed") or rec.get("last_updated")
s = rec.get("state")
if t is None:
raise ReadFailed("a record carries no timestamp")
try:
w = float(s)
except (TypeError, ValueError):
bad.append({"t": t, "state": s})
continue
good.append((t, w))
return good, bad
def render(rows, *, newline: str) -> bytes:
"""The committed format, exactly: `{"t": <iso>, "w": <float>}` per line.
json.dumps' default separators (", " / ": ") and repr of a float are what
the two committed files contain; so is the CRLF, an artefact of the original
one-off having been run on Windows in text mode. It is reproduced rather
than tidied because reproducing the committed bytes is this exporter's
verification, and gzip.open(..., 'rt') strips it either way.
"""
out = bytearray()
for t, w in rows:
out += json.dumps({"t": t, "w": w}).encode("utf-8")
out += newline.encode("ascii")
return bytes(out)
def gz(payload: bytes) -> bytes:
"""gzip level 9, mtime 0 - so the same input always gives the same bytes."""
import io
buf = io.BytesIO()
with gzip.GzipFile(fileobj=buf, mode="wb", compresslevel=9, mtime=0) as f:
f.write(payload)
return buf.getvalue()
def gaps_in(rows, gap_s: float):
out = []
prev = None
for t, _ in rows:
cur = datetime.fromisoformat(t)
if prev is not None:
d = (cur - prev).total_seconds()
if d > gap_s:
out.append({"from": prev.isoformat(), "to": cur.isoformat(),
"seconds": round(d, 3)})
prev = cur
return out
def export_day(base, entity, token, day, tz, *, timeout, retries, backoff,
gap_s, newline, log=print):
"""Read one local day. Raises ReadFailed rather than returning a guess."""
start, end = day_bounds(day, tz)
doc, nbytes, attempts = fetch_json(
history_url(base, entity, start, end), token,
timeout=timeout, retries=retries, backoff=backoff, log=log)
rows, bad = rows_from(doc, entity)
entry = {
"date": day.date().isoformat(),
"window": [start.isoformat(), end.isoformat()],
"read": "OK",
"http_bytes": nbytes,
"attempts": attempts,
"samples": len(rows),
"non_numeric_states": bad,
"first": rows[0][0] if rows else None,
"last": rows[-1][0] if rows else None,
"gaps": gaps_in(rows, gap_s),
}
if rows:
span = (datetime.fromisoformat(rows[-1][0])
- datetime.fromisoformat(rows[0][0])).total_seconds()
entry["covered_span_s"] = round(span, 1)
entry["mean_cadence_s"] = round(span / max(1, len(rows) - 1), 3)
return rows, entry
# ---------------------------------------------------------------------------
# modes
def do_export(args, token, tz, log=print):
base = args.url.rstrip("/")
out_dir = Path(args.out_dir)
out_dir.mkdir(parents=True, exist_ok=True)
newline = "\r\n" if args.newline == "crlf" else "\n"
log(f" proving {args.entity} exists before trusting any empty day")
st = assert_entity_exists(base, args.entity, token, timeout=args.timeout,
retries=args.retries, backoff=args.backoff,
log=log)
log(f" {args.entity} = {st.get('state')} "
f"{st.get('attributes', {}).get('unit_of_measurement', '')}")
if args.end_date:
last = datetime.fromisoformat(args.end_date).replace(tzinfo=tz)
else: # yesterday: today is still being logged
last = datetime.now(tz).replace(hour=0, minute=0, second=0,
microsecond=0) - timedelta(days=1)
days = [last - timedelta(days=i) for i in range(args.days - 1, -1, -1)]
manifest = {
"generated": datetime.now(timezone.utc).isoformat(),
"generator": "tools/export_p1_history.py",
"source": f"{base}/api/history/period",
"entity": args.entity,
"timezone": args.tz,
"gap_threshold_s": args.gap_s,
"format": '{"t": <ISO-8601 UTC>, "w": <float watts>} per line, gzip',
"days": [],
}
failures = []
for day in days:
name = f"{args.prefix}{day.date().isoformat()}.jsonl.gz"
log(f" {name}")
try:
rows, entry = export_day(
base, args.entity, token, day, tz, timeout=args.timeout,
retries=args.retries, backoff=args.backoff, gap_s=args.gap_s,
newline=newline, log=log)
except ReadFailed as exc:
# NO FILE. A missing file is the honest record of a read that did
# not happen; an empty one would claim the meter was silent.
entry = {"date": day.date().isoformat(), "read": "FAILED",
"error": str(exc), "file": None}
manifest["days"].append(entry)
failures.append(entry)
log(f" READ FAILED: {exc} - no file written")
continue
payload = render(rows, newline=newline)
blob = gz(payload)
(out_dir / name).write_bytes(blob)
entry["file"] = name
entry["bytes_gz"] = len(blob)
entry["bytes_raw"] = len(payload)
entry["sha256_raw"] = hashlib.sha256(payload).hexdigest()
entry["sha256_gz"] = hashlib.sha256(blob).hexdigest()
manifest["days"].append(entry)
ng = len(entry.get("gaps", []))
log(f" {entry['samples']} samples, {len(blob)} B gz, "
f"{ng} gap(s) over {args.gap_s:g} s"
+ (f", {len(entry['non_numeric_states'])} non-numeric state(s)"
if entry["non_numeric_states"] else ""))
if day is not days[-1]:
time.sleep(args.delay)
ok = [d for d in manifest["days"] if d["read"] == "OK"]
manifest["summary"] = {
"days_requested": len(days),
"days_read": len(ok),
"days_failed": len(failures),
"samples": sum(d["samples"] for d in ok),
"bytes_gz": sum(d["bytes_gz"] for d in ok),
"empty_days": [d["date"] for d in ok if d["samples"] == 0],
}
# newline="\n" explicitly: write_text() on Windows emits CRLF, and
# the manifest would then differ from a Linux run of the same export
# for no reason visible in a diff.
with open(args.manifest or (out_dir / "manifest.json"), "w",
encoding="utf-8", newline="\n") as fh:
fh.write(json.dumps(manifest, indent=2) + "\n")
log(f" {manifest['summary']['days_read']}/{len(days)} days, "
f"{manifest['summary']['samples']} samples, "
f"{manifest['summary']['bytes_gz'] / 1e6:.2f} MB gz")
if failures:
log(f" {len(failures)} DAY(S) NOT READ - the dataset is incomplete "
f"and says so: " + ", ".join(d["date"] for d in failures))
return 1
return 0
def do_verify(args, token, tz, log=print):
"""Re-export a committed day by this route and diff it against the file."""
base = args.url.rstrip("/")
newline = "\r\n" if args.newline == "crlf" else "\n"
rc = 0
for target in args.verify:
path = Path(target)
stamp = path.name.split(".")[0].rsplit("-", 3)[-3:]
day = datetime(int(stamp[0]), int(stamp[1]), int(stamp[2]), tzinfo=tz)
log(f" {path.name} (local day {day.date().isoformat()})")
committed = gzip.decompress(path.read_bytes())
rows, entry = export_day(base, args.entity, token, day, tz,
timeout=args.timeout, retries=args.retries,
backoff=args.backoff, gap_s=args.gap_s,
newline=newline, log=log)
fresh = render(rows, newline=newline)
if fresh == committed:
log(f" IDENTICAL: {len(fresh)} bytes, {entry['samples']} "
f"samples, sha256 {hashlib.sha256(fresh).hexdigest()[:16]}")
continue
rc = 1
cl = committed.split(newline.encode())
fl = fresh.split(newline.encode())
log(f" DIFFERS: committed {len(committed)} B / {len(cl)} lines, "
f"re-export {len(fresh)} B / {len(fl)} lines")
shown = 0
for i in range(max(len(cl), len(fl))):
a = cl[i] if i < len(cl) else b"<absent>"
b = fl[i] if i < len(fl) else b"<absent>"
if a != b:
log(f" line {i}: committed {a!r}")
log(f" re-export {b!r}")
shown += 1
if shown >= args.max_diff:
log(f" ... stopping after {shown} differing lines")
break
return rc
def main(argv=None):
p = argparse.ArgumentParser(description=__doc__.split("\n")[0])
p.add_argument("--url", default=DEFAULT_URL)
p.add_argument("--entity", default=DEFAULT_ENTITY)
p.add_argument("--token", help="bearer token; else $HASS_TOKEN")
p.add_argument("--tz", default=DEFAULT_TZ,
help="local timezone that defines a day boundary")
p.add_argument("--days", type=int, default=30)
p.add_argument("--end-date", help="last local day to export (YYYY-MM-DD); "
"default yesterday")
p.add_argument("--out-dir", default=".")
p.add_argument("--prefix", default="p1-net-")
p.add_argument("--manifest", help="path for the manifest JSON")
p.add_argument("--gap-s", type=float, default=DEFAULT_GAP_S)
p.add_argument("--newline", choices=("crlf", "lf"), default="crlf",
help="line terminator; crlf reproduces the committed files")
p.add_argument("--timeout", type=float, default=120.0)
p.add_argument("--retries", type=int, default=4)
p.add_argument("--backoff", type=float, default=5.0)
p.add_argument("--delay", type=float, default=2.0,
help="pause between days - this is a live HA")
p.add_argument("--verify", nargs="+", metavar="FILE",
help="re-export these committed days and diff them")
p.add_argument("--max-diff", type=int, default=20)
args = p.parse_args(argv)
token = args.token or __import__("os").environ.get("HASS_TOKEN")
if not token:
print("no token: pass --token or set HASS_TOKEN", file=sys.stderr)
return 2
if ZoneInfo is None:
print("zoneinfo unavailable", file=sys.stderr)
return 2
tz = ZoneInfo(args.tz)
try:
if args.verify:
return do_verify(args, token, tz)
return do_export(args, token, tz)
except ReadFailed as exc:
print(f"read failed: {exc}", file=sys.stderr)
return 1
if __name__ == "__main__":
raise SystemExit(main())
+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
+303
View File
@@ -0,0 +1,303 @@
#!/usr/bin/env python3
"""Run TARIFF-01's and SAFETY-07's AC 3 over a directory of `p1-net-*.jsonl.gz`.
AC 3, both cards, same words: *"monthly peak held under the soft limit in
>= 95 % of intervals over a 30-day simulation replay."* Both cards merged with
it UNMET because two days of capture existed. DATA-01 exported thirty. This is
the thing that turns those thirty days into the number.
cd goodwe_controller
python3 tools/replay_ac3.py scenarios/p1-net-30d-2026-08
WHAT IT MEASURES
================
Two runs over the same telegrams, one file at a time in date order into a
SHARED peak store, so the 15-minute blocks accumulate into a real MONTH rather
than into 30 disconnected days:
UNCONTROLLED the recorded meter as it happened. Nothing was shaving peaks on
this house during August 2026, so this is not a simulation of
anything - it is what the month did. It is TARIFF-01's AC 3.
GUARDED the same month with `peakguard.decide()` in the loop and the
battery it asks for modelled, closed-loop: the meter the guard
sees is the recorded net MINUS the discharge it obtained. That
is SAFETY-07's AC 3.
Both numbers are `quarters <= peak_cap_w` over `quarters closed`, with the cap
read out of config.yaml rather than typed. Nothing here exits non-zero on 95 %:
a measurement below the criterion is a finding about the house and the guard,
and this tool's job is to report it, not to be graded by it.
FAITHFULNESS TO THE SUITE
=========================
The replay loop is `test_peakguard.py` part 6's, with `pack=None` (SoC pinned
above the floor, so SAFETY-24's energy floor is not the thing deciding the
answer). It is not imported from there because that file runs its whole suite on
import. The duplication is checked instead of asserted: pointed at `scenarios/`
- the two committed days - this tool must reproduce part 6's published totals,
and `--expect` makes that a hard check.
python3 tools/replay_ac3.py scenarios --expect 189/190
GAPS
====
Nothing is interpolated. A hole in the export is a hole here: the shipped
`meter_max_age_s` is what decides whether a held reading still counts as
coverage, so an hour with no telegrams closes no quarters and contributes to
neither numerator nor denominator. `--report-gaps` lists them.
"""
from __future__ import annotations
import argparse
import gzip
import json
import sys
import tempfile
from datetime import datetime, timedelta
from pathlib import Path
HERE = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(HERE))
from app.p1 import P1Ingest, make_sample, split_signed # noqa: E402
from app.peakguard import decide # noqa: E402
from app.tariff import PeakStore, PeakTracker, month_key # noqa: E402
def read_option(key: str):
"""The shipped default for `key`, out of config.yaml.
⚠️ `peak_cap_w:` appears TWICE in config.yaml - once under `options:` with
the default, once under `schema:` as `int(500,15000)`. The FIRST match is
the options block, which is the number an install actually lands on; taking
the last would try to float() the schema line. Same rule as the suites.
"""
for line in (HERE / "config.yaml").read_text(encoding="utf-8").splitlines():
if line.strip().startswith(f"{key}:"):
try:
return float(line.split(":", 1)[1].strip())
except ValueError:
continue
return None
def read_schema_max(key: str):
for line in (HERE / "config.yaml").read_text(encoding="utf-8").splitlines():
s = line.strip()
if s.startswith(f"{key}:") and "(" in s and ")" in s:
try:
return float(s[s.index("(") + 1:s.index(")")].split(",")[-1])
except ValueError:
continue
return None
def sample(t: datetime, net_w: float):
"""One telegram through the SHIPPED sign derivation - the suites' helper."""
imp, exp = split_signed(net_w)
return make_sample("ha_signed", imp, exp, phases=1,
ingest_ts=t, ingest_mono=t.timestamp())
def rows(path):
"""Every sample in one file, in order, with the gaps left as gaps."""
with gzip.open(path, "rt", encoding="utf-8") as fh:
for line in fh:
line = line.strip()
if not line:
continue
row = json.loads(line)
yield datetime.fromisoformat(row["t"]), float(row["w"])
def replay(paths, *, guarded: bool, cap_w, max_w, max_hold_s, cycle_s,
soc, soc_floor, tmp: Path, gap_s: float):
"""test_peakguard.py part 6's loop, over an arbitrary number of days.
⚠️ ONE STORE, AND AN INGEST THAT IS RESET ONLY AT A REAL DISCONTINUITY.
Neither half of that is a detail.
The STORE is shared across the files because "monthly peak" is what AC 3 is
about and a per-file store cannot express it.
The INGEST is carried across a file boundary when the next file's first
telegram follows the previous file's last one within `gap_s`, and rebuilt
when it does not. Both failure modes are real and were measured here:
* carried across a genuine hole, one averager manufactures quarters out of
nothing - streamed straight through the three-day gap between the two
committed days this reported 285/286 where the suite reports 189/190;
* rebuilt at every file, each day's LAST quarter (21:45-22:00 UTC) never
closes, because it closes only when a telegram past the boundary
arrives and that telegram is in the next file. That is why the suite's
two days give 95 quarters each rather than 96, and it silently discards
one quarter per day - 30 of them over a month.
So contiguous days are joined and non-contiguous ones are not, which gives
189/190 on the committed pair and a full 96 quarters a day on a run of
consecutive days.
"""
store = PeakStore(str(tmp / f"ac3-{'g' if guarded else 'u'}.db"))
tracker = PeakTracker(store, cap_w=cap_w)
engaged = blind = saturated = cycles = n = joins = 0
wh = 0.0
gaps = []
months = set()
ing = None
batt = 0.0 # delivered discharge, W (positive)
next_cycle = None
prev_t = None
for path in paths:
for i, (t, w) in enumerate(rows(path)):
if i == 0:
contiguous = (prev_t is not None
and 0 <= (t - prev_t).total_seconds() <= gap_s)
if contiguous:
joins += 1
else:
if ing is not None:
months |= {month_key(b.start) for b in ing.blocks}
ing = P1Ingest(phases=1, max_age_s=max_hold_s)
batt = 0.0
next_cycle = None
prev_t = None
if prev_t is not None:
dt = (t - prev_t).total_seconds()
if dt > gap_s:
gaps.append((prev_t, t, dt))
wh += batt * dt / 3600.0
prev_t = t
n += 1
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=max_w, max_hold_s=max_hold_s, soc=soc,
soc_floor=soc_floor, frozen=False)
if d.engaged:
blind += 1 if d.blind else 0
engaged += 0 if d.blind else 1
saturated += 1 if d.saturated else 0
if not guarded:
continue
engaged_floor = d.engaged and d.floor_w is not None
batt = max(0.0, d.floor_w) if engaged_floor else 0.0
if ing is not None:
months |= {month_key(b.start) for b in ing.blocks}
out = {m: dict(store.blocks_in(m)) for m in sorted(months)}
return {"months": out, "samples": n, "cycles": cycles, "joins": joins,
"engaged": engaged, "blind": blind, "saturated": saturated,
"wh": wh, "gaps": gaps}
def main(argv=None):
p = argparse.ArgumentParser(description=__doc__.split("\n")[0])
p.add_argument("directory", help="a directory of p1-net-*.jsonl.gz")
p.add_argument("--glob", default="p1-net-*.jsonl.gz")
p.add_argument("--expect", help="UNDER/TOTAL the uncontrolled run must "
"reproduce, e.g. 189/190")
p.add_argument("--report-gaps", action="store_true")
args = p.parse_args(argv)
paths = sorted(Path(args.directory).glob(args.glob))
if not paths:
print(f"no {args.glob} under {args.directory}", file=sys.stderr)
return 2
CAP_W = read_option("peak_cap_w")
MAX_HOLD_S = read_option("meter_max_age_s")
CYCLE_S = read_option("cycle_floor_s")
SOC_FLOOR = read_option("peak_soc_floor")
LIVE_MAX_W = read_schema_max("max_w")
if None in (CAP_W, MAX_HOLD_S, CYCLE_S, SOC_FLOOR, LIVE_MAX_W):
print("could not read the shipped options out of config.yaml",
file=sys.stderr)
return 2
# The suites' fixture SoC: comfortably above the floor, so SAFETY-24's
# energy floor is not what decides an AC 3 that is not about it.
SOC_OK = SOC_FLOOR + 30.0
days = len(paths)
span_first = span_last = None
print(f"AC 3 - {days} file(s) from {args.directory}")
print(f" shipped: peak_cap_w {CAP_W:.0f} W, meter_max_age_s "
f"{MAX_HOLD_S:.0f} s, cycle_floor_s {CYCLE_S:.0f} s, "
f"max_w schema ceiling {LIVE_MAX_W:.0f} W")
tmp = Path(tempfile.mkdtemp(prefix="goodwe-ac3-"))
kw = dict(cap_w=CAP_W, max_w=LIVE_MAX_W, max_hold_s=MAX_HOLD_S,
cycle_s=CYCLE_S, soc=SOC_OK, soc_floor=SOC_FLOOR, tmp=tmp,
gap_s=MAX_HOLD_S)
u = replay(paths, guarded=False, **kw)
g = replay(paths, guarded=True, **kw)
def flat(run):
return [w for m in run["months"].values() for w in m.values()]
uq, gq = flat(u), flat(g)
u_under = sum(1 for w in uq if w <= CAP_W)
g_under = sum(1 for w in gq if w <= CAP_W)
u_pct = 100.0 * u_under / max(len(uq), 1)
g_pct = 100.0 * g_under / max(len(gq), 1)
print(f" {u['samples']} samples, {len(uq)} closed quarters "
f"({len(uq) / 96.0:.1f} days' worth), {days - u['joins']} contiguous "
f"run(s) of days")
for m in sorted(u["months"]):
mu = u["months"][m]
mg = g["months"].get(m, {})
print(f" month {m}: {len(mu)} quarters, peak "
f"{max(mu.values()):.1f} W uncontrolled -> "
f"{max(mg.values()) if mg else 0.0:.1f} W guarded")
print()
print(f" TARIFF-01 AC 3 (UNCONTROLLED, what the month did): "
f"{u_under}/{len(uq)} = {u_pct:.2f} % of quarters at or under "
f"{CAP_W:.0f} W")
print(f" SAFETY-07 AC 3 (GUARDED, peakguard.decide in the loop): "
f"{g_under}/{len(gq)} = {g_pct:.2f} %")
print(f" guard cycles {g['cycles']}, engaged on the measurement "
f"{g['engaged']}, blind {g['blind']}, saturated {g['saturated']}, "
f"modelled discharge {g['wh']:.0f} Wh")
# AC 3'S WORDS SUPPORT TWO READINGS AND BOTH ARE REPORTED, because they
# disagree on this data and picking the flattering one is the failure mode
# this whole card exists to correct.
u_peak = max(uq) if uq else 0.0
g_peak = max(gq) if gq else 0.0
print(f" reading A - PERCENTAGE OF INTERVALS under the cap (the reading "
f"test_tariff.py part 9 already uses): uncontrolled {u_pct:.2f} %, "
f"guarded {g_pct:.2f} %")
print(f" reading B - THE MONTHLY PEAK ITSELF under the cap: "
f"{u_peak:.1f} W uncontrolled -> {g_peak:.1f} W guarded, against a "
f"{CAP_W:.0f} W soft limit "
f"({'under' if g_peak <= CAP_W else 'STILL OVER'})")
print(f" verdict at the 95 % criterion: uncontrolled "
f"{'MEETS' if u_pct >= 95.0 else 'DOES NOT MEET'}, guarded "
f"{'MEETS' if g_pct >= 95.0 else 'DOES NOT MEET'} "
f"({len(uq) / 96.0:.1f} days of replay)")
if u["gaps"]:
tot = sum(d for _, _, d in u["gaps"])
print(f" gaps over {MAX_HOLD_S:.0f} s: {len(u['gaps'])}, "
f"{tot:.0f} s total - NOT interpolated; the quarters they fall in "
f"simply carry less coverage")
if args.report_gaps:
for a, b, d in u["gaps"]:
print(f" {a.isoformat()} -> {b.isoformat()} {d:.0f} s")
if args.expect:
want_u, want_t = (int(x) for x in args.expect.split("/"))
ok = (u_under, len(uq)) == (want_u, want_t)
print(f" reproduces test_peakguard.py part 6's published "
f"{want_u}/{want_t}: {'yes' if ok else 'NO'} "
f"(got {u_under}/{len(uq)})")
return 0 if ok else 1
return 0
if __name__ == "__main__":
raise SystemExit(main())