Compare commits

...
25 Commits
Author SHA1 Message Date
adminandClaude Opus 5 905b6fd2b3 MAINT-05 fix round 2: the refusal has to survive the NEXT start, and both marker guards have to be visible
checks / unit (pull_request) Successful in 5m14s
REJECTED because the fix round's own load-bearing sentence was FALSE, and the
whole suite was blind to that. `_verify_moves()` produced the red the reviewer
reproduced - that half stood - but DECISIONS §2 claimed "`ok` gates the marker,
so a misdirected migration is not stamped and the next start runs it again ...
a re-run is recoverable". THE REFUSAL LASTED EXACTLY ONE START.

MEASURED, Controller level, ONE persisted store, roster ["garage","shed"], flat
last_completed 2026-08-07, call site still handing `inverter-a` on both starts:

    construction 1: ok=False misdirected=4 moved=4 kept=0   marker=<absent>
    construction 2: ok=True  misdirected=0 moved=0 kept=4   marker=1
    history parked under unit/inverter-a/...; marker stamped after ONE restart.

WHY. `_verify_moves()` graded only `rep.moved`. On start 2 the same wrong call
site finds the four keys already present, so rule 1 routes every one of them to
`rep.kept`, `rep.moved` is EMPTY, the roster loop iterates over nothing,
`misdirected` is empty and `ok` is True. Start 3 then takes the
`from_version >= MAINT_SCHEMA_VERSION` early return FOREVER - including after
the call site is fixed. Loud-and-recoverable became silent-and-permanent after
one restart: the exact state store.py's header says must never happen, reached
by the fix written to prevent it.

WHY THE CHECK MISSED IT - the recurring defect, this time INSIDE the remedy.
Part 9b's recovery check was `migrate_maint_keys(_m5, ROSTER[0], ROSTER)` - the
CORRECTED name. It measures recovery along the one path where the operator has
ALREADY fixed the bug. Nothing in the 19 files called `migrate_maint_keys()`
twice with the SAME WRONG `unit`. The check was true and passed for the wrong
reason.

WHAT CHANGED

1. app/store.py `_verify_moves()` grades `set(rep.moved) | set(rep.kept)`.
   Sound by construction: every entry in both lists is a `unit_key(unit,
   legacy)` built from the SAME `unit` argument, so grading `kept` grades the
   same namespace decision `moved` does. A correct call site's `kept` entries
   sit under a roster name and pass; a wrong one cannot launder its namespace by
   having already written it. `migrate_unit_keys()` passes `roster=None` and
   returns before the loop, so it is untouched.

2. test_maintenance.py part 9c - THE CHECK THAT WAS MISSING. Two starts, SAME
   wrong unit, ONE store: the marker is still withheld on the second, the
   refusal names the same roster, the flat history is still there to recover
   from, and a third start with the CORRECTED name still gets a run (which a
   stamped marker would have made impossible). Its PRECONDITION asserts the
   SHAPE of the second report - `moved` empty, `kept` full - so it cannot
   quietly revert to grading 9b's path. Counterfactual beside it: the same two
   calls with the right name are accepted, then skipped as `already at schema`.

3. test_maintenance.py part 9d - THE OTHER GUARD ON THE SAME LINE, and a
   survivor nothing in the repository could see. `if rep.ok:` is
   `not lost and not misdirected`; every check that reached the marker did so on
   a store whose `kept` was empty, so

       if rep.ok:        ->      if rep.ok or rep.kept:        (+12 B)

   stamped the marker on a migration that LOST A MONTH OF HISTORY - defeating
   the older, settled `lost` guard as well as the new one - and ALL 19 SUITES
   WERE GREEN on it (measured at 65cddf3, purged, :ro). 9d's fixture is the one
   shape that separates the guards: two keys already namespaced (`kept`
   non-empty, the mutant's `or` fires) and two whose write the store drops
   (`lost` non-empty), `misdirected` empty throughout.

4. FOUND HERE AND CLOSED: THE SAME MUTATION ONE FUNCTION UP. `migrate_unit_keys()`
   - SAFETY-02's LATCH migration - gates its own marker the same way, and every
   check that reached it ran on a store with an empty `kept`. `if rep.ok or
   rep.kept:` at store.py:307 SURVIVED ALL 19 FILES. It stamps `schema_version`
   on a migration that DROPPED THE LATCH: the guard is off, the file still reads
   `sign_tripped: true`, and the store now says the migration finished, so the
   next start skips the one thing that would re-arm it. test_inverter.py part 10
   now drops the `sign_tripped` write BESIDE an already-namespaced
   `sign_reason`, with the accepted-baseline counterfactual. No source change -
   the shipped gate was right; nothing could see it. Mutation table 34 -> 35.

5. DECISIONS/MAINT-05 §2 CORRECTED. The paragraph that stated the false
   guarantee now states what was measured, why grading `moved` alone could not
   hold, and why the union is sound. §7 records the marker-gate hole found in
   `migrate_unit_keys()` and that it was closed. MUTATION.md gains habit 9 -
   "exercise a refusal a SECOND time with the SAME wrong input, not the
   corrected one" - and two survey rows.

MUTATION LEDGER - 11 mutations, ALL RED on the final tree, every run on a fresh
copy with the bytecode cache purged (entry count printed before and after) and
the tree mounted :ro so none could be written. Two were survivors BEFORE this
commit and both are recorded as such. Full transcript on the PR.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BwRLw7eKYj2byVdwB6kbjU
2026-09-04 19:40:51 +02:00
glenn schrooyenandClaude Opus 5 65cddf35f1 MAINT-05 fix round: grade the migration against the ROSTER, not against the name it was handed
checks / unit (pull_request) Successful in 4m47s
REJECTED because a survivor undoes AC 5, and it survived for the recurring
reason: two fixture values that must be distinguishable were EQUAL.

THE SURVIVOR. app/main.py:282 mutated from `self.inverters[0].name` to `UNIT_A`
left the full 19-file suite green. `inverter.UNIT_A == "inverter-a"`, and every
two-pack fixture in test_maintenance.py named its first roster entry
"inverter-a" - so the two expressions were the same string in every check that
existed. main.py's own comment made the distinction load-bearing and nothing in
the repository could see whether that comment was true.

THE FAILURE IS REAL. `build_roster()` names a declared roster's entries from the
config and numbers a nameless one POSITIONALLY (`inverter-1`), so "inverter-a"
is not even the fallback. On ["garage","shed"] with a flat last_completed of
2026-08-07 the mutant migrates into unit/inverter-a/, pack 0 reads back None,
and both packs come up believing they have never been recalibrated.

AND IT FAILED SILENTLY, which was the worse half: `_verify_moves()` read back
the keys it had just WRITTEN, under the namespace it had just been HANDED, was
satisfied, and MAINT_SCHEMA_KEY was stamped - so the next start skipped the
migration too. A postcondition that reads back the namespace it was handed
cannot detect being handed the wrong one.

WHAT CHANGED

1. THE POSTCONDITION IS GRADED AGAINST THE ROSTER. `_verify_moves()` takes the
   names the MACHINES read and reports a namespace that is not among them as
   `misdirected` - a new, differently-named failure from `lost`:
     * `lost` is "the store took the write and dropped it" - a storage fault,
       with a harmless-default case (a dropped `last_completed: None` loses
       nothing, because absent and never-recalibrated are the same statement);
     * `misdirected` is "the store did exactly as it was told, by a caller that
       was wrong". There is no harmless-default version of it - a write nobody
       reads is not information whatever its value - so it fails `ok` alone.
   `ok` gates the marker, so a misdirected migration is NOT stamped and the next
   start re-runs it. Asymmetric on purpose: a re-run is recoverable (rule 1
   makes it a no-op, rule 2 left the flat keys to recover from), a silent skip
   is not. Part 9b MEASURES the recovery rather than asserting it.

2. `migrate_maint_keys()` TAKES THE ROSTER IN PLACE OF AN `n_units` COUNT. The
   count was `len(self.inverters)` at the only call site, so the roster carries
   it, and a count beside the names is a second opinion about how many packs
   there are.

3. THE FIXTURES CAN NOW REACH THE FAILURE THEY NAME. Parts 9 and 11 run on
   ["garage","shed"], each behind a PRECONDITION check that the first name is
   not UNIT_A - so an edit that makes them equal again goes red instead of
   making the claims vacuous. Part 11's fixture date is relative to `now`, not
   a literal, so "history preserved" and "history lost" cannot converge as the
   file ages past `interval_days`.

MUTATION LEDGER - all red, purged tree, none at +0 B, full detail on the PR:
   M1  main.py  inverters[0].name -> UNIT_A            -16 B  4 checks red
   M2  store.py drop `roster=names` from _verify_moves -14 B  5 checks red
   M3  store.py drop the misdirected.append            -37 B  5 checks red
   M4  store.py ok: drop `and not self.misdirected`    -25 B  3 checks red
   M5  fixture  garage -> inverter-a (the trap itself)  +4 B  5 checks red
   M6  store.py parts[1] -> parts[-1]                   +1 B  1 check red

FOUND AND NOT FIXED - `migrate_unit_keys()` HAS THE SAME HOLE AND IT IS A LATCH.
It runs BEFORE `build_roster()` (each Inverter restores its latch in its
constructor), so it is handed the constant UNIT_A with no roster to grade
against. On a declared roster a pre-DEV-02 `sign_tripped: true` lands under
unit/inverter-a/sign_tripped, which no unit reads - and
`_grade_store_migration()`, whose whole job is to re-arm exactly this, is
DEFEATED BY THE KEY THE DEFECT WROTE: its "is anything namespaced latched" test
is satisfied by the misdirected value itself. Measured, with the flat-config
counterfactual, and pinned as a running check (test_maintenance.py part 13)
whose assertions state the WRONG behaviour on purpose. It wants its own card:
the remedy is in inverter.py and SAFETY-02's semantics, and a silent expansion
into a safety latch is how a rejected PR becomes a broken one.

Suite: 19/19 PASS, purged tree, bind-mounted :ro in goodwe-addon-ci.
No hardware was touched; every fixture here is SIMULATED and pack B's 3000 W
remains a marked hypothesis.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BwRLw7eKYj2byVdwB6kbjU
2026-09-04 16:18:34 +02:00
adminandClaude Opus 5 1aef19e995 MAINT-05: one recalibration per pack, and only one pack moves power at a time
checks / unit (pull_request) Successful in 4m48s
§12's monthly cycle drains a pack to empty and refills it to true its coulomb
counter. There was exactly one `Maintenance` and one un-namespaced history, so
at two packs only the first was ever recalibrated - and nothing prevented the
cycle draining pack A while the loop charged pack B, which is two power-moving
phases on one grid connection pulling against each other.

* ONE `Maintenance` PER ROSTER ENTRY, each with its own schedule, phase and
  history under `unit/<name>/...`. `store.migrate_maint_keys()` moves an
  install's flat history into the first pack's namespace under
  `migrate_unit_keys()`'s three rules - shared in code via `_move_flat_keys()`
  and `_verify_moves()`, not restated - on its own marker, because unlike
  DEV-02's it runs only where the roster has more than one pack. The flat keys
  are kept LIVE as the rollback view.
* ONE MAINTENANCE SLOT PER SITE (`maintenance.arbitrate()`). At most one pack
  in a power-moving phase - drain, charge AND hold. The holder is DERIVED from
  the packs' own stored phases, never persisted, so a restart mid-drain
  re-derives it. Several packs due in the same hour: the slot goes to the one
  that has gone longest without a completed cycle; roster order breaks a
  numeric tie and nothing else. Nothing preempts a cycle in flight.
* THE DEFERRED PACK IS NOT STARVED AND IS NOT A FAULT. A deferral does not
  stamp `last_start_attempt` and does not move the phase, so neither the 12 h
  drain nor the 36 h charge timeout is reachable by waiting.
* The claim is filed on the pack whose state machine produced it, and stays
  SCOPE_UNIT - ARCH-01's rule.
* `validate.py` rule 6 grades `maintenance_charge_w` against the WEAKEST cap on
  the roster now, as its own comment said it must once `maint_unit` stopped
  being `inverters[0]`.
* At a roster of one nothing changes, and it is asserted: no new store key, the
  migration does not run, the four cycle events are the shipped strings, the
  banner is the bare phase.
* RECORDED NOT FIXED: a drain pins its pack while the loop's target is a site
  claim, so below the pin the allocator refuses the split and the site parks at
  0 W. Pre-existing at 2d025ee. Pinned as a running check.

Verified: 19/19 suites green in the CI image; 17 mutations run through
tools/mutation_run.sh (bytecode purged), every one observed red.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BwRLw7eKYj2byVdwB6kbjU
2026-09-04 13:38:29 +02:00
admin 2d025eebf7 Merge pull request 'SAFETY-30: grade each inverter against its own power, and the site's total against the meter' (#46) from SAFETY-30 into release/1.0 2026-09-04 12:28:44 +02:00
glenn schrooyenandClaude Opus 5 ae21b71824 Merge release/1.0 into SAFETY-30
checks / unit (pull_request) Successful in 4m39s
CFG-04 (#45) merged first and moved the base. Two conflicts, both resolved
as the union of the two sides:

- app/main.py: an import-block collision. CFG-04 added validate_unit_ranges
  to the .validate import; SAFETY-30 added AGAINST_METER, AGAINST_OWN_POWER,
  SIGN_OPTION_DEFAULTS and SignWatchdog to the .watchdog import. Neither
  side dropped anything, so the resolution keeps both lists whole.
- CHANGELOG.md: two adjacent new entries under ## Unreleased. Both kept.

Both sides also independently rewrote large parts of test_peakguard.py
(60 and 47 insertions against the merge base) and git merged them
textually, so the full suite was run on the MERGE RESULT rather than
inferred from the two parents: 19 passed, 0 failed, twice.

One caveat recorded rather than hidden: test_peakguard.py failed once
during the first sequential full-suite run and then passed 10/10 in
isolation and in two further full runs on this same tree. It passes on
both parents too, so this is the pre-existing flakiness CFG-04 already
disclosed, not a merge defect - it is timing- or load-sensitive. It sits
on the required CI context and can therefore block an unrelated merge at
random, which wants a card of its own.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BwRLw7eKYj2byVdwB6kbjU
2026-09-04 12:23:50 +02:00
admin 18f052a071 Merge pull request 'CFG-04: an operator can declare a second inverter, and the shape was measured against the Supervisor' (#45) from CFG-04 into release/1.0 2026-09-04 11:51:57 +02:00
glenn schrooyenandClaude Opus 5 d5c1577212 SAFETY-30: pin WHICH thresholds each sign detector is armed with, not just what the numbers are
checks / unit (pull_request) Successful in 4m48s
REVIEW FOUND A MUTATION SURVIVOR THAT UNDOES THE WHOLE PRODUCT OF AC 5, and it
is a coverage defect rather than a behaviour one - the shipped code arms the
detectors correctly today. In `_arm_sign_watchdogs()`, collapsing

    inv.sign_wd.arm(self.sign_cfg if one else self.unit_sign_cfg, ...)

to `arm(self.sign_cfg, ...)` throws the re-derived 250 W / 85 s per-unit pair
away and arms every unit with SAFETY-02's meter-facing 300 W / 180 s - and left
ALL 19 FILES GREEN. Reproduced here before fixing anything: fresh per-mutation
tree, no __pycache__, mounted :ro, graded through tools/mutation_run.sh; -31 B;
19 pass, 0 fail.

WHY NOTHING CAUGHT IT. `grep -rn "sign_wd.cfg" test_*.py` found exactly ONE
threshold assertion, part 7's N=1 arm at (300.0, 1.0) - which the mutation
PRESERVES. Nothing at a roster of two read `inv.sign_wd.cfg` at all. The ledger
mutates the VALUES in SIGN_OPTION_DEFAULTS (M10 250->300, M11 325->180, both
correctly red through the config pins) and never the WIRING that delivers them.
Part 3's behavioural checks cannot close the gap either, and the comment now
says why: B is reversed at ~2000 W with short holds, so it trips under EITHER
pair, and a fault big enough and long enough to trip under both thresholds is
evidence about neither.

THE FIX - test_watchdog.py part 3, on the real two-inverter Controller. Every
`inv.sign_wd.cfg` equals the per-unit pair, `site_sign_wd.cfg` equals the site
pair, and each detector's `against` is its own instrument. Graded against
LITERALS, because `== self.unit_sign_cfg` cannot tell "the per-unit pair" from
"whatever this Controller was handed". Both pairs are printed.

⚠️ AND THE FIXTURE HAD TO CHANGE FOR THE PIN TO MEAN ANYTHING - the recursion
worth naming, because it is the same defect class as the one being closed.
`_sign_site` set `sign_disagree_s`, `unit_sign_disagree_s` AND
`site_sign_disagree_s` all to 1 s, with two of the three magnitude gates at
300 W. A bare equality there discriminates on `min_w` alone: a mis-wiring that
delivered the right magnitude with the WRONG HOLD compares EQUAL to the pair it
was supposed to have. A check comparing two things that happen to be equal
cannot see the difference it names (MUTATION.md's third failure mode). The
three pairs are now pairwise distinct IN BOTH COORDINATES - 250 W / 1 s per
unit, 320 W / 2 s site, 300 W / 3 s shipped - a PRECONDITION asserts that
distinctness so a later edit collapsing them goes red rather than quietly
vacuous, and a second PRECONDITION asserts the literals are the pairs this
Controller actually holds.

VERIFIED BY BREAKING IT. Three mutations, each on its own freshly copied tree
with no __pycache__, mounted :ro, through tools/mutation_run.sh:

  M14  arm() handed self.sign_cfg at every roster        -31 B  RED (was the
       survivor; the AC 5 WIRING check names the wiring)
  M15  right min_w, SHIPPED hold - hold-only mis-wire    +78 B  RED, same pin
  M16  right min_w, SITE hold - hold-only, and it still
       trips inside the drive                            +83 B  RED, and the
       ONLY red in test_watchdog.py

M16 is the one that says the hold half of the equality bites on its own.
Unmutated tree: 19 pass, 0 fail, purged and fingerprinted.

Ledger rows M14-M16 and the write-up in DECISIONS/SAFETY-30-per-unit-sign.md
section 5; a CHANGELOG bullet.

NOT IN THIS PR, so it gets a card rather than a quiet fix: a stuck per-unit
power sensor would false-trip the new per-unit check at N>=2. Already-merged
SAFETY-31 has the identical exposure on the same fixture. Pre-existing N>=2
class, unreachable at the deployed roster of one.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BwRLw7eKYj2byVdwB6kbjU
2026-09-04 11:13:13 +02:00
glenn schrooyenandClaude Opus 5 22c016fadd CFG-04 fix round: the probe now measures the key it is cited for
checks / unit (pull_request) Successful in 4m33s
Review blocked this on ONE finding, and it was in the EVIDENCE, not the code.
The design and the shipped behaviour are unchanged.

THE INSTRUMENT DID NOT MEASURE WHAT FOUR DOCUMENTS SAID IT MEASURED

tools/supervisor_shape_probe.py section B validated the RECONSTRUCTED LIVE
options blob - which is missing many required keys that have nothing to do with
this card. Its refusal therefore named whichever of THOSE the validator reached
first: the committed transcript recorded `meter_freeze_s`, the reviewer's run
printed `p1_phase_export_entities`, and a run today printed `sign_disagree_w`.
The string those documents quoted - `Missing option 'inverters' in root` - was
never produced by the instrument.

And section B asserted a bare `not ok`. Any refusal at all satisfied it, so
deleting `inverters: []` from config.yaml left it printing PASS: the probe could
not detect the one regression it is the committed evidence for.

THE UNDERLYING CLAIM IS TRUE AND IS NOW MEASURED PROPERLY

Section B is an ISOLATED COUNTERFACTUAL now: the full shipped `options:` block
(expect accept), and the SAME block with `inverters` removed and nothing else
varying (expect refusal). One key differs, so the refusal has nowhere else to
come from - and the assertion is on the KEY NAME IN THE REFUSAL STRING, so the
line goes red if the refusal is ever about a different key. The probe also exits
non-zero when any case fails; without that a transcript is only evidence to
someone who reads it.

The old live-blob case survives as section B2, relabelled for what it is: an
incomplete reconstruction whose RAW half is refused for unrelated missing keys,
kept because its MERGED half genuinely demonstrates what App.options is.

VERIFIED BY BREAKING IT, WHICH IS THE WHOLE POINT

`inverters: []` deleted from config.yaml, probe re-run against
ghcr.io/home-assistant/amd64-hassio-supervisor:2026.08.0:

  == B. THE LOAD-BEARING ONE: an options blob with no `inverters` key ==
    FAIL  the shipped `options:` block validates AS IT STANDS - ...
          Missing option 'inverters' in root in GoodWe RS485 Controller
  ...
  == 2 CASE(S) FAILED ==

exit 1. Key restored, same image, same command: `== all cases passed ==`, exit
0. The transcript in DECISIONS is that restored run, re-run today, not the old
one.

THE FOUR MIS-CITATIONS

DECISIONS/CFG-04-inverter-roster.md section 4's "section B shows both halves"
sentence and its line-103 transcript; CHANGELOG.md; test_inverter.py's part-9
comment and its part-12 mutation row; and the PR description. All now attribute
the string to section B and say plainly what section B2 does not show. The
part-12 row additionally records that the probe was blind to that mutation until
review, because a mutation table that lists a defeat nothing catches is the
failure this repository keeps finding.

MUTATION.md gains it as the sixth instance of "the check's data cannot reach the
failure it names" - the first found OUTSIDE the suite, in a committed evidence
artifact, because nothing in that document had ever been pointed at tools/. Three
habits with it: assert on the CONTENT of a refusal rather than that one happened;
vary ONE thing, from an ACCEPTED baseline; and treat a committed transcript as a
check subject to the mutation battery.

TWO NON-BLOCKING FINDINGS, ALSO FIXED

  validate.py rules 5 and 6 NAMED THE WRONG INVERTER. `unit_caps()` SKIPS an
  entry with no usable `max_w`, so caps position i stops being roster position i
  the moment one entry is malformed - and rule 5 fed `caps.index(weakest)` to
  `_unit_label()`, which indexes the roster, while rule 6 paired `caps[0]` with a
  hard-wired `_unit_label(opts, 0)`. Right number, another inverter's name: an
  operator sent to the wrong device by the message that exists to stop that. New
  `unit_caps_indexed()` carries the roster index with the cap. It is latent -
  rule 9(d) refuses such a config in the same pass - but that was a property of
  today's rule ordering, not of the code, and validate_startup_config() is also
  sim/inject.py's entry point. Part 10 gains a check that asserts the fixture
  really does desynchronise the two lists, then that both messages name the right
  unit, then the counterfactual: the OLD expressions, on that same config, still
  evaluate to the wrong names.

  DOCS.md called a downgrade "safe". True of the SCHEMA - the older schema drops
  the key with a warning - and incomplete about the ADD-ON: rule 9(e) requires the
  flat `setpoint_entity` be cleared when a roster is declared, so a config that
  downgrades cleanly is by construction one whose flat actuator is blank, and the
  older version has nothing to write to. Confirmed by running release/1.0's own
  validate_startup_config() on that blob: one refusal, naming setpoint_entity.
  Recoverable and loud, but an outage until a field is refilled. The note says so
  now, and tells the operator to write the entity down before downgrading.

19/19 green in the goodwe-addon-ci image.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BwRLw7eKYj2byVdwB6kbjU
2026-09-04 10:33:51 +02:00
adminandClaude Opus 5 f000547518 SAFETY-30: grade each inverter against its own power, and the site's total against the meter
checks / unit (pull_request) Successful in 4m38s
THE DEFECT, in one line. `inv.sign_wd.evaluate(stood, self.grid, ...)` compared
the command THIS controller put on ONE actuator against what the WHOLE SITE is
exchanging with the network. At a roster of one those are two views of the same
thing - specs.md §6.2's identity - and that is what makes the check sound and
what earned it the best record in the safety table (NOTES.md: 93 % agreement
while healthy against 4 % during runaway, four observed episodes, zero false
positives). At two inverters they are not, and it fails in BOTH directions:

  FALSE TRIP  inverter A commanded -1500 W while the meter reads +1500 W is
              evidence of nothing when inverter B is discharging 3000 W exactly
              as told. Nothing is faulty and the highest-value check fires.
  MISSED      the converse, and it is worse. A unit commanded +1500 W and
              MEASURED at -1500 W, beside a sibling at +1500 W, leaves P1
              exactly where a healthy site leaves it. The summation destroys the
              evidence and no threshold recovers it.

DEV-02 had already shipped the per-INSTANCE half - one SignWatchdog per
inverter, namespaced latch, a trip on B no longer latching A. What was left was
the COMPARISON, and it is two questions rather than one:

  PER UNIT  this unit's standing command against ITS OWN measured power
            (`Inverter.batt`, holding register 0x0518, per-instance since
            DEV-02). Conclusion: "the actuator I am driving is not doing what I
            told it" - a fact about one device, so the remedy stays the per-unit
            `failsafe` SET that arbiter.CLAIM_SCOPE has classified SCOPE_UNIT
            from the day it was written. That entry read "the evidence is
            site-wide and the remedy is not"; the first half is now simply true.
  SITE      the SUM of the standing commands against the meter, as a new
            `sign_site` SET at P_SAFETY on the site actuator, latched under flat
            `site_sign_tripped` / `site_sign_reason`. This is the 2026-08-20
            fault day and NO per-unit check can see it, because every inverter
            may be faithfully executing its share of a number that is itself
            wrong. It stops every inverter and the banner names the site.

WHAT IT IS NOT, said here because two guards that overlap without saying so is
how a false-alarm generator gets built. It is not SAFETY-31: circulation.py
compares the units AGAINST EACH OTHER and catches them pushing power THROUGH
each other, which nets to zero at the meter and about which no single command is
evidence. This compares each unit against ITS OWN COMMAND. They overlap in
exactly one scenario - a unit reversing while its sibling pulls the other way -
and test_watchdog.py asserts on that fixture that both fire and what each
concludes. It is also not the saturation freeze, which is a MAGNITUDE test
(|command - measured| > 500 W) that shapes the loop and fires on a merely
saturated unit; this is a DIRECTION test that latches and parks one.

THE FOUR NUMBERS, RE-DERIVED AT TWO INVERTERS - one carried with a justification
and one refused. 1890 closed-loop runs on admin/goodwe's TEST-19 two-master rig
in which NOTHING is faulty, swept over the whole range config.yaml accepts for
`gain` and `slew_w`, across load reversals with write staggers and flapping
loads, and RUN AT BOTH ROSTERS so the N=1 arm is the control:

  unit_sign_disagree_w  250   `saturation_w / 2`. The check gates on both sides,
                              opposed, so the smallest gap it can see is 500 W -
                              exactly where compute()'s own anti-windup test
                              already says the inverter is not following. It
                              cannot fire on a divergence the control law calls
                              ordinary tracking. Worst legitimate opposition at
                              250 W: 10.0 s; the curve is nearly flat, because a
                              unit's own power chases its own command.
  unit_sign_disagree_s   85   8.5x that 10.0 s, 2.8x the firmware's own 30 s
                              link veto (inverter.LINK_STALE_S), under half the
                              180 s site hold.
  site_sign_disagree_w  300   CARRIED. Its argument is the meter's noise floor
                              and the 15 W deadband; the roster touches neither,
                              and the campaign agrees - the gate opens in 994 of
                              1050 runs at two inverters and 955 of 1050 at one.
  site_sign_disagree_s  325   NOT CARRIED, and this is the number the card
                              exists to not assume. The worst legitimate
                              crossing at 300 W is 110 s with one inverter and
                              215 s with TWO, because the command must travel a
                              rail that is the roster sum at a `slew_w` that is
                              not - reachable at gain 0.05, slew_w 50 and a
                              2.2 kW load reversal, all schema-legal. 180 s
                              would have shipped a false trip. 325 s is 1.51x
                              the measured worst, inside the 900 s billing
                              quarter and inside every episode of the fault day.

AT ONE INVERTER NOTHING CHANGES, and "nothing" is asserted rather than assumed.
The two questions are the same sentence there, so only the detector that shipped
is armed: same comparison against the meter, same 300 W / 180 s, same reason
string byte for byte, same namespaced latch and flat rollback mirror, same
`failsafe` claim, same banner, same single status row - and the site detector is
NEVER CALLED, counted on the object over twelve cycles.

VERIFIED BY BREAKING IT. Thirteen mutations on fresh per-mutation trees with no
__pycache__, mounted :ro, with the battery refusing to report at all unless the
baseline is green. Twelve red on the first pass. M4 - the site half armed at N=1
as well - SURVIVED, because the check read `disagree_since is None` and the unit
detector trips first, parks the inverter and leaves the site standing at 0 W:
the assertion ran, the sentence was true, and the data could not reach the
failure it named. Replaced with a call counter on the object; M4 is red now.
Recorded as a survivor in DECISIONS/SAFETY-30-per-unit-sign.md §5, with the
first battery's own RED BASELINE - a shared mutation directory read mid-copy -
discarded rather than reported.

RECORDED, NOT FIXED: the site comparison is defeated by a square-wave load whose
half period is about one control cycle, which holds it opposed for ~1000 s. The
N=1 control arm is what makes that interpretable - it is identical at the roster
this add-on ships, so it is a property of comparing a lagged command against a
meter and has nothing to do with the second inverter. It wants an alternation
test rather than a number, and a card of its own.

SAFETY-24's lo-only asymmetry proof re-run unchanged: 1296 combinations, 0
negative floors, `hi` +inf on every claim, every claim on the SITE actuator.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BwRLw7eKYj2byVdwB6kbjU
2026-09-04 09:33:20 +02:00
adminandClaude Opus 5 6b85acb0f1 CFG-04: an operator can declare a second inverter, and the shape was measured
checks / unit (pull_request) Successful in 4m30s
DEV-02 made every per-device value per-instance - rating, SoC, watchdogs,
heartbeat, store keys - so the code stopped assuming one inverter. The options
schema did not. `build_roster()` returned a list of exactly one and said so in
its own docstring, and there was no `inverters:` key for an operator to write,
so the roster could only ever be a roster of one.

THE SHAPE, AND WHY IT WAS MEASURED RATHER THAN CHOSEN

config.yaml had no list-of-objects anywhere, and `static_profile` carries a
whole tariff structure as a JSON string in a `str?` precisely because a nested
schema was doubted. That is a question about somebody else's software, so it was
answered by running it: `tools/supervisor_shape_probe.py` (committed) runs
Supervisor 2026.08.0's OWN `AppOptions` validator and `SCHEMA_APP_CONFIG`, out
of the release image, against this repository's config.yaml. 2026.08.0 is the
version the live install reports. The full transcript and the argument are in
DECISIONS/CFG-04-inverter-roster.md.

It accepts the list, enforces per-entry types, refuses a missing `name` /
`setpoint_entity` / `max_w` BY NAME, renders the option in the UI as a
repeatable section, and drops the key with a warning under an older schema - so
a downgrade is not the forward trap in reverse.

⚠️ AND THE `inverters: []` DEFAULT IS LOAD-BEARING, WHICH IS THE MEASUREMENT
THAT MATTERED MOST. Supervisor answers `Missing option 'inverters' in root` for
an options blob that has no such key - which every existing install's has, since
the key did not exist when they were written. `App.options` is the shipped
`options:` block deep-merged with the operator's stored one, so the empty
default is the difference between an upgrade nobody notices and an add-on that
cannot start with a schema pinned to the version that would fix it. That is
docs/deploy-rollback.md §4's trap in the FORWARD direction, found before it was
sprung. The merger was checked too: lists override rather than concatenate, so a
non-empty default could not have grown a roster behind the operator's back.

NOTHING IS INHERITED, WHICH IS DEV-02 RESTATED AS A CONFIG RULE

`name`, `setpoint_entity` and `max_w` are required of every entry. An entry that
omits `soc_entity` has no SoC sensor; it does not borrow the flat one. A
three-line fallback would have rebuilt the sibling-grading defect DEV-02 spent a
card removing, in YAML. Defaults still live in exactly one place (CFG-03):
there is no per-entry default anywhere, because there is no optional per-entry
number. A flat `setpoint_entity` left set beside a declared roster is refused
rather than ignored - it names an actuator nothing will write.

TWO PERMISSIVE READERS IN SHIPPED CODE, AND THREE MORE IN THE CHECKS

  validate.py rules 5 and 6 compared their thresholds against the FLAT `max_w`.
  At a roster of two 2000 W units with `max_w: 5000` left over from a
  single-inverter install, `sign_disagree_w: 3000` passed rule 5 while
  SAFETY-02's watchdog could fire on NEITHER unit - rule 5's own failure mode,
  reached through rule 5. They read `unit_caps()` now, which at one inverter is
  `[max_w]` exactly.

  main.py's `run_control()` re-ran the device-rating check behind
  `if self.o.get("setpoint_entity")` - the flat key, which a roster leaves blank
  - so on a two-inverter site no inverter's `max_w` was graded against the
  device it is written to, and the skip was silent. `validate_unit_ranges()`
  grades each unit against its own ESPHome and runs unconditionally.

  test_peakguard.py's `read_option()` and `_schema_bound()` and
  test_inverter.py's `read_schema_max()` matched a STRIPPED line and took the
  first hit, so the nested per-inverter `max_w:` began outranking the flat one -
  silently, and correctly, because the two bounds are the same int(100,5000)
  today. A reader that is right by coincidence is this project's named failure
  mode. All three are anchored at exactly two spaces now; the file's two halves
  disambiguate `peak_cap_w` instead of first-match, and an ambiguous key raises
  rather than picking one. test_tariff.py's copy of the idiom went with them.

THE AUDIT IS A CHECK, NOT A PROMISE

test_inverter.py part 11 finds every config.yaml-reading function in the suite -
transitively, because two of the readers CFG-04 had to change never name the
file - EXECUTES each against a synthetic two-inverter config.yaml whose
per-inverter numbers differ from its flat ones, and fails if any answers with
the per-inverter value. The table is not maintained by hand: the signature
decides, so the eleventh reader is named on its first run. config.yaml declares
`inverters:` BEFORE `max_w:` on purpose and part 11 asserts that ordering, so
the trap stays baited.

SAFETY-28's `actuator_writers()` needed no change - it was already a structural,
case-folding census - but until now there was no configuration in which two
writers on one actuator could be WRITTEN DOWN. There is now, and it is refused.

VERIFIED BY BREAKING IT

Ten mutations run through tools/mutation_run.sh and observed red, listed in
test_inverter.py part 12 with the check that bites each. Two survived the first
run and the CHECKS were changed, not the table: the inheritance check had blank
flat keys, so "inherited" and "not inherited" were the same empty string; and
the `run_control()` check asserted a SOURCE LINE was present, which re-indenting
it does not remove. Both are recorded in MUTATION.md's "the check's data cannot
reach the failure it names" section, which now carries two more habits: assert
on behaviour rather than on source text, and give a check whose failure mode is
a hang a deadline.

19/19 green in the goodwe-addon-ci image. The one-inverter path is byte-
identical: the whole existing suite runs unmodified against it.

Version bumped to 0.6.0 - the Supervisor keys the built image by `version:`, so
a schema change without a bump is a schema nobody reads.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BwRLw7eKYj2byVdwB6kbjU
2026-09-04 04:29:45 +02:00
admin b30797e1f9 Merge pull request 'SAFETY-31: measure circulating power, which nets to zero at the meter' (#44) from SAFETY-31 into release/1.0 2026-09-04 02:40:50 +02:00
adminandClaude Opus 5 7ef3d23245 SAFETY-31: measure circulating power, which nets to zero at the meter
checks / unit (pull_request) Successful in 4m28s
Inverter A charging at 3 kW while inverter B discharges at 3 kW nets ~0 W at
P1. The site reads idle while both packs are cycled through two round-trip
conversion losses continuously, for no benefit, and the wear is real.

NOTHING EXISTING CAN SEE IT, AND THAT IS STRUCTURAL. Every guard in this
add-on is a consumer of the NET figure at the grid connection: SAFETY-02's
sign watchdog gates on abs(grid_w) > 300 and the gate never opens at a netted
zero; the peak guard and the capacity tariff both bill grid exchange.
Circulating power is precisely the component of per-inverter power that the
sum destroys, so no threshold on any existing detector could reach it.

WHAT ALLOC-01 ALREADY COVERED, AND IS NOT RE-IMPLEMENTED HERE. Its AC 7
shipped the sign-coherence gate (allocator.REFUSE_SIGN, graded by
test_alloc.py part 6): an allocation whose shares carry two signs is REFUSED,
both units named, no shares returned. That is the COMMAND half - the allocator
can no longer command circulating power. This commit is the MEASUREMENT half:
circulation the allocator NEVER COMMANDED.

  app/circulation.py   the sensor and the trip
  main.py              site_circulating_w, the evaluation, the claim, the alarm
  arbiter.py           `circulation` classified SCOPE_SITE, with the argument
  store.py             a flat, site-level durable latch
  mqtt.py              sensor.goodwe_circulating_power
  config.yaml          two options, two schema ranges, CFG-03 discipline

THE SENSOR: sum(|Bi|) - |sum(Bi)|. Zero when the units pull the same way,
2*min(|Ba|,|Bb|) when they oppose. DERIVED FROM MEASURED PER-INVERTER POWER -
Inverter.batt, register 0x0518 - and never from the allocation record. The
cheap version would be simpler and worth nothing: ALLOC-01's gate already
guarantees the record is sign-coherent, so a record-derived sensor reads zero
BY CONSTRUCTION and can only confirm that the allocator agrees with itself,
which is the third failure mode MUTATION.md names. What this catches is a unit
ignoring or lagging its share, a stale share still being executed, a
maintenance or SAFETY-25 pin holding one unit while the loop drives the other,
or HW-01's power stage running its last instruction for 6 h 25 m with the
comms dead and the allocation record impeccable throughout. batt became
per-instance in DEV-02; before that this could not have been written.

VERIFIED BY MAKING ONE UNIT IGNORE ITS SHARE, on the TEST-19 two-master rig:

  S = -2500 W   shares a = -1250 W  b = -1250 W   <- record ok, ONE sign, sums
  MEASURED      A = -1250 W  B = +1000 W          <- hardware
  sensor over the RECORD     :    0 W
  sensor over MEASURED power : 2000 W  -> trips at 190 s

and the card's own scenario, A -3000 W against B +3000 W at zero house load:
the meter reads +0 W, the sensor reads 6000 W, and the shipped SignWatchdog's
predicate is FALSE on 30 of 30 cycles.

WHAT "ACTED ON" MEANS - decided, and recorded in DECISIONS/. The trip files
Claim.set("circulation", P_SAFETY, 0.0) on the SITE actuator: every inverter
to 0 W, latched. HW-01 established that commanding a wedged inverter achieves
nothing, so the remedy is not aimed at it. A circulating loop needs TWO
participants and one of them is THIS CONTROLLER, faithfully driving the
listening sibling into the one that stopped listening. Stopping (1) halves the
loop, which needs no cooperation from the wedged unit, and (2) - the more
important half - makes the residue VISIBLE at the meter instead of cancelled
at it, where every ordinary guard can finally see it. What it cannot do is
stop the wedged unit; the notification says so and names the isolator as the
last actuator. SITE-scoped because the quantity is defined over the roster and
is identically zero for any one unit - there is no fact of the matter about
which of two opposing inverters is the offender, so filing it per-unit would
invent an attribution and could park the only unit still listening.

THE WINDOW IS FROM THE RIG, NOT A ROUND NUMBER (AC 3). 924 closed-loop runs in
which NOTHING is faulty, over both families of legitimate opposition (7
reversals x 5 write staggers; 7 flap periods x 4 amplitudes), swept across the
whole range the schema accepts for gain and slew_w. Worst CONTINUOUS
legitimate opposition by threshold: 505.0 s at 100 W, 40.0 s at 250 W, 10.0 s
at 300 W, 5.0 s at 400 W and above. The knee is 400 W and it is the schema
floor - below it, ordinary operation holds the sensor over the line for
minutes and no window inside the 900 s billing quarter could tell that from a
fault. circulation_w 700 is 1.75x the knee, the headroom bought for inverter
B's ramp and lag being PLACEHOLDERS until SPIKE-04 measures them.
circulation_hold_s 75 clears three bounds: 15x the worst legitimate episode,
2.5x the firmware's own LINK_STALE_S veto, 12x inside the quarter. A momentary
opposition while one unit slews through zero is LEGITIMATE - writes are
serialised, so B's number lands up to a cycle after A's - and 0 of the 924
runs trip.

THE ALARM SURVIVES AN HA RESTART (SAFETY-34). persistent_notification is in
memory, which is exactly how the 2026-09-02 outage went unseen for 6 h 25 m
with the detector correct throughout. The latch is persisted to /data as flat
site-level keys and the notification is RE-RAISED on the first cycle after
every start, through the same code path as a fresh trip - two paths would be
two chances for the restart one to rot unnoticed.

AT N=1 NOTHING CHANGES (AC 5). |B| - |B| is 0 for every reading including one
nobody took, no claim is ever filed, the arbitration is byte-identical, and
the status page says n/a rather than claiming to watch something that cannot
happen.

VERIFIED BY BREAKING IT (AC 4). 18 mutations, all RED on named checks, each on
a freshly copied tree with no __pycache__ mounted :ro. M10 - the sensor
rewritten to read self.allocation.shares - is the headline: it takes AC 2 red.
Three mutations are +0 B, the risky delta, and are marked as such. One
equivalent mutant (the max(0.0,...) guard) is ARGUED rather than claimed:
searched over 700 000 rosters without a negative. One genuine SURVIVOR was
found and closed - publish() turning an unknown into a published 0 W, the
sensor's own None rule defeated one layer out. Full ledger in DECISIONS/.

arbiter.CLAIM_SCOPE gains its ninth source, so test_peakguard.py's 10f and 10g
tripwires and test_arbiter.py's scope table went red on the line the append
was written. Updated deliberately, with the argument, as their own comments
require. Full 19-file suite green.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BwRLw7eKYj2byVdwB6kbjU
2026-09-04 01:56:23 +02:00
admin b6f41f736c Merge pull request 'DEV-02: per-instance Inverter objects - rating, SoC, watchdogs, heartbeat and store keys stop being scalars' (#43) from DEV-02 into release/1.0 2026-09-04 00:36:06 +02:00
glenn schrooyenandClaude Opus 5 753f700539 DEV-02: merge release/1.0, and close the two review blockers
checks / unit (pull_request) Successful in 4m15s
PR #43 was rejected on two findings and had gone unmergeable behind SAFETY-28
and the ALLOC-01 fix. This is the merge commit; the conflict resolution and both
fixes are below, because a merge that also changes behaviour has to say so.

THE MERGE, AND WHAT IT COST
===========================
Two conflicts in main.py, both where SAFETY-28 and this card touched the same
method:

  * `write_setpoint()` split into a site entry point plus a per-unit
    `_write_unit()` here, while SAFETY-28 put its record gate in the old
    single-unit body. `write_refusal()` now takes the INVERTER it is about.
    Asking it with `self.unit` - as release/1.0 does - would authorise A's share
    on B's wire, and would also trip test_inverter.py part 1's AST scan, which
    goes red on any read of a Controller N=1 view inside Controller.
  * the SAFETY-28 gate sits above the clamp and below the non-finite coercion,
    exactly where release/1.0 put it, and is now asked about `inv`.

Fallout the merge produced in the checks, re-aimed rather than relaxed:

  * every fixture that calls `write_setpoint()` DIRECTLY - the clamp probe, the
    hung-heartbeat experiment and its serialised counterfactual, the split
    deadline probe - now arms a real allocation record first. test_inverter.py
    grows an `arm()` built through the shipped `resolve()`, the same shape
    test_clamp.py's is: the per-unit envelopes are filed as real `supervised`
    claims and the site target is their sum, so the water-fill has exactly one
    answer and the fixture cannot quietly become its own allocator.
  * test_clamp.py's two-unit failsafe fixture assigned `c.units`, which DEV-02
    made a derived property with no setter. It appends a real `Inverter`.

BLOCKER 1 - AC 4's ARBITER-BOUND EVIDENCE WAS VACUOUS
=====================================================
test_peakguard.py claimed "each unit's `supervised` bound is ITS OWN `max_w` -
give inverter B a different rating and the claim filed on inverter B moves with
it", and compared B's bound against `_b2.max_w`. `second_inverter()` DEFAULTED
B's rating to `LIVE_MAX_W`, which is A's. IT COMPARED (-5000, 5000) AGAINST
(-5000, 5000): a number against itself, unable to observe the failure it named.

Reproduced: filing the per-unit `device`/`supervised` claims from
`self.inverters[0]`'s numbers while leaving `actuator=self.actuator_of(..., inv)`
alone left ALL 19 FILES GREEN. At a roster of two with A=5000/B=3000 that makes
inverter B's planned envelope (-5000, 5000) instead of (-3000, 3000) - a 2000 W
over-command the arbiter believes is supervised. It is a DIFFERENT defect from
the actuator variant the static routing pin catches, and only the actuator
variant was in the mutation table.

  * `second_inverter()` gives B 3000 W - a hypothesis, marked as one - for every
    fixture in the file, so no check there can compare B against A by accident.
  * the claim is asserted against LITERAL numbers rather than against an
    expression that can read the same object twice, for `supervised` AND for
    `device` (whose `dev` had the same defect), plus the envelope the ARBITER
    RESOLVED for B - a claim filed right and resolved wrong is the same defect
    one layer down.
  * a PRECONDITION check fails if the two ratings are ever made equal again.
  * the BOUND mutation is in the table, beside the actuator one, and was
    observed RED (3 checks in test_peakguard.py) via tools/mutation_run.sh.

⚠️ THIRD INSTANCE THIS SESSION of a check whose DATA cannot reach the failure it
names - ARB-03's call-site scan saw 3 of 8 appends, ALLOC-01's replay generator
saw 0 escapes where a widened one saw 39,991. MUTATION.md gains a section for it
beside the stale-bytecode and masking ones, and the rule is written at the line:
ANY CHECK ASSERTING "X DIFFERS FROM Y" MUST BE RUN ONCE WITH X AND Y ACTUALLY
MADE DIFFERENT.

BLOCKER 2 - THE LATCH WAS SILENTLY DISARMED BY THE ROLLBACK ROUND TRIP
======================================================================
store.py's rule 2 keeps the flat keys "so a rollback still finds its latch". The
operator path that rule contemplates is a ROUND TRIP, and this card lost the
latch on it:

  1. install migrates          -> schema_version=1, unit/inverter-a/... = False
  2. operator DOWNGRADES; SAFETY-02 trips inside the downgrade window and the
     old add-on writes only the flat `sign_tripped: true`
  3. operator upgrades again   -> `rep.ran` is False, so `_grade_store_migration()`
     returned early, and `Inverter.__init__` read the namespaced key: False

Observed: the controller came up with `sign_wd.tripped = False` while
/data/state.json said `sign_tripped: true`. That is store.py's own header
sentence - "the file still says sign_tripped: true, the banner is green, and the
controller resumes driving the wrong way" - rebuilt by the version marker. A
firmware version change with a rollback path was performed on this site on
2026-09-02, so this is not hypothetical.

Three changes, each graded by a mutation observed RED:

  * THE OPERATOR'S CLEAR CLEARS BOTH SPELLINGS. That is what removes the
    "re-arm forever" objection the `rep.ran` gate existed to answer: with the
    fossil cleared, `flat True + namespaced False` is unambiguously a
    downgrade-window latch.
  * A TRIP MIRRORS THE FLAT PAIR. Rule 2 only ever covered the latch present AT
    MIGRATION TIME - nothing flat was written for a trip taken afterwards, so an
    operator who downgraded found `sign_tripped: false` and came up DRIVING.
    store.py claimed the staleness could only fail toward a SPURIOUS latch. It
    could not; that sentence is corrected rather than left standing.
  * THE GUARD RUNS ON EVERY START, and asks the STORE - not the roster - whether
    anything namespaced is latched. A mirrored trip on B must not re-arm a
    healthy A, and the store is the right place to ask because it holds every
    `unit/*/sign_tripped` this install has written, including one belonging to a
    unit that is not in today's roster.

Graded by the three-step scenario itself, run end to end in test_inverter.py
part 2, with all three preconditions asserted - including that the catching
start did NOT migrate anything, which is what used to skip the guard. Part 2's
idempotence check now PRESSES the button instead of hand-writing the store,
because the state it used to construct is not one the shipped clear path can
produce. Part 3 grades the mirror and the clear on a real roster of two.

test_watchdog.py's "the flat key is NOT written" assertion is re-aimed rather
than deleted: its argument was right about the READ and wrong about the WRITE.
Nothing at runtime reads that key, and the one thing that does ignores it
whenever any namespaced latch is set - which a sibling's trip always leaves.
What its absence actually cost was the rollback.

HANDOVER.md and DOCS.md said the flat key "is never read again", which was the
instruction an operator clearing a trip by hand would follow. Both corrected: it
is a maintained rollback view, it IS read on every start, and clearing a trip by
hand means clearing both spellings.

MUTATIONS THIS ROUND, each applied on a purged tree via tools/mutation_run.sh
and observed RED:
  * per-unit `device`/`supervised` BOUNDS from `self.inverters[0]`, actuator
    left correct                                   -> test_peakguard.py 10g
  * `_grade_store_migration()` gated on `rep.ran`   -> test_inverter.py part 2
  * the operator's clear leaving the flat keys set  -> test_inverter.py part 2/3
  * a trip not mirroring the flat pair              -> test_inverter.py part 3
  * the guard asking only `self.inverters[0]`       -> test_inverter.py part 3

19/19 files green on the merged tree. No hardware was touched.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BwRLw7eKYj2byVdwB6kbjU
2026-09-03 23:37:23 +02:00
admin f594543988 Merge pull request 'SAFETY-28: gate the write path on the allocation record, not on how many config keys exist' (#42) from SAFETY-28 into release/1.0 2026-09-02 15:44:40 +02:00
glenn schrooyenandClaude Opus 5 d48c6b971d DEV-02: correct the operator instruction the latch rename made wrong
checks / unit (pull_request) Successful in 4m13s
HANDOVER.md told an operator to "delete `sign_tripped` from
/data/state.json" to clear a sign-disagreement trip by hand. After this card
that key is a FOSSIL: the live latch is `unit/<inverter>/sign_tripped`, and
the flat one is left in the file only so a rollback finds its latch and is
never read again. Following the old instruction would delete a key that clears
nothing, on the one path an operator reaches while staring at a FAILSAFE
banner - so the instruction would look like it had failed.

DOCS.md's §SAFETY-02 section named the file but not the key; it now names both,
and says why there is one per inverter.

No code change; the suite is unaffected and green.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BwRLw7eKYj2byVdwB6kbjU
2026-09-02 15:02:58 +02:00
glenn schrooyenandClaude Opus 5 e941bf7f62 DEV-02: zero every unit's target when the operator stops, not just the site's
checks / unit (pull_request) Successful in 4m12s
A hazard THIS CARD CREATED, found by re-reading the operator paths rather than
by a failing check - so a check now exists for it.

Before DEV-02 the heartbeat re-emitted `self.target`, so the stop button
zeroing that one scalar was enough: the next refresh carried the zero. The
heartbeat now re-emits `inv.target` - it has to, or it would put the SITE
number on every inverter, which is the ARCH-01 broadcast fault arriving once
every `heartbeat_s` on a path with no allocator in it.

So a stop that zeroed only `self.target` left each unit's LAST SHARE standing.
No cycle has run yet at that moment, so nothing else would have cleared it, and
the very next heartbeat - up to `heartbeat_s` later - would put it back on the
wire. The operator presses stop, watches the inverter go to zero, and sees it
resume seconds later.

`command_site_zero()` moves both together and carries the reason. It is one
method rather than two lines at three call sites precisely because the two
lines have to stay together: shutdown(), the stop button and maint_abort all
mean the same thing, and 0 W is the one value that may legitimately be written
site-wide.

test_inverter.py part 6 presses stop with 995/995 standing and then runs the
SHIPPED `send_heartbeats()` before any cycle, which is the racing refresh. The
mutation that zeroes the site target alone takes it red.

19 files green.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BwRLw7eKYj2byVdwB6kbjU
2026-09-02 14:58:54 +02:00
glenn schrooyenandClaude Opus 5 e306c74cb8 DEV-02: per-instance inverter objects, so nothing is graded against a sibling
checks / unit (pull_request) Successful in 4m15s
Every piece of per-device state in the Controller was a scalar, and several of
them are safety inputs. app/inverter.py introduces an `Inverter` that owns its
entities, its rating, its device range, its SignWatchdog, its last_write and
its last_beat, under store keys namespaced by unit name. The Controller holds a
list of them and keeps only what is genuinely site-level: the P1 reading, the
site integrator, and the tariff quarter.

WHAT THE SCALARS WERE SILENTLY ASSERTING

  dev_min/dev_max   one pair, read from one setpoint_entity. A second
                    inverter's rating was NEVER READ AT ALL, so its clamp, its
                    freeze rail and the peak guard's achievable_w were the
                    first one's numbers.
  soc               one reading into the maintenance FSM, SAFETY-24's pack
                    floor and arbitrage's bounds. An average lets the emptier
                    pack be driven below its own floor.
  sign_wd           ONE SignWatchdog, whose own docstring says "one instance
                    per actuator", latched under FLAT store keys - so a trip
                    caused by B latched A across restarts and one operator
                    press cleared both.
  last_beat         one deadline and one serialised hass.call(), so a hung
                    write to A ate B's 30 s layer-1 budget.

actual_w BECAME SITE LEVEL WHILE THE READINGS BECAME PER-INSTANCE, and those
are opposite directions on purpose. compute()'s anti-windup test is
`abs(prev_w - actual_w) > saturation_w` with prev_w the SITE target, so feeding
it one inverter's power compares a site number against a unit number, trips the
saturation freeze permanently and leaves a standing grid error. Measured on
admin/goodwe's two-master rig (tools/alloc_sim.py --splits, 2 kW load, 40
cycles), worst |delta| between splits at the meter:

    gain    one unit's power      the site sum
    0.2           510 W                0 W
    0.4           250 W                0 W
    0.6            50 W                0 W

That was ALLOC-01's disclosed finding; test_alloc.py part 8 kept its stimulus
and now grades the other row.

THE STORE MIGRATION IS GRADED, NOT MERELY PERFORMED. sign_tripped/sign_reason
move to unit/<name>/... once, verified by READING BACK what was written, and
the version marker is set only when nothing that carried state was lost. The
flat keys stay in the file so a rollback still finds its latch. And __init__
compares the pre-migration flat latch against what unit A actually came up
with: if the latch did not survive it is RE-ARMED from the legacy value and
shouted about. A latch that silently fails to migrate is a disarmed safety
guard on an install whose state file says it is protected - which is strictly
worse than never persisting it, because now there is evidence saying it is
fine. test_inverter.py part 2 breaks the migration and watches the guard fire.

HEARTBEATS ARE INDEPENDENT AND THE BUDGET IS DERIVED. Each inverter owns its
deadline, the refreshes go out concurrently, and each write is bounded by
WRITE_BUDGET_S = 4 s. The inequality is graded rather than asserted: 4 +
heartbeat_s's schema maximum of 25 < 30, validate.FIRMWARE_INGEST_VETO_S.
Verified by injecting a transport that accepts and never answers.

live_units() ANSWERS HONESTLY. A unit whose every write has been rejected for a
whole layer-1 window is not commandable; the allocator drops it, the survivors
carry its share, the action log names it, and the dropped unit is commanded
0 W rather than left standing on its last share. A roster entry with NO
setpoint_entity is deliberately not handled there - that is a configuration
that cannot be delivered, and it reaches main.py's refusal branch, which is how
that branch keeps a live trigger after this card removed its old one.

AT N=1 NOTHING MOVES. The removed scalars survive as read/write properties of
the sole inverter, so every existing replay runs unmodified - and they REFUSE
at N>=2 rather than answering for the first inverter, which is the tripwire on
a consumer that was never made per-instance.

EVIDENCE. 19 files green. test_inverter.py is new (82 checks). Eighteen
mutations were applied to the shipped modules on a purged tree via
tools/mutation_run.sh and each was observed RED. Two of them SURVIVED first
time and the checks were changed rather than the table: the serialised dispatch
and the shared last_beat both passed while part 6 gathered its own writes and
computed its own `due` list. send_heartbeats() was extracted from run_control()
so the shipped dispatch is reachable by a check at all.

INVERTER B STILL DOES NOT EXIST. build_roster() returns exactly one inverter
from the flat options and is the one function CFG-04 changes; every two-unit
figure here is architecture, and the second rating in the checks is marked a
hypothesis.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BwRLw7eKYj2byVdwB6kbjU
2026-09-02 14:50:43 +02:00
Claude 591c35ed01 SAFETY-28: gate the write path on the allocation record, not on key count
checks / unit (pull_request) Successful in 4m19s
specs §1.5 makes "any configuration in which two writers can reach one
actuator" a non-goal. That non-goal was enforced by counting config keys:
validate.py's ACTUATOR_WRITE_KEYS = ("setpoint_entity",), consumed at rule 1,
with a comment stating the guarantee outright - "there is exactly one such
key, so a second writer is not expressible in the options schema at all".

That was true and it graded THE SHAPE OF THE OPTIONS SCHEMA, not the writes.
Add CFG-04's per-inverter config - a roster of inverters each with its own
setpoint_entity - and there are two real writers with len() of that tuple
still equal to 1. The check stays green while the property it protects is
gone. sim/inject.py's two_writers scenario asserted on the same tuple, so it
went green too. That is this repository's named failure mode: a check that
observes something other than what it claims to observe.

Demonstrated rather than argued. test_validate.py part 2 now constructs the
hazardous per-inverter config, asserts that the OLD proxy is still green on
it, and then asserts the new check refuses it. Against release/1.0's
validator the updated sim scenario reports: "validate_startup_config()
ACCEPTED a configuration in which 3 declarations reach the ONE actuator
number.goodwe_setpoint ... the old proxy reports 1 write key(s) on this same
config and is therefore GREEN on it".

THE WRITE PATH IS NOW GATED ON THE RECORD
=========================================
Controller.write_refusal() asks Allocation.authorises() whether the single
allocator placed exactly this number, for this unit, on this tick.
write_setpoint() refuses anything else. A second writer with arithmetic of
its own cannot satisfy that - its number appears in no record - so it has to
file a Claim and go through resolve(), which is the one allocator. "Exactly
one allocator per shared resource" stops being a convention somebody can
forget and becomes something the write path checks.

The refusal is a SUBSTITUTION, not a return: 0 W goes on the wire in place of
the number nothing stands behind. Returning would leave the inverter latched
on its last command with the ESP32 heartbeat still being fed - holding an
unauthorised setpoint quietly, which is the outcome the gate exists to stop.
AC 1 is "refused at the write path, not merely logged", and test_clamp.py
part 7a grades the device's writes, not the log.

The gate sits BELOW the non-finite coercion and ABOVE the clamp. Below,
because a nan is loss of input and rule 1 has already turned it into 0 W.
Above, because the question is who chose this number, and the answer is only
meaningful about the number that was asked for - gating the CLAMPED value
would refuse exactly the cycles SAFETY-03 exists for, since a clamped write
differs from the allocator's share by construction. Mutation M7 moves the
gate below the clamp and turns nine checks red, part 6c among them.

A STALE RECORD CANNOT BE REPLAYED
=================================
Every Allocation now carries the `tick` it was made for. It is handed IN by
the caller - plan(..., tick=) - rather than counted inside the allocator,
because test_alloc.py part 10 grades that the module holds no state at all,
and a serial number incremented in there would be the cached-across-ticks
thing the envelope rule forbids wearing a different hat.

Controller.alloc_tick advances ONCE PER RESOLUTION, not once per loop
iteration, and both halves are load-bearing:

  * a new allocation makes the previous record stale immediately, so a record
    whose envelopes have moved cannot authorise a write. That is the replay
    half (AC 2), graded by capturing a real record, running another real
    cycle, putting the old one back and observing refusal.
  * the "inputs missing, not yet stale" hold returns BEFORE the allocator
    runs, exactly so one dropped meter reading does not zero the inverter,
    and the heartbeat re-affirms self.target through this same gate while it
    does. A tick incremented per loop iteration would refuse that heartbeat
    and turn the hold into the outage it exists to prevent. Graded.

An UNSTAMPED record (tick None) authorises nothing: "I cannot say when I was
made" fails closed rather than reading as tick zero.

THE FAILSAFE CANNOT DEADLOCK BEHIND THE GATE, AND HERE IS WHY
=============================================================
write_setpoint() is also how layer 2 commands 0 W. cycle()'s two refusal
branches substitute a 0 W failsafe and write it like any other cycle;
shutdown() and the operator's stop button do the same. EVERY ONE OF THOSE
RUNS WHILE THE ALLOCATOR HAS REFUSED - ok is False and there are no shares -
so a gate that asked the allocator's permission to command zero would block
the safety write behind the very component whose failure the safety write
answers. A gate that can do that is worse than the hole it closes.

Resolved by authorising 0 W unconditionally, and on the VALUE rather than on
a failsafe=True flag: a flag is an assertion by the caller, which is exactly
what a second writer would pass; the value is a fact about what will be
written. The argument that this is safe and not merely convenient is that the
hazard §1.5 names is N-times loop gain from BROADCAST - handing every inverter
the same target so each supplies it in full (allocator.py's opening argument;
TEST-19 measured a permanent 4000 W p2p limit cycle at gain 1.0 with no guard
firing). At S = 0 the broadcast and the correct allocation COINCIDE: a_i = 1
for every unit gives every unit 0 W, which is exactly its share. There is no
over-command to make at zero. Said at the line, in write_refusal().

test_clamp.py part 7c drives it end to end through the real cycle() and the
real REFUSE_EMPTY branch: the allocator refuses every tick, the device still
sees 0 W, and the action log says ARBITER: REFUSED rather than WRITE REFUSED
so the two failures stay distinguishable to whoever has to debug them.

unmet_w IS STILL NOT ok
=======================
The gate reads ok and the unit's share and never unmet_w. allocator.py:179
says why: an allocation that could not place every watt is still safe to
write, and fusing them would let one saturated inverter park the whole site.
Graded on a record with 3800 W unmet and every share legal - mutation M5 adds
`or self.unmet_w` to the gate and that check goes red.

THE CONFIG CHECK, REPLACED RATHER THAN DELETED
==============================================
actuator_writers() counts WRITERS PER ACTUATOR instead of option keys. It
walks the options TREE rather than looking for a container called `inverters`,
because CFG-04 has not chosen that name yet and a census that guessed wrong
would go green while two writers existed - the same defect one step along.
Entity ids are folded to lower case so a second writer cannot be smuggled in
as Number.X versus number.x.

Two inverters with two entities are ACCEPTED - that is what the per-inverter
roster is for, and a validator that refuses the feature it guards is one
somebody switches off. Two declarations aimed at ONE entity are refused,
naming the actuator and every writer pointed at it. That includes the case an
author will meet first - keeping setpoint_entity as A's and listing A again -
because "they happen to be the same entity, so it is fine" is precisely the
reasoning that makes two writers invisible.

ACTUATOR_WRITE_KEYS survives ONLY as the enumeration a census needs, with its
guarantee comment deleted; nothing asserts on its length any more. Keeping the
name is also what stops admin/goodwe's current two_writers scenario failing on
an AttributeError between the two merges.

WHAT NEITHER CHECK OBSERVES, SAID OUT LOUD
==========================================
The census sees CONFIGURED writers. A second write path added in CODE - a
hass.set_number() call next to some new strategy - declares nothing and is
invisible to it, exactly as it was invisible to the tuple. That half is not
closed at startup and cannot be; it is closed at runtime by the record gate,
which does not care what the options look like or who called the method. The
two checks are deliberately different kinds, and only the runtime one survives
a schema this file has not seen yet.

EVIDENCE
========
* Full 18-file suite green on a purged tree (tools/mutation_run.sh).
* Verified by breaking it - seven mutations, each on a purged tree, each
  reverted and re-verified:
    M1 remove the gate                -> test_clamp red (4 checks)
    M2 make the zero exit an amnesty  -> test_clamp red (12 checks)
    M3 drop the tick comparison       -> test_clamp red (5 checks)
    M4 delete the census refusal      -> test_validate red (3 checks)
    M5 fuse unmet_w into ok           -> test_clamp red (1 check)
    M6 freeze the tick on the live path -> test_clamp red (2 checks)
    M7 move the gate below the clamp  -> test_clamp red (9 checks)
* AC 5: no existing check was weakened. The two edits to test_clamp.py are
  fixtures, not assertions - parts 5 and 6c call write_setpoint() directly
  with a number nothing allocated, which is now refused, so they say where
  their number came from. Every assertion in both parts is unchanged, and
  part 7f asserts that across part 3's sixty real cycles the gate refused
  zero writes.
* admin/goodwe's TEST-19 norig scenarios (planner_binding, two_master_plant,
  two_master_broadcast) still pass against this tree - they import the
  add-on's control law across the repo boundary.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-02 13:56:48 +02:00
admin 3030f72b9e Merge pull request 'ALLOC-01: allocate the site grid target across N inverters, sum-invariant' (#41) from ALLOC-01 into release/1.0 2026-09-02 12:13:33 +02:00
glenn schrooyenandClaude Opus 5 3fe3c7acb0 ALLOC-01: clamp each envelope end on its own, and widen the replay that missed it
checks / unit (pull_request) Successful in 4m9s
Two blocking findings from the review of 186e13c. The second is why the first
survived, and it is the one this commit is really about.

THE CLAMP. `_clamp_int()` folded both ends of the interval into one
`min(max(...))` and substituted `v` itself for a bound that was infinite. That
reads as "an absent bound cannot bind", and it is not what it does: with
`hi == inf` the expression collapses to `min(max(v, lo), v) == v`, so A MISSING
CEILING SILENTLY DISCARDED THE FLOOR. `_clamp_int(0, 2142, inf)` returned 0. It
reached the shares through all three call sites - the base, the pin clamp and
the post-floor clamp.

The worked failure: bounds `{a: [2000, +inf], b: [-5000, 5000]}` against a
+1000 W site target returned `a=+500, b=+500` - inverter-a commanded at a
quarter of its own 2000 W floor - while THE SAME CASE WITH A FINITE CEILING
correctly REFUSES on sign coherence. So one defect broke the ticket's first
named deliverable ("each share clipped to that unit's UnitBounds interval") and
suppressed a circulating-power refusal that should have fired. Both now behave
identically, and the refusal is the behaviour.

Not reachable on the live install - N=1 is a pass-through, and via main.py the
supervised claim unconditionally files a finite +/-max_w LIMIT at P_SAFETY that
pre_resolve's gate can never filter because nothing outranks P_SAFETY. But
`plan()` and `arbiter.allocate()` are the public envelope contract SAFETY-28 and
DEV-02 are being asked to build on, and `UnitBounds()` DEFAULTS TO
`(-inf, +inf)`, so a one-sided envelope is the ordinary case at N>=2 rather than
an edge, and any caller with one inherited the defect.

Fixed by clamping the two ends independently: cast to int, apply `lo` only if it
is not -inf, apply `hi` only if it is not +inf. `_int_envelope()` already passes
infinities through untouched and needed no change; it is the only other place in
the module that special-cases infinity, and the rest of the tree's `isfinite`
calls are input validation in unrelated modules.

THE RECORD. `UnitPlan.explain()` printed
`inverter-a -> +500 W in [2000, +inf] (weighted share)` - a line asserting a
share is inside an interval that excludes it, in the record SAFETY-28 gates on.
It now ASKS: `within_envelope` checks the share against the interval, and a
violated plan prints `OUTSIDE ... - ENVELOPE VIOLATED, DO NOT WRITE` instead. A
dropped unit is exempt and prints "not commanded" - it was told nothing, its
interval may be a contradiction no number is inside, and a banner there would
cry wolf on the one row that is working.

THE REPLAY THAT COULD NOT SEE IT, WHICH IS THE FINDING THAT MATTERS. The
250 000-tick replay drew every envelope as `B(-uniform(0, RATING),
uniform(0, RATING))` - finite on both ends and containing zero, every time -
while the check it fed claimed "no share ever leaves the envelope it was clamped
into", which reads as a statement about `UnitBounds`. The data could only
exercise a symmetric closed interval around zero. That is why it reported 0
escapes against a live defect while the reviewer's own 120 000 ticks reported
6 254.

The generator now draws from every shape `UnitBounds` can express: finite
straddling zero, half-open above, half-open below, finite excluding zero in each
direction, half-open AND excluding zero, and bare `UnitBounds()`. Over the same
seed and the same 250 000 ticks it draws 166 657 half-open intervals, 55 233
bare ones and 222 082 that exclude zero, and those counts are PRINTED and
asserted so "the replay covers half-open intervals" is a number a reader can see
rather than a sentence the file asserts about itself. The escape check also
dropped its 1 W tolerance: `_int_envelope()` narrows inward, so there is nothing
for slack to absorb except a defect.

GRADED, NOT MERELY APPLIED - the acceptance bar for this round. A/B on one seed
and one tick count, against the defective clamp: THE OLD GENERATOR SEES 0
ESCAPES, THE NEW ONE SEES 39 991. Reverting the fix under the widened generator
takes test_alloc.py RED on four checks (the escape count, the record check, and
both halves of the new half-open block); re-applying it takes it green. The
collapse is now a row in part 12's mutation table, recorded as the mutation that
actually shipped rather than a hypothetical one.

TWO CHECKS RE-AIMED RATHER THAN LOOSENED.
* Part 6's "the sign gate never fires on an ordinary tick" counted refusals over
  the whole replay. Envelopes that EXCLUDE zero are precisely what that gate is
  for, so the widened generator makes refusals correct there. It now counts an
  ORDINARY tick explicitly - no pin, every envelope contains zero - and asserts
  0 refusals over 77 533 of them, half-open and bare envelopes among them. That
  is stronger than what it replaced, not weaker.
* Part 1's third check summed `sum_w - sum(shares)` over ticks where
  `unmet_w == 0`, and `unmet_w` IS that difference - so it was true by
  construction and would have gone quiet rather than red. It now measures the
  one rounding that is actually left: the site-level `quantisation_w`, totalling
  -39.8 W over 137 964 allocations, i.e. -0.0003 W per tick. Largest remainder
  against the per-unit alternative is still graded in part 2, where the
  counterfactual drifts -125 W over 50 000 ticks at three inverters.

Verified: all 18 suites green in the CI image on a tree with no bytecode cache;
test_alloc.py also re-run through tools/mutation_run.sh, which purges. AC 2 and
AC 3 are untouched by this change - the rig and part 8 use symmetric finite
envelopes, which the old and new clamp treat identically - and part 8 is green.
No hardware touched; admin/goodwe not fetched, not modified, not pushed to.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-02 11:49:18 +02:00
glenn schrooyenandClaude Opus 5 186e13ceca ALLOC-01: allocate the site grid target, sum-invariant, never broadcast
checks / unit (pull_request) Successful in 4m6s
ARB-03 left `allocate()` as a documented seam that passed through at N<=1 and
DECLINED at N>=2, with the reasoning recorded at the line: the obvious
placeholder - hand the site target to each inverter - IS the ARCH-01 fault, and
"a placeholder that cannot be told apart from the real thing by any guard we
have is worse than no placeholder". This fills the seam.

WHY A BROADCAST IS A FAULT AND NOT AN INEFFICIENCY. The control primitive is
meter emulation: the master reports a FABRICATED grid reading and the inverter
regulates itself to it, so one number means "the battery moves X W" to this
add-on and "the grid is at X W" to the inverter - an identity that holds only at
N=1. Hand two inverters the same target and each supplies it IN FULL, so the
loop gain at the meter becomes N times the per-unit gain. Reproduced on
admin/goodwe's two-master rig against this tree: -400 W export overshoot at
gain 0.6, and at gain 1.0 - which config.yaml accepts as its documented maximum
- a permanent 4000 W peak-to-peak limit cycle, commands alternating
1000/2000/1000/0 W, with NOT ONE GUARD FIRING. The sign watchdog is evaluated on
every cycle and never trips, because the disagreement flips on alternate ticks
and never holds its 180 s window.

WHAT WAS BUILT. `app/allocator.py`, host-side and strictly above the driver
seam. It consumes intervals and a number and nothing else - no claims, no
priorities, and no measurement, because an allocator that read P1 would be a
SECOND integrator on the site measurement.

  * ENVELOPE CLAMP, from ARB-03 stage 1's `UnitBounds`, read PER TICK. `plan()`
    is a pure function and the module holds no state, so there is nowhere for a
    construction-time envelope to be cached.
  * WATER-FILL by weight, with the surplus of a full unit moving to the others.
    Weights express PREFERENCE, envelopes express PERMISSION: a zero weight is
    honoured while another unit has headroom and overridden when it does not,
    because the SUM is the safety property and stranding capacity behind a
    comfort choice manufactures a standing error at the meter.
  * LARGEST-REMAINDER ROUNDING. The target is rounded ONCE, at the top; every
    sum below that line is integer arithmetic, so it cannot drift. Measured: a
    per-unit round() drifts -125 W over 50 000 ticks at three inverters.
  * THE ALLOCATION RECORD, with `unmet_w`, `dropped` and a per-unit reason.
    `ok` is one boolean for SAFETY-28 to gate on, and `unmet_w` is deliberately
    NOT fused into it - a saturated inverter must not park the whole site.

THE STABILITY PROPERTY IS STRUCTURAL. With sum(a_i) = 1 the gain at the meter is
sum(a_i * g_i), a convex combination of the per-unit gains, so it lies in
[min g_i, max g_i] FOR ANY SPLIT. That is what makes the weights a comfort
choice rather than a tuning parameter, and it is why a bad split cannot
destabilise the site. Graded directly, and measured end to end: 90/10, 50/50 and
100/0 give a bit-identical aggregate trace at the meter, and a gain sweep to 1.0
at every split has a flat tail at all 84 combinations.

THE TWO REFUSALS main.py NOW MAKES, AND WHY THERE ARE TWO. `allocated=False` no
longer means "no allocator"; it means no safe split EXISTS - a mis-routed claim,
an empty envelope set, or a split that could only be made by commanding one pack
to charge while another discharges. Separately, and this guard is the price of
making allocate() succeed rather than something inherited, main.py refuses to
act on a valid split it cannot DELIVER: there is one `setpoint_entity`, so
writing the site target to the one inverter it can reach would over-command that
inverter by exactly the other's share. Commanding a partial site is a worse
instruction than commanding nothing. DEV-02 gives it the second writer.

scope_violations() IS NOW CONSUMED, AND AS A REFUSAL. ARB-03 left it logging
without changing the resolution. A mis-routed claim means the number about to be
divided may itself be wrong, and dividing a number that may be wrong is worse
than not dividing it - the same answer clause 3 already gives a contradiction.
It is NOT promoted into an envelope: a unit-scoped claim that landed on the site
names no unit, so promoting it would mean guessing one, or applying one
inverter's rating to a sibling that does not have it.

AT N<=1 IT IS A PASS-THROUGH, BYTE-IDENTICAL: the share is the site target, as a
float, unrounded and unclamped. All 17 existing suites replay unedited.

test_peakguard.py part 10h and test_arbiter.py part 7 were RE-AIMED, not
deleted. PR #40's reviewer proved that refusal branch was unreachable and
untested once; removing its trigger without giving it a new one would have
rebuilt the hole. Part 10h now drives three real cycles - a deliverable split, a
dead sibling, and every master stale - and grades all three.

KNOWN AND NOT CLOSED HERE: at a roster of two the loop's `actual_w` is one
inverter's power used as a site measurement, because the add-on binds a single
`inverter_power` sensor. That is the SENSING half of the same N=1 identity this
card removes from the COMMANDING half, and it makes the aggregate trace
split-dependent below gain 1.0. Measured with its counterfactual in test_alloc.py
part 8 and tools/alloc_sim.py --splits. It belongs to DEV-02.

Verified: all 18 suites green in the CI image. 16 mutations run through
tools/mutation_run.sh on a purged tree; 13 red, and the 3 survivors are recorded
in test_alloc.py part 12 with the reason each cannot be caught.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-02 10:42:33 +02:00
admin df88b323f5 Merge pull request 'ARB-03: restore Claim.actuator and make resolve() three-stage' (#40) from ARB-03 into release/1.0 2026-09-02 04:16:45 +02:00
glenn schrooyenandClaude Opus 5 38f6680639 ARB-03: pin all eight actuator call sites statically
checks / unit (pull_request) Successful in 3m45s
The independent review of PR #40 found AC 6 met at three of the eight claim
construction sites while the check claimed to cover the class - this
repository's named failure mode, a check observing something other than what
it claimed, reproduced inside the check written to prevent it.

WHAT WAS WRONG. Part 10g's only call-site check was a real two-inverter cycle.
That cycle is auto, P1-healthy, no maintenance procedure, no tripped sign
watchdog, the guard idle and arbitrage off, so it reaches `device`,
`supervised` and `loop` and nothing else - three of the eight direct appends in
`Controller.cycle()`. Its own check text nevertheless read "the line a
mis-typed `actuator_of(...)` at a call site goes red on", and the PR body's
mutation table presented it as covering the class. The reviewer proved the gap
on the shipped tree: `actuator_of("maintenance")` -> `actuator_of("peak")` at
the maintenance-shaping append left test_arbiter.py, test_peakguard.py and
test_arbitrage.py ALL GREEN, while at a roster of two it built a site loop of
-1500 W against the guard's site `lo` of 1500 W and the now-misrouted
charge-only `hi = 0` - `lo > hi`, arbiter clause 3, 0 W IN THE BILLED QUARTER,
SAFETY-25 §0a's fatal case from a one-word typo. The same mutation at the
`failsafe` append survived too. The runtime detector does fire -
`scope_violations()` names it - but it only logs; nothing graded it.

THE FIX, over machinery already present. Part 10f's AST scan already reads each
`claims.append(...)` in `Controller.cycle()`. All eight direct appends expose
their actuator statically as `actuator=self.actuator_of('<literal>')`, so 10g
now requires that literal to EQUAL the source the claim is filed under, read as
SOURCE TEXT rather than evaluated - `actuator_of("peak")` at the maintenance
append is the same VALUE at the shipped roster of one and a different string
here. That pins all eight routing sites, on the line the typo is written, in
every configuration and at every roster, exactly the way 10f pins the source
set. Two further lines keep the scan from going vacuous: every direct append
must be readable in that shape (a computed or hand-written actuator fails
there), and the ten appends must still account for 10f's eight sources.

The two INDIRECT appends carry no `actuator=` at the call site to mis-type.
`peak_claim` and `arb_claim` are routed where their claim is built, and are
pinned there - `peakguard.claim()` by the SWEEP_SITE sweep over every load x
elapsed x battery x SoC x floor combination, `arbitrage.claim()` by
test_arbitrage.py. 10g now says so at the line, and says which three of the
eight its dynamic cycle actually sees, rather than rounding up.

MEASURED, NOT ARGUED. Each of the eight direct appends mutated in turn to a
wrong actuator - device->loop, supervised->peak, failsafe->safety,
safety(stopped)->device, safety(inputs missing)->maintenance,
maintenance(SET)->loop, maintenance(shaping)->peak, loop->supervised - each on
a purged tree via tools/mutation_run.sh over all 17 files. All eight RED, every
one of them on the new line.

TWO SURVIVING MUTATIONS OF THE SAME CLASS, ALSO CLOSED.

* `resolve()` did not have to honour the roster it was given: `if units is
  None:` -> `if True:` left the whole suite green. Ignoring the argument makes a
  unit that filed nothing this cycle cease to exist - a site of two reads as a
  site of one and stage 3 passes the whole grid target through to the inverter
  that spoke, which is ARCH-01's fault with its own evidence removed.
  test_arbiter.py part 7 now grades it on the one case that separates the two, a
  SILENT unit. Mutation RED in test_arbiter.py and test_peakguard.py.
* main.py's N>=2 refusal was unreachable and ungraded: `if not
  resolution.allocated:` -> `if False:` left the whole suite green, so the right
  instinct was one refactor away from being deleted as dead code. The guard is
  KEPT - the alternative default is the ARCH-01 fault - and new part 10h grades
  it on the two-inverter cycle that already existed: the 0 W, the `failsafe`
  winner, the log line naming the roster size, and the write that follows.
  Mutation RED.

AND THE WORDING CORRECTED. main.py does not "refuse to write" on
`allocated=False`. It SUBSTITUTES a 0 W failsafe and then calls
`write_setpoint(0.0)` like any other cycle. 0 W is the correct
fail-toward-inaction direction and the log text is accurate about what it
refuses - to BROADCAST the site target - but "refuses to write" overstates the
code. Said as what it does, in the CHANGELOG, at the branch in main.py, and in
10h's own check text. `resolve()`'s docstring now says the roster argument has
to be HONOURED, which is not the same as existing.

17/17 green on a purged tree.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-02 03:46:40 +02:00
adminandClaude Opus 5 06f95e0a64 ARB-03: restore Claim.actuator and make resolve() three-stage
checks / unit (pull_request) Successful in 3m45s
specs.md:467 declares `actuator: str` as the FIRST field of `Claim`.
app/arbiter.py:55 had no such field. The specification designed
per-actuator claims and the implementation dropped it, so every claim was
implicitly about "the one and only actuator", resolve() returned one scalar
Resolution.target_w, and main.py assigned it to one self.target. THERE WAS
NO SEAM AN ALLOCATOR COULD OCCUPY - and ARCH-01 (specs.md §6.2, 2026-09-02)
decided the site grid target is ALLOCATED across several inverters and never
broadcast. This is a regression fix against the written design; creating that
seam is the whole of the change.

WHY IT MATTERS, IN THE UNITS THE SYSTEM IS BILLED IN. The control primitive
is meter emulation: the master reports a fabricated grid reading and the
inverter regulates itself to it, so one number means "the battery moves X W"
to the add-on and "the grid is at X W" to the inverter - an identity that
holds only at N=1. Broadcast one target to two inverters and each supplies it
in full; the loop gain at the meter becomes N times the per-unit gain, which
at the gain config.yaml:374 accepts is a permanent limit cycle with every
watchdog in §11.2 reporting healthy. And a per-inverter reserve filed as a
site `hi` against the peak guard's site `lo` is `lo > hi`, arbiter clause 3,
0 W IN THE BILLED QUARTER - the parked battery SAFETY-25's memo calls fatal.

THE SPLIT, VERIFIED AT EACH CONSTRUCTION SITE RATHER THAN ACCEPTED FROM THE
SURVEY. Four sources are about the GRID CONNECTION and are SITE claims:
`loop` (compute() regulates grid_w, the P1 measurement, and §6.2's whole
architecture is one integrator on P1 whose output is then split), `peak` (the
15-minute average offtake AT the grid connection, which is what the capacity
tariff bills - one quarter-hour peak per site, not one per pack),
`arbitrage` (buys and sells at the grid against a day-ahead price; the price
is a property of the connection and the energy crosses the meter) and
`safety` (both construction sites read: "stopped" is the operator switching
control off for the site, "inputs missing" is the site's own meter gone -
neither is about a pack, and both must stop every inverter).

Four are about a pack, a device or one write and are PER-INVERTER: `device`
(one inverter's own reported min/max - there is no site rating),
`supervised` (max_w caps what may be WRITTEN to one setpoint entity, §11.3,
so it is scoped like `device` for the same reason), `maintenance` (§12's
recalibration is a pack procedure - drain THIS pack, charge THIS pack,
recalibrate THIS pack's counter) and `failsafe`. `failsafe` is the entry that
needed the reading rather than the survey: SAFETY-02's EVIDENCE is site-wide
(it compares P1 against the standing command) but its CONCLUSION is
"the unit I am driving is pushing power the wrong way" and its remedy is to
park that unit. At N>=2 the same evidence cannot be attributed to a sibling
this controller never commanded, so a site-wide stop would park an inverter
this watchdog never graded. The reasoning for all eight is recorded AT THE
LINE, in arbiter.CLAIM_SCOPE and again at each claims.append in main.py.

WHAT WAS BUILT. resolve() is three stages, each a separate function so a test
can construct a case at any one of them:

  pre_resolve()  - one inverter's own claims -> that unit's interval. Clauses
                   1 and 2 transposed: the unit's own winning SET gates its
                   own limits. The SET's value travels BESIDE the interval,
                   not inside it - folding a -2500 W drain into
                   [-2500, -2500] would turn "clamped to max_w" into
                   "contradicts max_w", a different and wrong answer.
  site_resolve() - THE SHIPPED ARBITER, UNCHANGED. Same code, new name.
  allocate()     - THE SEAM, AND DELIBERATELY NOT AN ALLOCATOR. ALLOC-01
                   builds it. At N<=1 it passes the target through (§6.2's
                   identity). At N>=2 it DECLINES - no shares,
                   allocated=False - and main.py refuses to write rather than
                   broadcast, because the obvious placeholder (hand the target
                   to each) is the fault ARCH-01 was filed about and no guard
                   we have can tell it apart from the real thing.

THE CONTRADICTION IS NOT GUARDED AGAINST, IT CANNOT BE WRITTEN DOWN. The
partition is by `actuator` and it is a partition: a unit's `hi` and the site's
`lo` are never both terms of one `lo > hi` test. Constructed and swept - 40
filings (every per-inverter source x unit x bound, including a unit
contradicting ITSELF at lo 900 > hi 100) against a live site floor, and not
one moves the site target or raises a contradiction. A unit's own impossible
pair parks that unit and says so on its own bounds; it does not park the site.
That is SAFETY-25 §0c's table made mechanical.

AT N=1 THIS IS A PURE REFACTOR, AND THAT IS PROVEN RATHER THAN ASSERTED. With
one inverter the fabricated grid reading and the battery setpoint are the same
number, so the grid connection and the only unit ARE one actuator:
actuator_for() routes every source to the site, no claim is filed on a unit,
stage 2 sees the whole list and answers what the shipped arbiter answered.
All 17 suites replay UNEDITED above the ARB-03 sections and are green on the
same numbers; test_arbiter.py additionally runs 13 claim lists through both
resolve() and site_resolve() and compares target, winner, binder,
contradiction flag, the considered list and the operator line.

EVIDENCE, BY BREAKING EACH THING (tools/mutation_run.sh, purged tree):
  * Claim's dataclass default emptied            -> RED (test_arbiter)
    ...and it survived until the check was added: the two helpers pass their
    own default down, so the FIELD's default never ran. Now checked directly.
  * `peak` reclassified SCOPE_UNIT               -> RED (arbiter x4, peakguard x2)
  * `maintenance` reclassified SCOPE_SITE        -> RED (arbiter x4, peakguard)
  * the N=1 identity dropped in actuator_for()   -> RED (arbiter, peakguard
    incl. the maintenance/peak suppression checks, freeze) - which is the
    measurement that says splitting at N=1 would be a behaviour change
  * resolve() stops partitioning                 -> RED (arbiter x4)
  * allocate() broadcasts at N>=2                -> RED (arbiter x2)
  * stage 1 drops clause-2 gating                -> RED (arbiter)
  * a call site routes `device` through `loop`   -> RED (peakguard 10g)
  * SAFETY-25 Option B built as a ninth source   -> RED (peakguard 10f, both
    halves, plus 10g) - the tripwire still bites

SAFETY-24's asymmetry proof is re-run and holds: 0 negative floors over the
shipped sweep, `hi` still +inf on every claim the guard files, and it now also
asserts every one of them is on the SITE actuator - a floor bound to one
inverter's share would leave the site, the thing the capacity tariff meters,
with no floor at all.

test_peakguard.py part 10f is kept, not adapted around. `source` is still
Claim.set()'s first positional argument precisely so its AST scan keeps
reading it, which is why `actuator` is the LAST field of Claim and not the
first - moving `source` off position 0 would silently blind the tripwire that
guards SAFETY-25's deferred option. The one adaptation is `**kw` on its spy,
so main.py's roster passes through unread rather than being silently dropped.
New part 10g pins CLAIM_SCOPE to the same eight-source set and grades a REAL
two-inverter cycle, which is the only place a mis-typed actuator_of(...) at a
call site is observable - at N=1 every source legitimately routes to the site,
so a swap there is invisible by construction.

No config key, no option, no operator surface, no default moved. Inverter B
does not exist yet and nothing here measures it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BwRLw7eKYj2byVdwB6kbjU
2026-09-02 01:54:29 +02:00
32 changed files with 16635 additions and 395 deletions
+18 -1
View File
@@ -83,7 +83,24 @@ rejected.
⚠️ **If you are testing the failsafe by hand, note that stopping and starting the
add-on will not clear a trip.** That is the point of it; use the *Start / stop
control* button twice, or delete `sign_tripped` from `/data/state.json`.
control* button twice, or delete the trip from `/data/state.json`.
⚠️ **DEV-02 renamed that key. There is one `SignWatchdog` per inverter, so the
LIVE latch lives under `unit/<inverter>/sign_tripped`** —
`unit/inverter-a/sign_tripped` on a single-inverter site. **That is the one to
delete if you are clearing a trip by hand**; deleting the flat one alone clears
nothing.
⚠️ **The flat `sign_tripped` is still maintained, though — it is the ROLLBACK
VIEW, not a fossil.** It is written alongside the namespaced key on a trip and
cleared alongside it when you press *Start / stop control*, so an add-on you
**downgrade** past this version still finds the latch it should. It is also read
on **every** start, and the one disagreement it can produce is acted on: *the
flat key says tripped and no inverter came up latched* means the latch was
written by an older add-on while this install was rolled back — or the migration
lost it — and the controller **re-arms the latch and shouts in the log** rather
than coming up disarmed with a green banner. So if you edit `/data/state.json`
by hand, clear **both** spellings or the next start will put the trip back.
⚠️ `test_loop.py` takes about **95 seconds** (measured 93 s) and that is not a bug. It
drives the real control loop, which sleeps 1 s a tick, eight times over, to prove a
+701
View File
@@ -2,6 +2,707 @@
## Unreleased
**Every pack is recalibrated on its own schedule, and only one moves power at a
time (MAINT-05).** §12's monthly cycle drains a pack to empty and refills it to
true its coulomb counter. There was exactly one `Maintenance` state machine and
one un-namespaced history, so at two packs **only the first was ever
recalibrated** and the second's counter drifted forever — and nothing prevented
the cycle draining pack A while the loop or arbitrage charged pack B, which is
two power-moving phases on one grid connection pulling against each other.
* **ONE `Maintenance` PER ROSTER ENTRY**, each with its own schedule, phase and
history under `unit/<name>/...`. `store.migrate_maint_keys()` moves an
existing install's flat history into the first pack's namespace under
`migrate_unit_keys()`'s three rules — shared in code, not restated — with the
same read-back postcondition, and the flat keys are kept **live** as the
rollback view so a downgrade finds a current history rather than one dated
migration day.
* **ONE MAINTENANCE SLOT PER SITE.** At most one pack may be in a power-moving
phase (`drain`, `charge` **and** `hold` — `charge` is in the set because a
pack pulled full from the grid beside a pack exporting to empty is 4 kW
circulating with the meter at zero). The holder is **derived** from the packs'
own stored phases, not persisted, so a restart mid-drain re-derives it. When
several packs are due in the same hour the slot goes to the one that has gone
**longest without a completed cycle**; roster order breaks a numeric tie and
nothing else. Nothing preempts a cycle in flight.
* **THE DEFERRED PACK IS NOT STARVED AND IS NOT A FAULT.** A deferral does not
stamp `last_start_attempt` (that is the 90 min post-abort cooldown, inside a
60 min start hour), and does not move the phase, so neither the 12 h `drain`
nor the 36 h `charge` timeout — *"the battery is not following commands"* —
can be reached by waiting. It says WAITING, names the pack it waits for, and
recalibrates at the next start hour; a test drives the winner's whole cycle
and observes it start.
* **THE SCHEDULE IS NOT STAGGERED BY CONSTRUCTION.** The interlock defers and
the stagger is what comes out of it: one contested month separates two packs
by one cycle length and they stay separated. `DECISIONS/MAINT-05-per-pack-maintenance.md`
§3 carries the argument.
* **`validate.py` rule 6 now grades `maintenance_charge_w` against the WEAKEST
cap on the roster**, like rule 5. Its own comment said it would have to move
the day `maint_unit` stopped being `inverters[0]`; that day is this card. It
refuses configurations that used to start — a 3000 W charge beside a 2000 W
pack that is now recalibrated too — which is the `lo > hi` contradiction rule
6 exists to refuse, caught when the config is written. Identical at N=1.
* **AT A ROSTER OF ONE, NOTHING CHANGES**, and it is asserted rather than
assumed: the state file keeps the flat keys and gains none, the migration does
not run, the four cycle events are the shipped strings character for
character, and the status banner is the bare phase with no pack name.
* **THE MIGRATION IS GRADED AGAINST THE ROSTER, NOT AGAINST THE NAME IT WAS
HANDED** (fix round). `migrate_maint_keys()` takes the roster rather than a
pack count and `_verify_moves()` checks the namespace it wrote against the
names the machines actually read. A postcondition that reads back the
namespace it was given cannot detect being given the wrong one: handed
`inverter.UNIT_A` on a roster of `["garage", "shed"]`, the first version of
this card wrote all four keys under `unit/inverter-a/...`, read all four back
equal, reported **verified**, and stamped `maint_schema_version` — so both
packs came up believing they had never been recalibrated and the next start
skipped the migration too. That is now `misdirected`: not `ok`, the marker is
**not** written, and the next start re-runs and recovers (rule 1 makes the
re-run a no-op). `build_roster()` numbers a nameless roster entry
`inverter-1`, so `inverter-a` is not even the fallback for a declared roster.
Every two-pack fixture that could see this now names its first pack
`garage`; with them all called `inverter-a`, `self.inverters[0].name` and
`UNIT_A` were the same string and the swap left all 19 suites green.
* **AND THE REFUSAL NOW SURVIVES THE NEXT START** (second fix round). The fix
above graded only the keys it had just *written*, so it refused exactly once:
measured at Controller level over one persisted store, roster
`["garage", "shed"]`, with the call site still wrong on both starts —
construction 1 `ok=False misdirected=4 moved=4 kept=0 marker=<absent>`,
construction 2 `ok=True misdirected=0 moved=0 kept=4` and the marker
**stamped**. On the second start rule 1 finds the wrong keys already there and
routes all four to `kept`, so `moved` is empty and the roster loop grades
nothing — and start 3 skips the migration forever, *including after the call
site is fixed*. Loud-and-recoverable became silent-and-permanent after one
restart. `_verify_moves()` now grades `set(moved) | set(kept)`; both lists are
built from the same `unit` argument, so grading `kept` grades the same
namespace decision. `test_maintenance.py` part **9c** drives two starts with
the same wrong unit over one store — the shape nothing in the suite had, since
9b measured recovery along the path where the operator has *already* fixed the
call site.
* **AND THE MARKER GATE IS PINNED ON BOTH GUARDS.** `if rep.ok:` is
`not lost and not misdirected`, and the mutation `if rep.ok or rep.kept:`
stamped the marker on a migration that **lost a month of history** with all 19
suites green. Part **9d** is the fixture that separates the two guards: two
keys already namespaced (`kept` non-empty) and two whose write the store
drops (`lost` non-empty), `misdirected` empty throughout.
* ⚠️ **AND THE SAME MUTATION ONE FUNCTION UP WAS A SURVIVOR, FOUND HERE AND
CLOSED.** `migrate_unit_keys()` — SAFETY-02's **latch** migration — gates its
own marker on `rep.ok` too, and every check that reached that gate ran on a
store where nothing was namespaced yet, so `rep.kept` was empty in all of
them. `if rep.ok or rep.kept:` there stamps `schema_version` on a migration
that **dropped the latch**: the guard is off, the file still says
`sign_tripped: true`, and the next start skips the migration that would have
re-armed it. Measured a survivor of all 19 files; now red on
`test_inverter.py` part 10, which drops the `sign_tripped` write beside an
already-namespaced `sign_reason`. No source change — the shipped gate was
right; nothing could see it.
* ⚠️ **FOUND, RECORDED, NOT FIXED (SECOND ONE).** `migrate_unit_keys()` —
SAFETY-02's latch migration — has the identical hole and it costs a **guard**
rather than a history. It runs before `build_roster()` (each `Inverter`
restores its latch in its constructor), so it is handed the constant `UNIT_A`
and there is no roster to grade against. On a declared roster a pre-DEV-02
`sign_tripped: true` lands under `unit/inverter-a/sign_tripped`, which no unit
reads — and `_grade_store_migration()`, whose job is to re-arm exactly this,
is **defeated by the key the defect wrote**: its "is anything namespaced
latched" test is satisfied by the misdirected value itself. Fixing it means
naming the migration's target from the config before any `Inverter` exists,
which is `inverter.py` and SAFETY-02's semantics, with its own battery.
Measured and pinned as a running check (`test_maintenance.py` part 13), whose
assertions state the WRONG behaviour on purpose.
* ⚠️ **FOUND, RECORDED, NOT FIXED.** A maintenance drain **pins** its pack while
the loop's target is a **site** claim, so when the site target is below the
pin the only split asks the sibling to charge against the drain and
`allocator.plan()` refuses it — the site parks at 0 W and the pack's 12 h
timeout would eventually report *"drain stuck"* about a healthy battery.
Pre-existing on `release/1.0` at `2d025ee` with the unit names swapped; fixing
it means changing what the loop's target means while a unit is pinned, which
is loop and allocator territory. Pinned as a running check
(`test_maintenance.py` part 12) so it cannot be forgotten.
**At two inverters the sign watchdog stops comparing one unit against the whole
site meter, and becomes two checks instead of one (SAFETY-30).**
`disagrees(commanded_w, grid_w, ...)` compared the command **this controller put
on ONE actuator** against **what the whole site** is exchanging with the network.
At a roster of one those are two views of the same thing - §6.2's identity - and
that is what makes the check sound and what earned it the best record in the
safety table. At two they are not, and it fails **in both directions**: inverter
A commanded −1500 W while the meter reads +1500 W is evidence of nothing when
inverter B is discharging 3000 W exactly as told, and - worse - a unit genuinely
driving the wrong way is **MASKED** by a sibling that covers for it, because the
site figure nets. No threshold recovers that; the summation destroys the
evidence.
* **PER UNIT: each inverter's own share against its OWN measured power**
(`Inverter.batt`, holding register 0x0518, per-instance since DEV-02).
Conclusion: *the actuator I am driving is not doing what I told it* - evidence
about one device, so the remedy stays the per-unit `failsafe` SET that
`arbiter.CLAIM_SCOPE` has classified `SCOPE_UNIT` since it was written. That
entry read *"the evidence is site-wide and the remedy is not"*; after this card
the first half is simply true. Verified by making one unit reverse while its
sibling covers it at the meter: the shipped comparison is false on **0 of 14**
cycles while the new one convicts that unit on every one, and only that unit is
parked.
* **SITE: the SUM of the standing commands against the meter**, as a new
`sign_site` SET at `P_SAFETY` on the site actuator, latched under flat
`site_sign_tripped` / `site_sign_reason`. This is the fault the 2026-08-20
capture contains and **no per-unit check can see it**, because every inverter
is faithfully executing its share - what is wrong is the number they were
given. It stops every inverter and the banner names the site rather than an
inverter, so nobody is sent to swap the wrong box.
* **⚠️ Different questions from SAFETY-31, and the PR and the decision record
both say which.** `circulation.py` compares the units **against each other**
and catches two inverters pushing *through* each other, which nets to zero at
the meter and which no single command is evidence about. This compares each
unit against **its own command**. They overlap in exactly one scenario - a unit
reversing while its sibling pulls the other way - and `test_watchdog.py`
asserts on that fixture that both fire and what each concludes. It is also not
the saturation freeze: that is a magnitude test (`|command − measured| >
500 W`) that shapes the loop and fires on a merely saturated unit; this is a
direction test that latches and parks one.
* **⚠️ All four thresholds RE-DERIVED at two inverters - one carried with a
justification, one refused.** 1890 closed-loop runs in which nothing is faulty,
over the whole range `config.yaml` accepts for `gain` and `slew_w`, across load
reversals with write staggers and flapping loads, **run at both rosters so the
N=1 arm is the control.** `unit_sign_disagree_w: 250` is `saturation_w / 2`, so
the smallest divergence this can see is exactly the gap at which the control
law itself already says the inverter is not following; `unit_sign_disagree_s:
85` is 8.5× the worst legitimate opposition those runs produce (10.0 s), 2.8×
the firmware's own 30 s link veto and under half the site hold.
`site_sign_disagree_w: 300` is **carried** - its argument is the meter's noise
floor and the deadband, and the roster touches neither. **`site_sign_disagree_s`
is NOT: 180 s would have shipped a false trip.** The worst legitimate crossing
at 300 W is 110 s with one inverter and **215 s with two**, because the command
must travel a rail that is the roster sum at a `slew_w` that is not - reachable
at `gain: 0.05`, `slew_w: 50` and a 2.2 kW load reversal, all schema-legal.
325 s is 1.51× that, inside the 900 s billing quarter and inside every episode
of the fault day. See `DECISIONS/SAFETY-30-per-unit-sign.md`.
* **⚠️ At ONE inverter this changes nothing, and "nothing" is asserted rather
than assumed.** The two questions are the same sentence at a roster of one, so
only the detector that shipped is armed: same comparison against the meter,
same 300 W / 180 s, same reason string byte for byte, same namespaced latch and
flat rollback mirror, same `failsafe` claim, same banner, same single status
row - and the site detector's window is never so much as opened.
`unit_sign_disagree_*` and `site_sign_disagree_*` do nothing on a
one-inverter install.
* **The threshold WIRING is pinned, not just the threshold values.** Review
found that `arm(self.sign_cfg if one else self.unit_sign_cfg, ...)` could be
collapsed to `arm(self.sign_cfg, ...)` — arming every unit with the
meter-facing pair instead of the re-derived per-unit one — with all 19 test
files still green, because nothing at a roster of two read `sign_wd.cfg` and
the trips in the fixture happen under either pair. `test_watchdog.py` part 3
now asserts the pair and the instrument on **every** detector against
literals, and the fixture's three threshold pairs were made pairwise distinct
in both coordinates so that a hold delivered from the wrong pair cannot
compare equal to the right one. M14–M16 in
`DECISIONS/SAFETY-30-per-unit-sign.md` §5.
* **Known and recorded rather than fixed:** the site comparison is defeated by a
square-wave load whose half period is about one control cycle, which holds it
opposed for ~1000 s at *both* rosters. The N=1 control arm is what says this is
a property of comparing a lagged command against a meter and has nothing to do
with the second inverter, so it is not acted on here - it wants an alternation
test, not a number, and a card of its own.
**An operator can declare a second inverter, and the shape was measured against
the Supervisor rather than assumed (CFG-04).** DEV-02 made rating, SoC,
watchdogs, heartbeat and store keys per-instance, so the code no longer assumed
one inverter — but the options schema still described exactly one, and
`build_roster()` returned a list of length one and said so in its own docstring.
The roster could only ever be a roster of one. **Version bumped to 0.6.0,
because the Supervisor keys the built image by `version:` and a schema change
without a bump is a schema nobody reads.**
* **`inverters:` — a list of objects, defaulting to `[]`.** Empty is not
"unconfigured", it is **the single-inverter configuration**: the flat
`setpoint_entity` / `soc_entity` / `batt_entity` / `batt_invert` / `max_w`
keys describe the one unit exactly as they always did. An install that
upgrades reads identically — same entities, same rating, same behaviour, no
operator action, and the whole existing check suite runs against it unchanged.
* **⚠️ The shape was ESTABLISHED, not assumed, and the empty default is the
load-bearing part.** There was no list-of-objects anywhere in `config.yaml`
and `static_profile` carries its structure as a JSON string in a `str?`
precisely because a nested schema was doubted. So Supervisor **2026.08.0**'s
own `AppOptions` validator — the version this site runs — was run against this
repository's `config.yaml` out of the release image
(`tools/supervisor_shape_probe.py`, committed; the transcript and the
reasoning are in `DECISIONS/CFG-04-inverter-roster.md`). It accepts the list,
enforces per-entry types, refuses a missing `name` / `setpoint_entity` /
`max_w` **by name**, and renders the option in the UI as a repeatable section.
And the shipped `options:` block validates as it stands while the **same
block with only `inverters` removed** is answered with **`Missing option
'inverters' in root`** — one key varied, so the refusal is about that key —
which is every options blob written before this version, since the key did not
exist when they were written. `App.options` is
the shipped `options:` block deep-merged with the operator's stored one, so
`inverters: []` in `config.yaml` is the difference between an upgrade nobody
notices and an add-on that cannot start with a schema pinned to the version
that would fix it. That is `docs/deploy-rollback.md` §4's trap in the forward
direction, found before it was sprung rather than after.
* **Nothing is inherited by an entry that omits a key, and that is DEV-02
restated as a config rule.** `name`, `setpoint_entity` and `max_w` are
required of every entry; a missing `soc_entity` means *this unit has no SoC
sensor*, never *use the other one's*. A three-line fallback to the flat keys
would have rebuilt the sibling-grading defect DEV-02 spent a card removing, in
YAML. Defaults still live in exactly one place (CFG-03): there is no
per-entry default anywhere, because there is no optional per-entry number.
* **SAFETY-28's `actuator_writers()` refuses two inverters naming one
`setpoint_entity` — the first configuration in this add-on's life in which
that was expressible.** The census was already structural and case-folding, so
it needed no change; what it needed was a config that could express the
hazard, and now there is one. Its sibling refusal is new: a flat
`setpoint_entity` left set beside a declared roster names an actuator nothing
will write, and is refused rather than ignored.
* **⚠️ Two PERMISSIVE READERS in shipped code, found and fixed.** Both failed in
the direction that hides a defect. (1) `validate.py` rules 5 and 6 compared
`sign_disagree_w` and `maintenance_charge_w` against the **flat** `max_w`; at
a roster of two 2000 W units with `max_w: 5000` left over from a
single-inverter install, `sign_disagree_w: 3000` passed rule 5 while
SAFETY-02's watchdog could fire on **neither** unit — rule 5's own failure
mode, reached through rule 5. They now read the roster's caps
(`unit_caps()`), which at one inverter is `[max_w]` exactly. (2)
`run_control()` re-ran the device-rating check behind `if
self.o.get("setpoint_entity")` — the flat key, which a roster config leaves
blank — so on a two-inverter site **no** inverter's `max_w` was ever graded
against the device it is written to. `validate_unit_ranges()` grades each unit
against its own ESPHome and runs unconditionally.
* **⚠️ Three config.yaml READERS IN THE CHECKS took the first match on a
stripped line, and one of them was already known.** `test_peakguard.py`'s
`read_option()` and `_schema_bound()` and `test_inverter.py`'s
`read_schema_max()` threw indentation away, so the nested per-inverter
`max_w:` began outranking the flat one — **silently, and correctly**, because
the two bounds are the same `int(100,5000)` today. A reader that is right by
coincidence is the failure mode this project is named after. All three are
anchored at exactly two spaces now, the halves of the file disambiguate
`peak_cap_w` instead of first-match, and an ambiguous key raises rather than
picking one. `test_tariff.py`'s copy of the idiom went with them.
* **The audit is a check, not a promise.** `test_inverter.py` part 11 finds
every `config.yaml`-reading function in the suite — transitively, so a reader
that never names the file because it delegates is still found — **executes**
each one against a synthetic two-inverter `config.yaml` whose per-inverter
numbers differ from its flat ones, and fails if any returns the per-inverter
value. The table is not maintained by hand: the signature decides, so the
eleventh reader is named on its first run. `config.yaml` declares `inverters:`
**before** `max_w:` on purpose, and part 11 asserts that ordering, so the trap
stays baited rather than sorted out by an ordering nobody would maintain.
* **Ten mutations run and observed red** (`tools/mutation_run.sh`), listed in
`test_inverter.py` part 12 with the check that bites each. **Two survived the
first run and the checks were changed, not the table:** the inheritance check
had blank flat keys, so "inherited" and "not inherited" were the same empty
string; and the `run_control()` check asserted a **source line** was present,
which re-indenting it does not remove. The second is now driven through the
shipped `run_control()` under a deadline, because that mutation's real symptom
is a hang rather than a red.
**Circulating power - two inverters pushing against each other - becomes a
measured quantity, a bounded one, and an alarm that survives a restart
(SAFETY-31).** Inverter A charging at 3 kW while inverter B discharges at 3 kW
nets ~0 W at P1: the site reads idle while the packs are cycled through two
round-trip conversion losses continuously. **Every guard in this add-on is a
consumer of that net figure**, so none of them can see it - SAFETY-02's sign
watchdog gates on `abs(grid_w) > 300` and the gate never opens, and both the
peak guard and the capacity tariff bill grid exchange.
* **A site sensor, `Σ|Bᵢ| − |ΣBᵢ|`.** Zero when the units pull the same way,
`2 × min(|B_a|,|B_b|)` when they oppose. Published as
`sensor.goodwe_circulating_power` beside the grid figure, because *"grid 0 W,
circulating 6000 W"* is the whole phenomenon in two dashboard rows and no
arithmetic on the grid figure alone can produce the second one.
* **⚠️ Derived from MEASURED per-inverter power, never from the allocation
record, and that is the whole card.** ALLOC-01's sign-coherence gate
(`REFUSE_SIGN`, its AC 7) already refuses any allocation whose shares carry
two signs, so a record-derived sensor reads zero **by construction** and could
only ever confirm that the allocator agrees with itself. What this detects is
circulation **nobody commanded**: a unit ignoring or lagging its share, a
stale share still being executed, a maintenance or SAFETY-25 pin holding one
unit while the loop drives the other, or HW-01's power stage running its last
instruction for **6 h 25 m** with the comms dead and the allocation record
impeccable throughout. Verified by making one unit ignore its share on the
TEST-19 rig: the record stays `ok` with both shares at −1250 W - a
record-derived sensor reads **0 W** - while the shipped sensor reads
**2000 W**. `Inverter.batt` became per-instance in DEV-02; before that this
sensor could not have been written.
* **The trip stops the site, and the decision record says why that is an action
rather than theatre.** Sustained opposition files `Claim.set("circulation",
P_SAFETY, 0.0)` on the **site** actuator - every inverter to 0 W, latched.
HW-01 established that a wedged inverter cannot be commanded at all, so the
remedy is not aimed at it: a circulating loop needs **two** participants and
**one of them is this controller**, faithfully driving the listening sibling
into the one that stopped listening. Stopping halves the loop, and - the more
important half - **makes the residue visible at the meter**, where every
existing guard can finally see it. What it cannot do is stop the wedged unit;
the notification says so, and names the isolator as the last actuator.
* **The threshold and the window were measured, not chosen (AC 3).** 924
closed-loop runs on the TEST-19 two-master rig in which *nothing* is faulty,
swept over the whole range the schema accepts for `gain` and `slew_w`. Worst
**continuous** legitimate opposition by threshold: **505.0 s at 100 W, 40.0 s
at 250 W, 10.0 s at 300 W, 5.0 s at 400 W and above**. The knee is 400 W and
it is the schema floor. `circulation_w: 700` is 1.75× it, the headroom bought
for inverter B's ramp and lag being **placeholders until SPIKE-04 measures
them**. `circulation_hold_s: 75` clears three bounds - 15× the worst
legitimate episode (5.0 s), 2.5× the firmware's own `LINK_STALE_S` veto, and
12× inside the 900 s capacity-tariff quarter. **A momentary opposition while
one inverter slews through zero is legitimate** - the serialised write path
lands B's number up to a control cycle after A's - and the guard does not fire
on it, in any of the 924 runs.
* **The alarm survives a Home Assistant restart (SAFETY-34).**
`persistent_notification` is in memory, which is exactly how the 2026-09-02
outage went unseen for 6 h 25 m with the detector correct throughout. The
latch is persisted to `/data` as flat, site-level keys - flat because the
quantity is defined over the roster and is identically zero for any one unit,
so there is no inverter to attribute it to - and the notification is
**re-raised on the first cycle after every start**, through the same code path
as a fresh trip.
* **At one inverter the sensor is identically zero and nothing changes (AC 5).**
`|B| − |B| == 0` for every reading, including one nobody took; no claim is
ever filed, the arbitration is byte-identical, and the status page says *n/a*
rather than claiming to watch something that cannot happen.
* **Verified by breaking it.** 18 mutations against the sensor, the window, the
latch, the claim, the store, the alarm, the routing table and both config
copies - **all red**, each on a named check; one equivalent mutant argued
rather than claimed; and one genuine **survivor found and closed** (`publish()`
turning an unknown into a published `0 W`). `arbiter.CLAIM_SCOPE` gains its
ninth source and `test_peakguard.py`'s 10f/10g tripwires were updated
deliberately, as their own comments require. Full ledger in
`DECISIONS/SAFETY-31-circulating-power.md`.
**Every per-device value stops being a Controller scalar: rating, SoC, battery
power, watchdogs, heartbeat, write bookkeeping and store keys are now
per-instance (DEV-02).** `app/inverter.py` introduces an `Inverter` object that
owns its entities, its rating, its device range, its `SignWatchdog`, its
`last_write` and its `last_beat`, under **store keys namespaced by unit name**.
The Controller holds a list of them and keeps only what is genuinely site-level:
the P1 reading, the site integrator, and the tariff quarter.
* **What the scalars were silently asserting.** One `dev_min`/`dev_max` pair was
read from one `setpoint_entity`, so a second inverter's rating was **never
read at all** and its clamp, its freeze rail and the peak guard's
`achievable_w` were the first one's numbers. One `soc` fed the maintenance
FSM, SAFETY-24's pack floor and arbitrage's bounds. One `SignWatchdog` - whose
own docstring says *"one instance per actuator"* - latched under **flat** store
keys, so a trip caused by B latched A across restarts and one operator press
cleared both. One `last_beat` and one serialised `hass.call()` meant a hung
write to A ate B's 30 s layer-1 budget.
* **`actual_w` became SITE level while the readings became per-instance, and
those are opposite directions on purpose.** `compute()`'s anti-windup test is
`abs(prev_w - actual_w) > saturation_w` with `prev_w` the **site** target, so
feeding it one inverter's power compares a site number against a unit number,
trips the saturation freeze permanently and leaves a standing grid error.
Measured on `admin/goodwe`'s two-master rig, 2 kW load: with one unit's power
the aggregate trace at the meter is split-dependent by **510 W at `gain: 0.2`,
250 W at 0.4 and 50 W at 0.6**; with the site sum **every split is
bit-identical at every gain the schema accepts**. That was ALLOC-01's
disclosed finding, graded in `test_alloc.py` part 8 and now closed there.
* **The store migration is graded, not merely performed.** `sign_tripped` /
`sign_reason` move to `unit/<name>/...` once, verified by **reading back**
what was written, and the version marker is only set when nothing that carried
state was lost. The flat keys are left in the file so a rollback still finds
its latch. And `Controller.__init__` compares the pre-migration flat latch
against what unit A actually came up with: if the latch did not survive it is
**re-armed from the legacy value and shouted about**, because a latch that
silently fails to migrate is a disarmed safety guard on an install whose state
file says it is protected.
* **Heartbeats are independent, and the budget is derived.** Each inverter owns
its own deadline, the refreshes are dispatched **concurrently**, and each write
is bounded by `WRITE_BUDGET_S` (4 s). The inequality that fixes that number is
graded rather than asserted: `4 + heartbeat_s`'s schema maximum of `25 < 30`,
layer 1's `FIRMWARE_INGEST_VETO_S`. Verified by injecting a transport that
accepts and never answers: B's write reaches the wire while A is still
hanging, and the serialised shape it replaces is run beside it.
* **`live_units()` answers honestly.** A unit whose every write has been rejected
for a whole layer-1 window is not commandable; the allocator drops it, the
survivors carry its share, the action log names it, and the dropped unit is
commanded **0 W** rather than left standing on its last share. A roster entry
with **no** `setpoint_entity` is deliberately *not* handled there - that is a
configuration that cannot be delivered, and it reaches main.py's refusal
branch, which commands 0 W and names the inverter.
* **At N=1 nothing moves.** The removed scalars survive as read/write properties
of the sole inverter, so every existing replay in this repository runs
unmodified - and they **refuse at N>=2** rather than answering for the first
inverter, which is the tripwire on a consumer that was never made
per-instance. `test_inverter.py` is the new file (77 checks); `test_alloc.py`
part 8, `test_peakguard.py` 10g/10h, `test_watchdog.py` and `test_clamp.py`
were re-aimed rather than relaxed.
* **Inverter B still does not exist.** `build_roster()` returns exactly one
inverter, from the flat options, and is the one function CFG-04 changes. Every
two-unit figure above is architecture, not a measurement of a second device;
the second rating in the checks is marked as a hypothesis.
**The write path is gated on the allocation record, not on how many config keys
exist (SAFETY-28).** specs §1.5 makes *"any configuration in which two writers
can reach one actuator"* a non-goal. Until now that non-goal was enforced by
`len(validate.ACTUATOR_WRITE_KEYS) == 1` - there is exactly one option key, so a
second writer is not expressible in the schema. True, and a statement about **the
shape of the options schema rather than about the writes**: add a per-inverter
config (CFG-04) and there are two real writers with that length still 1, so the
check stays green while the property it protects is gone. `sim/inject.py`'s
`two_writers` scenario asserted on the same tuple and went green with it.
* **The enforcement moved onto the writes.** `write_setpoint()` now refuses any
value that is not in **this tick's** allocation record from ALLOC-01:
`Controller.write_refusal()` asks `Allocation.authorises()` whether the single
allocator placed exactly this number, for this unit, on this tick. A second
writer with arithmetic of its own cannot satisfy that - its number appears in
no record - so it has to file a `Claim` and go through `resolve()`, which is
the one allocator. "Exactly one allocator per shared resource" stops being a
convention and becomes something the write path checks.
* **A refusal is a refusal, not a log line.** The unauthorised value is replaced
with **0 W and written**. Returning instead would leave the inverter latched
on its last command with the ESP32 heartbeat still being fed - holding an
unauthorised setpoint quietly, which is the outcome the gate exists to prevent.
* **A stale record cannot be replayed.** Every record now carries the `tick` it
was made for, handed *in* by the caller so `allocator.plan()` stays the pure
function `test_alloc.py` part 10 grades. The counter advances **once per
resolution, not once per loop iteration**: a new allocation makes the previous
record stale immediately, while the "inputs missing, not yet stale" hold -
which returns before the allocator runs, so one dropped meter reading does not
zero the inverter - leaves the standing authorisation intact for the heartbeat.
An **unstamped** record authorises nothing; "I cannot say when I was made"
fails closed.
* **⚠️ 0 W IS AUTHORISED UNCONDITIONALLY, SO THE FAILSAFE CANNOT DEADLOCK BEHIND
THE GATE.** `write_setpoint()` is also how layer 2 commands zero, and every
path that does so - `cycle()`'s two refusal branches, `shutdown()`, the
operator's stop button - runs while the allocator has *refused*. A gate that
asked the allocator's permission to command zero would block the safety write
behind the very component whose failure the safety write answers. The
exemption is on the **value**, not on a `failsafe=True` flag a caller asserts,
and the argument is that the hazard §1.5 names is N-times loop gain from
*broadcast*: at `S = 0` the broadcast and the correct allocation coincide -
`a_i = 1` for every unit gives every unit 0 W, which is exactly its share - so
there is no over-command to make at zero. Driven end to end through the real
refusal branch in `test_clamp.py` part 7c.
* **`unmet_w` is still not `ok`.** The gate reads `ok` and the unit's share and
never `unmet_w`, because an allocation that could not place every watt is
still safe to write; fusing them would let one saturated inverter park the
whole site. Graded on a record with 3800 W unmet.
* **`ACTUATOR_WRITE_KEYS` is replaced by `actuator_writers()`**, which counts
**writers per actuator** rather than option keys, and finds them by walking
the options tree rather than by looking for a container name CFG-04 has not
chosen yet. Two inverters with two entities are accepted - that is what the
per-inverter roster is *for*; two declarations aimed at one entity are refused,
naming the actuator and every writer pointed at it. The tuple survives only as
the enumeration a census needs, and nothing asserts on its length any more.
* **What neither check observes, said out loud.** The census sees *configured*
writers, so a second write path added in **code** is invisible to it - exactly
as it was invisible to the tuple. That half is closed at runtime by the record
gate, which does not care what the options look like or who called the method.
* Verified by breaking it: seven mutations on a purged tree via
`tools/mutation_run.sh` - removing the gate, making the zero exit an amnesty,
dropping the tick comparison, deleting the census refusal, fusing `unmet_w`
into `ok`, freezing the tick on the live path, and moving the gate below the
clamp - each turn `test_clamp.py` or `test_validate.py` red.
**The site grid target is now ALLOCATED across N inverters, sum-invariant, and
never broadcast (ALLOC-01).** `ARB-03` left `allocate()` as a documented seam
that passed through at N<=1 and DECLINED at N>=2; this fills it. The new
`app/allocator.py` turns one site target `S` into per-inverter shares with one
invariant - **`sum(shares) + unmet_w == S`, in integer arithmetic** - and each
inverter is then told a function of **its own share**, never of the shared
measurement.
* **Why a broadcast is a fault and not merely an inefficiency.** The control
primitive is meter emulation: the master reports a *fabricated grid reading*
and the inverter regulates itself to it, so one number means "the battery
moves X W" here and "the grid is at X W" there - an identity that holds only
at N=1. Hand both inverters the same target and each supplies it in full, so
the loop gain at the meter becomes N times the per-unit gain. Measured on
`admin/goodwe`'s two-master rig (TEST-19): **-400 W export overshoot at
`gain: 0.6`, and at `gain: 1.0` - which `config.yaml` accepts as its
documented maximum - a permanent 4000 W peak-to-peak limit cycle with not one
guard firing.** The sign watchdog is evaluated on every cycle and never trips,
because the disagreement flips on alternate ticks and never holds its 180 s
window.
* **The stability property is structural, not tuned.** With `sum(a_i) = 1` the
gain at the meter is `sum(a_i * g_i)`, a **convex combination** of the
per-unit gains, so it lies in `[min g_i, max g_i]` **for any split**. That is
what makes the weights a comfort choice (SoC, thermals, wear) rather than a
tuning parameter, and it means a bad split cannot destabilise the site.
Graded directly in `test_alloc.py` part 9, and measured end-to-end: a 90/10,
a 50/50 and a 100/0 split produce a **bit-identical aggregate trace at the
meter**, and a gain sweep to 1.0 at every split shows a flat tail at all 84
combinations.
* **Rounding is a safety property here.** The register is 1 W, and a per-unit
`round()` biases the sum - measured at **-125 W over 50 000 ticks at three
inverters**. At 1-2 Hz that is a permanent standing error the site integrator
chases and never reaches. So the target is rounded **once**, at the top, and
the fractional parts are settled by **largest remainder** with a deterministic
tie-break; every sum below that line is integer arithmetic and cannot drift.
Verified over 250 000 randomised ticks: **0 sum failures, 0 envelope escapes**,
and the one rounding that is left - the single site-level `quantisation_w`,
never distributed into a per-unit bias - totals **-39.8 W over 137 964
allocations, i.e. -0.0003 W per tick.**
* **Each share is clipped to that unit's interval, and THE TWO ENDS OF THE
INTERVAL ARE APPLIED INDEPENDENTLY.** `UnitBounds()` defaults to
`(-inf, +inf)`, so a one-sided envelope is the ordinary case at N>=2 rather
than an edge. The first cut of this work folded both ends into one
`min(max(v, lo), hi)` and substituted `v` itself for a missing bound, which
reads as "an absent bound cannot bind" but is not what it does: with
`hi == inf` the expression collapses to `min(max(v, lo), v) == v`, so **a
missing ceiling silently discarded the floor.** `_clamp_int(0, 2142, inf)`
returned 0. The worked failure it caused: a unit with a 2000 W floor and no
ceiling, beside a symmetric unit, against a +1000 W site target, was allocated
**+500 W - a quarter of its own floor** - and the sign-coherence refusal that
the same case with a finite ceiling correctly raises was **suppressed** with
it. Fixed by clamping each end on its own, and `UnitPlan.explain()` can no
longer print a share as being inside an interval that excludes it: that line
now reads `OUTSIDE ... - ENVELOPE VIOLATED, DO NOT WRITE`.
* **The envelope is read per tick, never cached.** `plan()` is a pure function
of that tick's intervals and holds no state, because a unit's range moves for
reasons unrelated to the allocator - a stale link, a pack at its floor, a
device rating that failed to read.
* **A dead link is announced, not absorbed.** A unit whose master is stale is
dropped from the envelope set; the survivors carry its share, and the
allocation record names the unit and the reason so `main.py` logs it. A site
running at half its inverters and reporting nothing reads as healthy on every
dashboard.
* **Opposite directions are refused, not averaged.** One pack discharging while
another charges nets to exactly the right number at the meter, so no existing
guard can see it. A sign-coherence gate makes it inexpressible.
* **`scope_violations()` is now consumed, and it is consumed as a refusal.**
ARB-03 left it logging without changing the resolution. A mis-routed claim
means the number about to be divided may itself be wrong, and dividing a
number that may be wrong is worse than not dividing it - the same answer
clause 3 already gives a contradiction. It is *not* promoted into an envelope:
a unit-scoped claim that landed on the site names no unit, so promoting it
would mean guessing one.
* **At N<=1 it is a pass-through, byte-identical.** The share is the site
target, as a float, unrounded and unclamped. Every one of the existing suites
replays unedited and green.
* **`main.py` still refuses to act at N>=2, for a new and narrower reason.**
There is one `setpoint_entity`, so this controller can command one inverter; a
valid two-way split names an inverter it has no writer for, and commanding a
partial site is a worse instruction than commanding nothing. The old
"no allocator" refusal and its test (`test_peakguard.py` part 10h) were
**re-aimed, not deleted** - `allocated=False` is now reachable on a mis-routed
claim, an empty envelope set, or sign incoherence, and all three are graded on
real cycles.
* **And the replay that missed it was widened, so the fix is graded rather than
merely applied.** The 250 000-tick replay drew every envelope as
`B(-uniform(0, rating), uniform(0, rating))` - **finite on both ends and
containing zero, every time** - while the check it fed claimed "no share ever
leaves the envelope it was clamped into". The data could only exercise a
symmetric closed interval around zero, so it reported 0 escapes against a live
defect. The generator now draws from **every shape `UnitBounds` can express**:
half-open above, half-open below, intervals that exclude zero, and bare
`UnitBounds()`. Measured A/B against the defective clamp on the same seed and
the same 250 000 ticks: **the old generator sees 0 escapes, the new one sees
39 991.** Reverting the clamp fix under the widened generator takes
`test_alloc.py` red on four checks; re-applying it takes it green. The
collapse is now a row in part 12's mutation table.
* **Known and not closed here:** at a roster of two the loop's `actual_w` is one
inverter's power used as a site measurement, because the add-on binds a single
`inverter_power` sensor. That is the *sensing* half of the same N=1 identity
this card removes from the *commanding* half, and it makes the aggregate trace
split-dependent below `gain: 1.0`. Measured, with the counterfactual, in
`test_alloc.py` part 8 and `tools/alloc_sim.py --splits`. It belongs to
`DEV-02`.
**`Claim` carries the `actuator` specs.md always said it did, and `resolve()`
is three-stage (ARB-03).** `specs.md` §6.1 declares `actuator: str` as the first
field of `Claim`; the shipped `app/arbiter.py` had no such field, so every claim
was implicitly about "the one and only actuator", `resolve()` returned one
scalar, and `main.py` assigned it to one `self.target`. **There was no seam an
allocator could occupy** - and `ARCH-01` decided the site grid target is
ALLOCATED across several inverters and never broadcast. This is a regression fix
against the written design, and it creates that seam. **At N=1 it is a pure
refactor: every one of the 17 suites replays unedited and green, on the same
numbers.**
* **The split, verified at each construction site rather than assumed.** Four
sources are about the **grid connection** and are SITE claims - `loop`
(regulates `grid_w`, the P1 measurement), `peak` (the quarter-hour average
offtake the capacity tariff bills), `arbitrage` (buys and sells at the grid
against a day-ahead price) and `safety` (`stopped` is the site's switch,
`inputs missing` is the site's own meter). Four are about **a pack, a device
or one write** and are PER-INVERTER - `device` (one inverter's own reported
rating), `supervised` (`max_w` caps what may be WRITTEN to one setpoint
entity), `failsafe` (**site-wide evidence, per-unit remedy**: SAFETY-02 grades
the command THIS controller put on THIS actuator, and at N>=2 that evidence
cannot be pinned on a sibling nobody here commands) and `maintenance` (§12's
recalibration is a pack procedure). The reasoning is recorded **at the line**,
in `arbiter.CLAIM_SCOPE` and again at each `claims.append` in `main.py`.
* **Getting it wrong is the parked-battery bug, so it is routed rather than
written.** A per-inverter reserve filed as a site `hi` against the peak guard's
site `lo` is `lo > hi`, arbiter clause 3, **0 W in the billed quarter** -
SAFETY-25 §0a's fatal case. `actuator_for()` is the one routing point and it
**raises `KeyError` on an unclassified source** rather than defaulting to the
site, because defaulting to the site is the failure itself.
* **Three stages, each a function a test can construct a case at.**
`pre_resolve()` turns one inverter's own claims into that unit's interval;
`site_resolve()` turns the site claims into one grid target and **is the
shipped arbiter, unchanged**; `allocate()` is **the seam, and deliberately not
an allocator** - `ALLOC-01` builds it. With at most one unit it passes the
target through (§6.2's N=1 identity); with two or more **it declines, no
shares, `allocated=False`**, because the obvious placeholder - hand the target
to each - IS the fault `ARCH-01` was filed about. **What `main.py` then does
is SUBSTITUTE, not abstain**: it replaces the resolution with a 0 W `failsafe`,
logs "refusing to broadcast the site target", and writes that 0 W through
`write_setpoint()` like any other cycle. The refusal is to BROADCAST; the
write still happens, in the fail-toward-inaction direction. Graded end to end
on a real two-inverter cycle by new **part 10h** - the branch is unreachable
on the shipped roster, and replacing it with `if False:` had left all 17
suites green.
* **`resolve()` HONOURS the roster it is handed, and that is now graded too.**
Left `None` the roster is derived from the claims, which is the documented
default; passed explicitly it is used. Deriving it *always* - ignoring the
argument - makes a unit that filed nothing this cycle cease to exist, so a
site of two reads as a site of one and the seam passes the whole grid target
through to the inverter that spoke: `ARCH-01`'s fault with its own evidence
removed. `test_arbiter.py` part 7 grades it on the one case that separates the
two, a **silent unit**.
* **The contradiction is no longer guarded against, it CANNOT BE WRITTEN DOWN.**
The partition is by `actuator` and it is a partition: a unit's `hi` and the
site's `lo` are never both terms of one `lo > hi` test. Constructed and swept -
40 filings (every per-inverter source x unit x bound, a unit contradicting
ITSELF included) against a live site floor, and not one moves the site target
or raises a contradiction. A unit's own impossible pair parks that unit and
says so on its own bounds; it does not park the site. That is SAFETY-25 §0c's
table made mechanical.
* **At N=1 nothing splits, and that is §6.2's identity rather than the
classification being ignored.** With one inverter the fabricated grid reading
and the battery setpoint are the same number, so the grid connection and the
only unit ARE one actuator and every source routes to the site. **Measured:
dropping that identity - splitting at N=1 - takes `test_peakguard.py`,
`test_freeze.py` and part 10g red**, because the `failsafe` and `maintenance`
SET claims would stop competing for the winner, `explain()` would name a
different source and `loop_is_following()` reads that name.
* **SAFETY-24's floor asymmetry survives, and now has a second half.** The
combination sweep is re-run and still holds - no negative floor, `hi` still
`+inf` on every claim the guard files - and it now also asserts every one of
them is on the **site** actuator, because a floor bound to one inverter's share
would leave the site, the thing the capacity tariff meters, with no floor.
* **The part 10f tripwire is kept and widened, not adapted around.** Its static
AST scan and its dynamic SoC sweep are untouched in substance - `source` is
still `Claim.set()`'s first positional argument precisely so the scan keeps
reading it, which is why `actuator` is the LAST field of `Claim` and not the
first. Its spy gained `**kw` so the roster passes through unread rather than
being silently dropped. New **part 10g** pins `CLAIM_SCOPE` to the same
eight-source set, so a ninth source now goes red twice. Verified by breaking
it: building SAFETY-25's Option B as a ninth source still takes 10f red on the
line it is written.
* **And the CALL SITES are pinned statically, at all eight of them.** 10g's
first cut graded routing only through a **real two-inverter cycle** and called
that "the line a mis-typed `actuator_of(...)` at a call site goes red on".
**It was not.** That cycle reaches `device`, `supervised` and `loop` and
nothing else - three of the eight direct appends - so a mis-type at the other
five survived every suite in this repository. Proved on the shipped tree by PR
#40's reviewer: `actuator_of("maintenance")` -> `actuator_of("peak")` at the
maintenance-shaping append left `test_arbiter.py`, `test_peakguard.py` and
`test_arbitrage.py` all green while, at a roster of two, it built a site loop
of -1500 W against the guard's site `lo` of 1500 W and the now-misrouted
charge-only `hi = 0` - `lo > hi`, arbiter clause 3, **0 W in the billed
quarter**, SAFETY-25 §0a's fatal case from a one-word typo. That is this
repository's named failure mode - **a check observing something other than
what it claimed** - reproduced inside the check written to prevent it, so it
is closed the way 10f closes it: over the **same AST scan**. All eight direct
appends expose their actuator as a literal `actuator=self.actuator_of('...')`,
so the literal is required to EQUAL the source the claim is filed under - all
eight, on the line the typo is written, in every configuration and at every
roster, whether or not any fixture reaches the state that files them.
**Measured: each of the eight mutated to a wrong actuator in turn, each one
red.** The two INDIRECT appends (`peak_claim`, `arb_claim`) carry no
`actuator=` at the call site to mis-type, and are pinned where their routing
is actually chosen - `peakguard.claim()` by the `SWEEP_SITE` sweep,
`arbitrage.claim()` by `test_arbitrage.py`. 10g's dynamic cycle is kept and
now says which three of the eight it sees instead of claiming the class.
**SAFETY-25's open question is ANSWERED: the BMS cut-out is the DELIBERATE and
only backstop for demand-driven discharge, and a loop-side reserve floor is
DEFERRED to `ALLOC-01` rather than rejected (SAFETY-25).** Decided by the
@@ -0,0 +1,213 @@
# CFG-04 — how a second inverter is declared, and why that shape was measured
**Status: DECIDED 2026-09-04 — a list of objects, `inverters:`, with `[]` as
the shipped default.** The alternative on the table was the `static_profile`
precedent: a structured value carried as a JSON **string** in a `str?` option.
Both work. The list wins on three counts that were measured rather than argued,
and the empty default is not cosmetic — without it the upgrade breaks.
Filed with CFG-04. Card 6a99fdf9d381935eddce4467.
---
## 1. The question, and why it could not be answered from the documentation
`config.yaml` used `list(off|ha_dsmr|…)` for enums and `str?` for free text, and
**there was no list-of-objects anywhere in the file**. `static_profile`
(`options:` `""`, `schema:` `str?`) carries a whole tariff structure as one JSON
line, and its own comment says why: *"a JSON string rather than a nested schema,
deliberately … it survives config.yaml's flat options block"*. That comment is
evidence that a nested schema was **doubted**, not that it was tried.
So the question was not "is this expressible in YAML" but **"does the Supervisor
this site actually runs accept it"** — and the Supervisor pins the options schema
to the *installed* version (`docs/pickup.md`), so guessing wrong is not a
compile error, it is an operator whose add-on will not start after an update
(`docs/deploy-rollback.md` §4, in the forward direction).
## 2. How it was answered
`tools/supervisor_shape_probe.py`, committed beside this record, runs
**Supervisor's own `AppOptions` validator and its own `SCHEMA_APP_CONFIG`** out
of the release image — `ghcr.io/home-assistant/amd64-hassio-supervisor:2026.08.0`
— against **this repository's `config.yaml`**. 2026.08.0 is the version the live
install reports (`supervisor_version` in its own backup metadata, 2026-09-03,
alongside Home Assistant 2026.8.3).
Nothing was re-implemented: if the Supervisor changes its rules, the script
changes its answer. Nothing was touched, either — it reads the file and runs a
validator in a throwaway container. It does **not** talk to the live Supervisor
and does not POST options, because the schema conflict is the one thing you do
not want to discover on a running site.
### What it printed, 2026-09-04
⚠️ **This transcript was RE-RUN after review, against the same image tag, and
it is not the one this record first carried.** The first §B validated the
reconstructed live blob — a blob missing many required keys that have nothing
to do with this card — and quoted its refusal as evidence about `inverters`.
It never was: that refusal names whichever unrelated key the validator reaches
first, and it has printed `meter_freeze_s`, `p1_phase_export_entities` and
`sign_disagree_w` on three different runs. §B is now the isolated
counterfactual — the shipped `options:` block, and the same block with
`inverters` and nothing else removed — and it asserts on the KEY NAME in the
refusal. The mis-cited half is kept, relabelled, as §B2. See §4.
```
App 'GoodWe RS485 Controller' uses deprecated 'arch' values: ['armv7']
Option 'inverters' does not exist in the schema for GoodWe RS485 Controller (local_goodwe_controller)
== A. the whole config.yaml through SCHEMA_APP_CONFIG ==
PASS Supervisor accepts the add-on manifest, version 0.6.0
schema declares 66 keys; inverters -> [{"name": "str", "setpoint_entity": "str", "max_w": "int(100,5000)", "soc_entity": "str?", "batt_entity": "str?", "batt_invert": "bool?"}]
options ship inverters -> []
== B. THE LOAD-BEARING ONE: an options blob with no `inverters` key ==
PASS the shipped `options:` block validates AS IT STANDS - so anything refused on the next line is refused for the one key that was removed
PASS ...and the SAME block with ONLY `inverters` removed is REFUSED, BY NAME - which is every options blob written before 0.6.0, since the key did not exist when they were written
Missing option 'inverters' in root in GoodWe RS485 Controller (local_goodwe_controller)
== B2. AC3: a reconstructed pre-0.6.0 blob upgrades into this version ==
PASS the reconstructed raw blob is REFUSED - for an unrelated missing key, because the reconstruction is incomplete; see the refusal printed below and §B for the `inverters` measurement
Missing option 'sign_disagree_w' in root in GoodWe RS485 Controller (local_goodwe_controller)
PASS the same blob MERGED with these defaults - what App.options actually is
inverters=[] setpoint_entity='number.kelder_goodwe_master_stage1_goodwe_setpoint_w' max_w=5000
== C. AC2: a two-inverter blob an operator would POST ==
PASS two inverters
[{"name": "inverter-a", "setpoint_entity": "number.goodwe_a_setpoint_w", "soc_entity": "sensor.goodwe_a_soc", "batt_entity": "sensor.goodwe_a_battery_power", "max_w": 5000}, {"name": "inverter-b", "setpoint_entity": "number.goodwe_b_setpoint_w", "soc_entity": "sensor.goodwe_b_soc", "batt_entity": "s
== D. what the schema itself refuses, per entry ==
PASS an entry with no name is refused
Missing option 'name' in inverters in GoodWe RS485 Controller (local_goodwe_controller)
PASS an entry with no setpoint_entity is refused
Missing option 'setpoint_entity' in inverters in GoodWe RS485 Controller (local_goodwe_controller)
PASS an entry with no max_w is refused
Missing option 'max_w' in inverters in GoodWe RS485 Controller (local_goodwe_controller)
PASS an entry with max_w over the range is refused
value must be at most 5000.0
PASS a JSON STRING where the list belongs is refused
Invalid list for option 'inverters' in GoodWe RS485 Controller (local_goodwe_controller)
== E. the ROLLBACK direction, and the operator's UI ==
PASS a schema WITHOUT `inverters` drops the key with a warning rather than refusing - so a downgrade is not the §B trap in reverse
['arbitrage_enabled', 'arbitrage_soc_ceiling', 'arbitrage_soc_floor', 'auto_start', 'batt_entity', 'batt_invert']
PASS Supervisor's UI renderer turns it into a repeatable section rather than choking - an operator can add the second inverter in the Configuration tab, which the JSON-string alternative could not offer
[{"name": "inverters", "type": "schema", "optional": true, "multiple": true, "schema": [{"name": "name", "required": true, "type": "string"}, {"name": "setpoint_entity", "required": true, "type": "string"}, {"name": "max_w", "lengthMin": 100.0, "lengthMax": 5000.0, "required": true, "type": "integer
== all cases passed ==
```
*(`arch: armv7` deprecation is pre-existing and unrelated.)*
## 3. What that establishes, item by item
| Claim | Evidence |
|---|---|
| A list of objects is a legal `schema:` element | §A — the whole manifest passes `SCHEMA_APP_CONFIG`, whose `SCHEMA_ELEMENT` explicitly permits `[{str: Self}]` |
| Per-entry types are enforced | §D — `max_w: 9999` refused with *"value must be at most 5000.0"* |
| A missing required key is refused **by name** | §D — *"Missing option 'name' in inverters"* |
| A two-inverter blob validates | §C |
| The operator can edit it in the UI | §E — `UiOptions` renders `{"type": "schema", "multiple": true}` |
| The `inverters: []` default is what makes a pre-0.6.0 blob validate | §B — the shipped defaults **minus only that key** are refused with *"Missing option 'inverters' in root"*; unmodified they pass |
| A downgrade drops the key rather than refusing | §E — a schema without `inverters` **drops the key with a warning**; it is not the §B trap in reverse |
## 4. ⚠️ The one that decided the default: `inverters: []`
§B is the load-bearing measurement, and it is an **isolated counterfactual**:
exactly one key differs between its two runs. `supervisor/apps/options.py`'s
`_check_missing_options()` treats a nested list as **required** unless its
element is an optional scalar — a list whose element is a dict is never
optional. So the shipped `options:` block validates as it stands, and the same
block with **only** `inverters` removed is answered with:
```
Missing option 'inverters' in root in GoodWe RS485 Controller (local_goodwe_controller)
```
The live install's stored options have no such key, because it did not exist
when they were written. If `config.yaml` declared `inverters:` in `schema:` and
**not** in `options:`, then on update `App.test_update_schema()` would log *"new
schema is not compatible"* and the operator would be left with an add-on that
will not start — and the schema they would need to fix it with is pinned to the
version they cannot install.
What makes it safe is that `App.options` is
`deepmerge(config.yaml's options:, the operator's persisted options)`, so a
shipped `[]` fills the gap before validation ever runs. §B shows the halves that
carry the claim — the defaults **minus this one key refused, by this key's
name**, and the unmodified defaults **accepted** — and §B2 shows the merge doing
its job on a reconstructed pre-0.6.0 blob.
⚠️ **What §B2 does NOT show, and what this record used to claim it did.** §B2's
`LIVE` dict is an incomplete reconstruction: it carries the keys `HANDOVER.md`
and `docs/deploy-rollback.md` record and no others, so it is missing many
required keys unrelated to this card. Its RAW half is therefore refused for
whichever of *those* the validator reaches first — three separate runs have
printed `meter_freeze_s`, `p1_phase_export_entities` and `sign_disagree_w` —
and the earlier version of this section quoted that refusal as if it named
`inverters`. It never did. The string above was produced by §B, where the
`inverters` key is the only thing that varies.
The probe's assertion on that line is on the **key name in the refusal**, not on
"a refusal happened". With the weaker assertion §B would have gone on printing
PASS after someone deleted `inverters: []` from `config.yaml` — blind to the one
regression it is the committed evidence for. It is now checked both ways: with
the default deleted the probe prints `2 CASE(S) FAILED` and exits 1; restored,
it prints `all cases passed` and exits 0.
The merge strategy was checked too, because it is the other way this could have
gone wrong: `_OPTIONS_MERGER` is `type_strategies=[(dict, ["merge"])]` with an
`override` fallback, so **lists override rather than concatenate**. A shipped
one-element default plus an operator's two-element list would otherwise have
produced three entries — with inverter A declared twice, aimed at one actuator,
which is exactly the hazard SAFETY-28 refuses. `[]` makes that unreachable and
the override rule means even a non-empty default could not have grown a roster.
## 5. Why the list, and not the `str?` + JSON precedent
The JSON string works — §C of the earlier draft of this probe validated the same
roster as a `str?` — and if the list had failed it is what would have shipped.
It loses on three things:
1. **SAFETY-28's writer census stops working.** `actuator_writers()` walks the
options **tree** looking for `setpoint_entity` at any depth, and its own
docstring anticipates this card: *"Add CFG-04's per-inverter config — a list
of inverters, each with its own `setpoint_entity` — and there are two real
writers"*. Inside a JSON **string** those entities are invisible to it, so
the §1.5 two-writers guarantee would have had to be re-implemented against a
parsed copy — a second place for the census to be wrong.
2. **No per-field validation.** With `str?` the Supervisor sees one opaque
string: a typo'd rating, a missing name and a malformed entity id all arrive
at the add-on identically, and every error message has to be written here.
§D shows the Supervisor doing that work, in its own words, before the add-on
starts.
3. **No UI.** §E renders a repeatable section; a `str?` renders a text box into
which an operator hand-types JSON. `static_profile` accepts that cost because
§14 gives it exactly one key and its structure is a tariff document; a roster
is a list of devices an operator adds one at a time.
## 6. What is deliberately NOT in the shape
- **No per-entry defaults.** `name`, `setpoint_entity` and `max_w` are
**required**; the sensors are optional and their absence means *this unit has
no such sensor*, never *use the other one's*. CFG-03 keeps defaults in exactly
one place, and a per-entry default would be a second one — worse, it would be
a per-entry default whose value is another inverter's measurement, which is
the sibling-grading defect DEV-02 spent a card removing.
- **No `gain`, `slew_w`, `integrator_max_w` per entry.** §6.2 and ALLOC-01 are
ONE integrator on P1 above the split. `app/inverter.py`'s module docstring
carries that argument; the config must not make a second one expressible.
- **No `inverters` entry for the flat keys.** They ARE the single-inverter
shape. Declaring both is refused (rule 9e) rather than merged, because a
config that silently becomes a different config is worse than one that
refuses to load.
## 7. Revisit triggers
- **A Supervisor upgrade that changes `AppOptions`.** Re-run the probe with the
new version tag. The whole point of committing it is that this costs a minute.
- **SPIKE-04 measuring inverter B.** It supplies a real `max_w` for the second
entry. It does not change the shape.
- **A second `Maintenance` FSM.** `validate.py` rule 6 grades
`maintenance_charge_w` against the first entry of `unit_caps_indexed()`
because `Controller.maint_unit` is `inverters[0]`. When that stops being true, that line moves with it.
@@ -0,0 +1,388 @@
# MAINT-05 — one recalibration per pack, one at a time, and what the card left open
**Status: DECIDED 2026-09-04.** There is one `Maintenance` per roster entry,
each with its own schedule, phase and history. The site holds exactly **one
maintenance slot**: at most one pack may be in a power-moving phase, the slot is
derived from the packs' own stored phases rather than persisted separately, and
when several packs are due in the same hour it goes to the one that has gone
**longest without a completed cycle**. The schedule is **not** staggered by
construction — the interlock defers, and the stagger emerges from it.
**Fix round 2026-09-04.** The store migration is now graded against the
**roster** rather than against the unit name it was handed — see §2's
*"The read-back postcondition is graded against the ROSTER"* — and the same
hole in SAFETY-02's latch migration is recorded in §7.
Filed with MAINT-05. Card `6a9a9e8503872905f298d80a`.
---
## 0. What the card asked to be decided, and the answers
| the card's open question | the decision |
|---|---|
| §2 the arbitration | **one pack at a time; the other stays under the loop.** Nothing preempts a cycle in flight. |
| §2 who wins when several are due | **the longest-waiting pack**, `last_completed` oldest first, `inf` for never-recalibrated. Roster order breaks a numeric tie and nothing else. |
| §4 staggering | **not by construction.** The interlock defers the second pack; the stagger is what comes out of it. §3 below. |
| AC 7 rule 6's `maint_unit` comment | **no, the first entry's cap is no longer right.** It grades against the weakest cap on the roster now, like rule 5. §4 below. |
| the store layout at N=1 | **flat, unchanged.** The namespace appears the day the roster grows. §2 below. |
## 1. Why the slot is derived and not persisted
The holder is *"whichever pack's stored phase is not `idle`"* — a fact already on
disk, written by the packs themselves in the per-pack history this card
introduces. A `maint_slot_holder` key would be a **second opinion about the same
thing**, and the two would disagree the first time the add-on was killed between
writing the phase and writing the holder. Derived, a controller that comes back
up mid-drain reads the drain and re-derives the holder from it; there is no
recovery path to get wrong because there is no second fact.
`CHARGE` is in `POWER_MOVING` even though the control **loop** owns the setpoint
in that phase, and that is the decision most likely to be "simplified" later.
Pack A charging from the grid at 2000 W while pack B drains 2000 W to export is
4 kW going round in a circle with the meter reading zero and both packs
believing they are behaving — the circulating power [[SAFETY-31]] exists to
detect, arriving as something this module can simply not do. `HOLD` is in the
tuple for the other half of the sentence: it moves nothing, and it **owns the
actuator**, so a second cycle starting under it would still be two
recalibrations at once.
## 2. Why the store layout at a roster of one does not change
The maintenance keys are flat — `phase`, `phase_started`, `last_completed`,
`last_start_attempt` — on every install since the add-on shipped. At one pack
there is nothing for a namespace to distinguish that pack **from**: §6.2's
identity, the same one `arbiter.actuator_for()` leans on when it routes every
claim to the site actuator at N=1. So `Maintenance` is constructed with
`unit=None` there, reads and writes the flat keys directly, and
`migrate_maint_keys()` **returns without writing anything**. A one-inverter state
file comes out of this card byte-identical, which is AC 6 and which
`test_maintenance.py` part 10 asserts by driving a whole cycle and comparing the
key set.
### The migration has its own marker, and that is not tidiness
`SCHEMA_VERSION` / `schema_version` is DEV-02's, and it is **monotone**: every
install runs that migration exactly once. This one runs **only where the roster
has more than one pack**, so a single counter could not express *"migrated on
this site, deliberately not migrated on that one"* without lying to the next
version that reads it — a one-inverter store would have to be pinned at the old
number forever, and a genuine future v2 migration could then never be told apart
from a site that simply never grew. `maint_schema_version` answers one question
and answers it honestly.
The **three rules are shared in code**, not restated: `_move_flat_keys()` is
rule 1 (never overwrite an existing namespaced value) and rule 2 (the flat keys
stay in the file), `_verify_moves()` is the read-back postcondition, and the
marker is written last. A second transcription of a migration is a second
opinion about what "it landed" means.
### The read-back postcondition is graded against the ROSTER (fix round)
**A postcondition that reads back the namespace it was handed cannot detect
being handed the wrong one.** That sentence is the whole finding, and this card
shipped it broken.
`_verify_moves()` iterated `rep.moved` — the keys it had just written — and
asked whether each read back equal. On a store where the write lands, it always
does. So a migration handed a `unit` that is on no roster wrote four keys, read
four keys back, set `verified = True`, and the caller stamped
`maint_schema_version`. Every symptom of a clean migration, and an install's
whole maintenance history parked under a name nothing will ever look up. And
because the marker was stamped, **the next start skipped the migration too** —
which is precisely the state `store.py`'s header says must never happen: a
failed migration a later version treats as done.
Reproduced on the reviewer's roster, a house with a garage pack and a shed pack,
carrying a flat `last_completed` of 2026-08-07:
| | `unit` the migration was handed | key written | pack 0 reads back | due now? |
|---|---|---|---|---|
| correct | `self.inverters[0].name` = `garage` | `unit/garage/last_completed` | `2026-08-07` | **False** |
| wrong | `inverter.UNIT_A` = `inverter-a` | `unit/inverter-a/last_completed` | `None` | **True** |
`build_roster()` names a declared roster's entries **from the config**, and its
fallback for a nameless entry is a **positional** `inverter-1` — so `inverter-a`
is not the name of anything on a declared roster, not even by default.
**The remedy, and why this one.** `migrate_maint_keys()` now takes the **roster**
in place of an `n_units` count (the count was `len(self.inverters)` at the only
call site, so the roster carries it, and a count passed beside the names is a
second opinion about how many packs there are). `_verify_moves()` grades the
namespace it wrote against those names, and a unit that is not among them is
reported as `misdirected` — a **different** failure from `lost`:
* `lost` is *the store took the write and dropped it* — a storage fault, and it
has a harmless-default case (a write of `last_completed: None` loses nothing,
because "absent" and "never recalibrated" are the same statement).
* `misdirected` is *the store did exactly as it was told, by a caller that was
wrong*. There is no harmless-default version of it: a write nobody reads is
not information, whatever its value. So anything in it fails `ok` on its own.
And **`ok` gates the marker**, so a misdirected migration is not stamped and the
next start runs it again. The argument for it is asymmetric: a re-run is
recoverable — rule 1 makes it a no-op where keys did land, and rule 2 left the
flat keys in the file to recover *from* — while a silent skip is not recoverable
at all, because the store now claims the migration happened.
### ⚠️ THE PARAGRAPH ABOVE USED TO END HERE, AND AS IT STOOD IT WAS FALSE
**The refusal lasted exactly one start. The second start stamped the marker.**
That is a correction to what the first fix round wrote down, not a new
qualification of it, and it is recorded here because a decision document that
states a guarantee the code does not provide is worse than one that says
nothing.
`_verify_moves()` graded only `rep.moved`. Measured at Controller level over
**one persisted store**, roster `["garage", "shed"]`, flat `last_completed`
2026-08-07, with the call site still handing `inverter-a` on **both** starts:
```
construction 1: ok=False misdirected=4 moved=4 kept=0 marker=<absent> (withheld)
construction 2: ok=True misdirected=0 moved=0 kept=4 marker=1 (STAMPED)
history parked under unit/inverter-a/…; marker stamped after ONE restart.
```
On start 2 the same wrong call site finds the four keys it wrote already
present, so **rule 1** — never overwrite a namespaced value — routes every one
of them to `rep.kept`. `rep.moved` is empty, the roster-grading loop iterates
over nothing, `misdirected` is empty, `ok` is True, the marker is stamped, and
start 3 takes the `from_version >= MAINT_SCHEMA_VERSION` early return **forever
— including after the call site is fixed**. Loud-and-recoverable became
silent-and-permanent after one restart: exactly the state `store.py`'s header
says must never happen, reached by the fix written to prevent it.
**The remedy is one line**, and it is sound by construction rather than by
argument: grade `set(rep.moved) | set(rep.kept)`. Every entry in *both* lists is
a `unit_key(unit, legacy)` built from the **same** `unit` argument, so grading
`kept` grades the same namespace decision `moved` does. A correct call site's
`kept` entries are under a roster name and pass; a wrong one cannot launder its
namespace by having already written it. `migrate_unit_keys()` passes
`roster=None` and returns before the loop, so it is unaffected.
**Why the check missed it, which is the part worth keeping.** Part 9b's recovery
check was `migrate_maint_keys(_m5, ROSTER[0], ROSTER)` — the **corrected** name.
It measures recovery along the one path where the operator has *already fixed
the bug*. The real failure is a call site that is still wrong on the next start,
and nothing in the 19 files called `migrate_maint_keys()` twice with the **same
wrong** `unit`. The check was true, passed, and could not reach the failure its
sentence named — MUTATION.md's third defect, this time sitting inside the fix
written to close it. Part **9c** now drives two starts with the same wrong unit
over one store, asserts the marker is still withheld on the second, and asserts
the *shape* of the second report (`moved` empty, `kept` full) so it cannot
quietly revert to 9b's path.
### The marker gate is `rep.ok` and nothing weaker — both guards, each pinned
`if rep.ok:` is `not lost and not misdirected`, and until this round only the
`misdirected` half was reachable by a check that also had a non-empty `kept`.
The mutation
```
if rep.ok: -> if rep.ok or rep.kept:
```
stamps the marker on a migration that **lost a month of history** — defeating
the older, settled `lost` guard as well as the new one — and **all 19 suites
were green on it**. Part **9d** is the fixture that separates them: two keys
already namespaced (`kept` non-empty, so the mutant's `or` fires) and two keys
whose write the store drops (`lost` non-empty, so `ok` is False), with
`misdirected` empty throughout so the section cannot pass on the other guard by
accident. Measured differential on it: shipped → marker absent; mutant → marker
`1`, both reporting `ok=False lost=2 kept=2`.
**Why the fixtures had to change, and this is the part that got the card
rejected.** Nothing in the repository could see whether any of the above was
true, because `inverter.UNIT_A` **is** the string `"inverter-a"` and every
two-pack fixture in `test_maintenance.py` named its first roster entry
`inverter-a`. `self.inverters[0].name` and `UNIT_A` were therefore the same
value in every check that existed, and swapping one for the other at the call
site left **all 19 suites green**. MUTATION.md's third defect exactly — a check
whose *data* cannot reach the failure it names — and the fifth consecutive card
to carry it. Parts 9 and 11 now run on `["garage", "shed"]`, each behind a
**precondition check** asserting that the first name is not `UNIT_A`, so an edit
that makes them equal again goes red instead of making the claims vacuous.
### And the flat keys are kept LIVE, which is the half DEV-02 had to add later
Rule 2 originally said the flat keys are left in place and go stale. DEV-02
amended it, for the sign latch, to *"left in place is not enough"* — and the
same sentence holds for history. A fossil dated the day the second inverter was
declared would hand a rolled-back single-FSM add-on a `last_completed` months
old (it recalibrates a pack that does not need it) or a stale `phase` with a
`phase_started` old enough to abort on the 12 h timeout the moment it comes up.
So `UnitHistory` **mirrors the first pack's writes back onto the flat keys** for
as long as the roster has more than one entry. Only the first pack: the flat
spelling means `inverters[0]` on every install that has one, and a mirror from
pack B would overwrite pack A's rollback view with pack B's phase.
## 3. Staggering: the interlock defers, and the stagger is the residue
Two packs on one monthly schedule are due in the same hour every month. The
options were a stagger **by construction** — offset each pack's first cycle by
`interval_days / N` — or **deferral**. Deferral, for three reasons:
1. **A constructed stagger cannot remove the need for the interlock.** A forced
start, a commissioning cycle, an abort-and-retry, or a pack added mid-month
desynchronises any static offset immediately, so the interlock has to be
there anyway — and then the stagger is a second mechanism that must also be
correct, for a case the first one already handles.
2. **A deferral is observable and a stagger is not.** The deferred pack says, in
the action log and on the status page, that it is waiting, which pack it is
waiting for, and that it will run at the next start hour. A silent offset
moves an operator's configured start day and explains nothing.
3. **The stagger comes out of the deferral for free and then persists.** Pack A
completes on day 1 and is next due on day 29; pack B, deferred, completes on
day 2 and is next due on day 30. One contested month separates them by one
cycle length and they stay separated.
**Starvation was the risk and it is closed at two points.** A deferral does
**not** stamp `last_start_attempt` — that key is the post-abort cooldown, and at
90 minutes inside a 60-minute start hour, stamping it would lock the deferred
pack out of exactly the hour it is waiting for. And the winner is the
longest-waiting pack rather than the first in the roster, so a pack that keeps
aborting cannot monopolise the slot month after month while its sibling drifts —
which is this card's own defect wearing a different costume.
**The deferral must not read as a fault.** §12's 12 h and 36 h phase timeouts
mean *"the battery is not following commands"*. A deferred pack stays `IDLE`
with `phase_started` untouched, so no timeout is reachable by waiting, and the
line it logs says WAITING, names the pack it waits for and says it will run
next — none of which any failure path in `maintenance.py` says.
## 4. Rule 6 (the card calls it rule 8): the first entry's cap is no longer right
`validate.py`'s rule 6 comment said, in as many words, that
`maintenance_charge_w` was graded against `inverters[0]`'s cap because there was
exactly one `Maintenance` and it could only ever recalibrate the first pack —
and that taking `min()` would be an over-refusal, because it would refuse *"a
5000 W pack being recalibrated beside a 2000 W sibling the cycle never
touches"*. It closed: **"when `maint_unit` stops being `inverters[0]`, this line
moves with it."**
It has stopped. Every pack is recalibrated on its own schedule, so **the sibling
the cycle never touches does not exist** and the over-refusal argument has no
subject. The shaping claim is filed on whichever pack is charging, so the cap
that can contradict it is any cap on the roster and the one that contradicts it
first is the smallest.
**This refuses configurations that used to start**, and that is the point rather
than a side effect: `max_w` 5000 on pack A beside 2000 on pack B with
`maintenance_charge_w` 3000 was correct while only pack A was ever recalibrated,
and is now a cheap-window charge asking the arbiter for `hi = -3000` against a
supervised `lo = -2000` — `lo > hi`, arbiter clause 3, 0 W, on the pack nobody
was watching. Refused when it is **written**, which is rule 6's whole job. At a
roster of one `min()` over one cap is that cap: same comparison, same message,
same boundary.
## 5. The claim stays per-unit, and nothing here files a site claim
`arbiter.CLAIM_SCOPE` has classified `maintenance` as `SCOPE_UNIT` since it was
written. Two FSMs mean two claims on two actuators, which the allocator consumes
as per-unit intervals. [[ARCH-01]] is explicit that this must never become a
site claim, because per-inverter constraints filed site-wide are the
cross-inverter `lo > hi` contradiction at `arbiter.py:114`. The only line this
card changed there is **which** roster entry the claim is filed on: the one whose
state machine produced the result, rather than `inverters[0]`.
## 6. FOUND AND NOT FIXED: the site loop still contradicts a drain at N>=2
Measured while wiring this card, and **pre-existing on `release/1.0` at
`2d025ee`** — the same drain filed on `inverters[0]` produces the identical
refusal with the two unit names swapped.
The maintenance SET **pins** its pack. The loop's target is a **site** claim.
When the site target is *below* the pin — a 2000 W drain while the house imports
less than that, which is most of a night — the only split that sums to the site
target asks the sibling to **charge** while the maintained pack **discharges**,
and `allocator.plan()` refuses it by name as circulating power. The refusal is
correct and fails safe: the whole site goes to 0 W with an `ARBITER: REFUSED`
line in the action log.
**The consequence an operator would see is a misdiagnosis.** The pack is held at
0 W while its state machine believes it is draining, so after 12 h the DRAIN
timeout fires and reports *"drain stuck"* — §12's words for a battery that is not
following commands. The battery is fine; the site refused to allocate.
**Why it is not fixed here.** The fix is to change what the site loop's target
*means* while a unit is pinned — regulate the meter using only the unpinned
packs — which is loop and allocator territory and changes the integrator's
subject. MAINT-05 moves which pack is pinned and nothing else about it. It is
pinned as a running check (`test_maintenance.py` part 12) rather than left as a
comment, so it cannot be forgotten or quietly tuned away, and it wants a card of
its own.
## 7. FOUND AND NOT FIXED: `migrate_unit_keys()` has the same hole, and it is a LATCH
Found while fixing §2's instance. It is the same defect one module over and it
costs a **disarmed safety guard** rather than a lost history.
`Controller.__init__` calls `migrate_unit_keys(store, UNIT_A)` — a hardcoded
constant where the maintenance migration now passes the roster's own first name.
It **has** to run before `build_roster()`, because each `Inverter` restores its
sign latch in its constructor, so there is no roster to name yet and
`_verify_moves()` is passed `roster=None`. On a **declared** roster a pre-DEV-02
`sign_tripped: true` therefore lands under `unit/inverter-a/sign_tripped`, which
no unit on that site reads.
**And the guard that exists for exactly this is defeated by the key the defect
wrote.** `_grade_store_migration()` re-arms the latch when the flat key says
tripped and *nothing namespaced is latched*. The misdirected write **is**
namespaced and **is** latched, so `namespaced_latched` is `True`, the guard
returns, and no inverter on the roster comes up tripped — on an install whose
`/data/state.json` still reads `sign_tripped: true`. That is DEV-02's own
sentence for the worst case: the state file says protected, the banner is green,
and the controller resumes commanding into the fault that tripped it.
Measured, on the same `["garage", "shed"]` roster:
```
pre-DEV-02 flat latch + declared roster ['garage', 'shed'] ->
migrated 2 flat key(s): unit/inverter-a/sign_reason, unit/inverter-a/sign_tripped
latch keys in the store: ['sign_tripped', 'site_sign_tripped', 'unit/inverter-a/sign_tripped']
roster came up tripped: [('garage', False), ('shed', False)]
the same store on the FLAT config -> [('inverter-a', True)]
```
The last line is the counterfactual: on the flat shape, where `UNIT_A` really is
the roster's only name, the same store migrates and comes up latched. So this is
a defect of the **declared roster**, not of the migration as such.
**Why it is not fixed here.** The remedy is to name the migration's target from
the config before any `Inverter` exists, which means factoring `build_roster()`'s
naming rule out of `build_roster()` so there is still only **one** spelling of
it — `inverter.py` and SAFETY-02's latch semantics, with its own mutation battery
over `test_inverter.py` and `test_watchdog.py`. MAINT-05 moves the maintenance
history and nothing about the sign latch, and a silent expansion into a safety
latch is how a rejected PR becomes a broken one.
It is pinned as a running check (`test_maintenance.py` part 13) rather than left
as a comment. ⚠️ **Its assertions state the WRONG behaviour on purpose** — read
them as the specification of a defect; the card that fixes it should expect them
to go red and should replace them.
### And its MARKER GATE had the round-3 hole too — found here, closed here
Separate from the namespace hole above, and **fixed** rather than recorded,
because closing it cost one test fixture and no source change.
`migrate_unit_keys()` gates `schema_version` on `rep.ok` exactly as
`migrate_maint_keys()` gates its own marker, and every check that reached that
gate ran on a store where **nothing** was namespaced yet — so `rep.kept` was
empty in all of them and
```
if rep.ok: -> if rep.ok or rep.kept:
```
**survived all 19 files**. What it does is stamp the schema marker on a
migration that DROPPED THE LATCH: the guard is off, the state file still reads
`sign_tripped: true`, and because the store now says the migration finished, the
next start skips the one thing that would have re-armed it. DEV-02's own worst
case, filed under *done*.
`test_inverter.py` part 10 now drops the `sign_tripped` write **beside an
already-namespaced `sign_reason`** — `lost` non-empty *and* `kept` non-empty,
which is the one shape none of the existing fixtures had — and asserts the
marker is withheld, with the accepted-baseline counterfactual beside it (habit
7). The shipped gate was correct throughout; what changed is that a check can
now see it.
@@ -0,0 +1,474 @@
# SAFETY-30 — what the sign watchdog compares once there is more than one inverter, and the numbers it compares with
**Status: DECIDED 2026-09-04.** The one comparison becomes **two**, asked of the
evidence that can answer each: **each unit's standing command against that
unit's own measured power** (register 0x0518, per-instance since [[DEV-02]]),
and **the sum of the standing commands against the meter**. At a roster of one
nothing changes at all — the two questions are the same sentence there, and the
detector that ships is the only one armed.
This document records the argument for that split, the campaign the four numbers
were read off, **a number that was carried and a number that refused to be**, and
the mutation ledger. Filed with SAFETY-30, card `6a9a1828e844f22fabf7fe9c`.
---
## 0. The half that was already built, and the half this card is
[[DEV-02]] shipped the **per-instance** half and nothing here re-tests it: each
`Inverter` owns its own `SignWatchdog`, the latch is namespaced under
`unit/<name>/sign_tripped`, the flat pre-DEV-02 pair is maintained as a rollback
view, and a trip on B no longer latches A. `test_inverter.py` part 3 grades that.
What was left is **the comparison itself**, and it was one line:
```python
inv.sign_wd.evaluate(stood, self.grid, self.following, now) # every unit
```
`stood` is the command **this controller put on THIS actuator**. `self.grid` is
what the **whole site** is exchanging with the network. At one inverter those are
two views of one thing — §6.2's identity — which is what makes the check sound
and what earned its record. At two they are not, and it fails in **both**
directions:
| | what happens | why no threshold fixes it |
|---|---|---|
| **false trip** | A commanded −1500 W while the meter reads +1500 W, because B is discharging 3000 W exactly as told | the meter is answering for a unit A's command says nothing about |
| **missed fault** | B commanded +1500 W and **measured** at −1500 W, beside A at +1500 W — the meter sits where a healthy site leaves it | the summation **destroys** the evidence |
NOTES.md calls SAFETY-02 the highest-value check in the safety table: 93 %
agreement while healthy against 4 % during runaway, four observed episodes, zero
false positives. **That record was earned at N=1 on the site comparison.** The
first row above spends it; the second row is the guard being absent when it
matters.
## 1. The two questions, and the two remedies
> **PER UNIT** — this unit's standing command against **its own** measured power.
> Conclusion: *the actuator I am driving is not doing what I told it.* Evidence
> about one device, so the remedy is that device: the `failsafe` SET, which
> `arbiter.CLAIM_SCOPE` has classified `SCOPE_UNIT` since it was written.
>
> **SITE** — the **sum** of the standing commands against the meter. Conclusion:
> *the site as a whole is driving the wrong way* — an inverted gain, an
> integrator wound past the rail, a strategy on the wrong side of the meter.
> That is the 2026-08-20 fault day, it is a property of the **connection**, and
> the remedy is a new SITE SET, `sign_site`, that stops every inverter.
### Why `failsafe` stays per-unit and `sign_site` is new
`CLAIM_SCOPE`'s entry for `failsafe` used to read *"the evidence is site-wide and
the remedy is not"* — a site measurement attributed to one actuator on the
strength of the N=1 identity. After this card the first half of that sentence is
simply true: the evidence **is** per-unit. The site-wide half did not disappear;
it moved to a claim that is site-scoped for the reason `circulation` is, one
entry above it: **the offending number is the site target, which no single
inverter owns.** Parking one unit on it would leave the rest of the roster
pushing the same way with the guard satisfied.
### At N=1, exactly one detector is armed
`Controller._arm_sign_watchdogs()` is the only place the roster decides anything
here, and it is a pure function of `len(self.inverters)`:
* **one inverter** — the unit detector is armed against **the meter**, at the
shipped `sign_disagree_w` / `sign_disagree_s`. The site detector is
**constructed and never evaluated**. Same comparison, same thresholds, same
reason string byte for byte, same namespaced keys and flat mirror, same
`failsafe` claim, same banner, same single status row. `test_watchdog.py`
part 7 asserts each of those, including that the site detector's window was
never so much as opened.
* **two or more** — each unit against its own 0x0518 power under the per-unit
pair, and the site detector against the meter under the site pair.
Arming both at N=1 would be two latches and two banners for one fault, and a
false-positive record measured on **one** comparison spent twice.
## 2. What this is NOT — the two neighbours, named
Two guards that overlap without saying so is how a false-alarm generator gets
built, so both are written down.
### It is not [[SAFETY-31]]
| | **SAFETY-31 — `circulation.py`** | **SAFETY-30 — the per-unit half** |
|---|---|---|
| compares | the units **against each other**: `Σ\|Bᵢ\| − \|ΣBᵢ\|` over measured power | each unit against **its own command** |
| catches | two inverters pushing **through** each other; nets to zero at the meter | a unit **not doing what it was told**; that unit is faulty or wedged |
| attributes | nothing — the quantity is defined over the roster and is identically zero for one unit | **the unit**, by name, and parks it |
| scope | SITE claim, flat latch | UNIT claim, namespaced latch |
They genuinely overlap in **one** scenario — a unit reversing while its sibling
pulls the other way — and `test_watchdog.py` part 4 asserts exactly that, on the
same fixture, with both readings printed: circulating power is over its threshold
**and** SAFETY-30 names B. Neither is the other with a different threshold. Take
two units faithfully executing an allocation with two signs: circulating power is
the whole loop and every per-unit sign check reads perfect agreement. Take one
unit doing the opposite of its share while its sibling covers: this reads the
whole disagreement and circulating power can be zero.
### It is not the saturation freeze
`compute()`'s anti-windup test is `|prev_w − actual_w| > saturation_w` (500 W). It
concludes *the inverter cannot follow*, it fires on a merely **saturated** unit as
readily as on a reversed one, it **stops the integrator winding** — an ordinary
control action taken every day — and it neither latches nor parks anything.
This asks for **opposition**: a sign, on both sides of a threshold, held
continuously. A saturated-but-obedient unit cannot produce it. And the two meet
at a number rather than overlapping in a band nobody drew — see §3.
## 3. The numbers, and where they come from
Read off `admin/goodwe`'s `sim/` two-master rig (TEST-19), used **read-only** and
run container-free. Real and imported, never transcribed: the control law
(`control.compute`, `Tuning`), the allocator (`arbiter.allocate_record` →
`allocator.plan`), the sign predicate (`watchdog.disagrees`), the wire
(`frame_check.setpoint_atomic`, the firmware's own encoder), the plant
(`plantsim.Plant`), and the per-unit reading, taken from **holding register
0x0518** — the register the live `batt_entity` binds.
**1890 closed-loop runs in which NOTHING is faulty** — every unit executes the
share the allocator gave it — over **6 gains × 5 slews**, the whole range
`config.yaml` accepts for `gain` `float(0.05,1.0)` and `slew_w` `int(50,5000)`,
across both families of stimulus that can produce legitimate opposition:
* **1050 load reversals** — 7 sizes (±300 W … ±4000 W) × 5 write staggers, the
serialised write path landing unit B's number up to four cycles after A's;
* **840 flapping loads** — 7 periods (10 s … 600 s) × 4 amplitudes.
Every run is executed **twice**: once at a roster of two and once at a roster of
one on the same stimulus. **The N=1 arm is the control**, and it is the reason
this document can separate *"a property of the check that shipped"* from *"a
property of the second inverter"* instead of asserting one and hoping.
Supervised caps are the shipped `max_w` (2000 W per unit), so the site rail is
2000 W at N=1 and 4000 W at N=2 — `Controller.site_max_w`, the roster sum.
### Reproducing it
The harness is **not committed here**, for the reason SAFETY-31's was not: it
imports `plantsim` and `frame_check`, which live in the other repository and are
not present in CI. What it does is small enough to restate: build two
`plantsim.Inverter`s from `INVERTER_A` / `INVERTER_B`, close the loop with the
add-on's own `compute()` and `arbiter.allocate_record()`, put each share on its
own wire through `Inverter.command()`, advance `Site.settle()` one control cycle,
and record `(standing command, inv.reg(0x0518))` per unit and
`(Σ standing, site.grid)` for the site. Then, for each candidate threshold, the
**longest run of consecutive cycles** on which the shipped `disagrees()` is true —
not a count of true samples, because the watchdog's window is cleared by any
disagreeing sample. Point it at a checkout with `GOODWE_ADDON_REPO`.
⚠️ MUTATION.md's note applies: those harnesses write `__pycache__` into **both**
trees.
### A. PER-UNIT — a unit's standing command vs its own 0x0518 power, N=2
| threshold | worst continuous, reversals | worst continuous, flapping | runs crossing (of 1890) |
|---:|---:|---:|---:|
| 50 W | 25.0 s | 20.0 s | 962 |
| 100 W | 20.0 s | 15.0 s | 511 |
| 150 W | 15.0 s | 15.0 s | 379 |
| 200 W | 10.0 s | 15.0 s | 258 |
| **250 W** | **10.0 s** | **10.0 s** | **194** |
| 300 W | 10.0 s | 10.0 s | 124 |
| 500 W | 5.0 s | 5.0 s | 37 |
| 700 W | 5.0 s | 5.0 s | 16 |
| 1000 W | 0.0 s | 0.0 s | 0 |
Largest opposed magnitude anywhere in the 1890 runs: **875 W**.
**The curve is flat, and that is the finding that decided the shape of this
pair.** Unlike the site comparison — where the meter is driven by the LOAD and a
flapping load can hold it opposed for minutes — a unit's own power **chases its
own command** through a bounded ramp and a first-order lag, so the opposition can
only last as long as the crossing does. Dropping the threshold from 300 W to
50 W buys 15 s of extra transient and nothing else. **So the work is done by the
window, and the threshold is put where the control law already draws its line.**
#### `unit_sign_disagree_w: 250` — schema `int(50,5000)`
`saturation_w / 2`. The check gates on **both** sides being over `min_w`, and the
two are **opposed**, so the smallest command-versus-power gap it can ever see is
`2 × min_w`. At 250 W that is exactly the 500 W at which `compute()`'s own
anti-windup test already concludes the inverter is not following. **This watchdog
therefore cannot fire on a divergence the shipped control law itself calls
ordinary tracking**, and the two guards meet at a number.
Rejected: a threshold above the observed 875 W maximum, which would gate nothing
legitimate in — and would also be blind to a unit reversing a 900 W share.
#### `unit_sign_disagree_s: 85` — schema `int(30,1800)`
Three bounds, and the value clears all three.
* **lower, from the rig — 10.0 s.** Two control cycles, the worst continuous
legitimate opposition above 250 W across all 1890 runs. It is a reversing site
whose second write lands a cycle after the first, both units then slewing
through zero behind a 10 s lag. Nothing is wrong.
* **lower, from the firmware — 30 s (`inverter.LINK_STALE_S`).** A unit not
executing its share for less than the firmware's own veto window is a *link*
fault the add-on already answers by dropping the unit from the split. Firing
inside that window would raise a second, louder alarm about a state already
being handled — the SAFETY-15/SAFETY-19 failure exactly.
* **upper, from SAFETY-02 itself — 180 s, the site hold.** A unit that is not
doing what it was told must not be parked *later* than the site would be
parked for the same watts, and this conclusion needs nothing to net out: it is
complete on the first cycle it appears.
**85 s** is seventeen control cycles: **8.5× the worst legitimate episode**,
**2.8× the firmware veto**, and **under half** the site hold. Deliberately not
60, 75, 90, 120 or 180.
### B / C. SITE — Σ standing commands vs the meter, at BOTH rosters
**Load-reversal family** (1050 runs each), worst continuous legitimate opposition:
| threshold | **N=2** | **N=1 (control)** | ratio |
|---:|---:|---:|---:|
| 100 W | 335.0 s | 175.0 s | 1.91× |
| 200 W | 260.0 s | 120.0 s | 2.17× |
| **300 W** | **215.0 s** | **110.0 s** | **1.95×** |
| 500 W | 155.0 s | 90.0 s | 1.72× |
| 700 W | 130.0 s | 70.0 s | 1.86× |
| 1000 W | 85.0 s | 35.0 s | 2.43× |
**The second inverter roughly DOUBLES the worst legitimate crossing, and at the
shipped 300 W threshold it takes it from 110 s — comfortably inside the 180 s
hold — to 215 s, which is outside it.**
The mechanism is not mysterious and is worth stating because it predicts the
ratio: the transient the 180 s hold exists to reject is the loop crossing zero
after a load reversal, and the command has to travel the whole **site rail** at
`slew_w` per cycle. At N≥2 that rail is `Controller.site_max_w`, the roster sum,
while `slew_w` is unchanged. The worst case is the corner of the config space
where that takes longest — `gain: 0.05`, `slew_w: 50`, both **schema floors** —
against a ±2200 W load reversal, which is an oven and a heat pump.
#### `site_sign_disagree_w: 300` — CARRIED, and here is the justification
The argument behind 300 W is about **noise**: *"near zero the sign is noise, and
near zero is where a healthy loop LIVES"* — the deadband holds the command still
while the meter wanders either side of `target_grid_w`. `deadband_w` is 15 W and
there is one P1 whatever is behind it. **Nothing in that argument depends on the
roster**, and the campaign agrees: the fraction of samples gated in at 300 W is
within a few percent at both rosters. Carried, with a measurement behind the
carry rather than an assumption.
#### `site_sign_disagree_s: 325` — NOT carried, and that is the point of the card
180 s is **inside** the 215 s the two-inverter campaign measures, at a
configuration the schema accepts. Carrying it would have shipped a false trip on
the check with the best record in the safety table — which is the exact failure
this card was opened to prevent, arriving from the other direction.
**325 s** is 1.51× the measured worst. It is well inside the **900 s** quarter
that bills the capacity tariff, and it is inside **every** episode the fault day
contains: 2026-08-20's four clusters run 16, 30, 77 and 77 minutes, and its
opposed runs reach 1750 s. What it costs is stated rather than hidden — about two
and a half extra minutes of wrong-direction **site** power before the stop —
and it is bought to remove a false trip a legal configuration produces.
Deliberately not 300 or 360.
**Rejected alternative:** keep 180 s and raise the site threshold to 1000 W,
where the worst is 85 s. It gives a better margin and a faster stop, and it is
wrong: it would be raising a **noise** gate to reject a **transient**, which is
what the window is for, and it would leave the site check blind to a 900 W
whole-site reversal at a 4 kW site.
### A limitation this campaign found, which SAFETY-30 does not introduce and does not fix
The **flapping-load** family behaves completely differently for the SITE
comparison, and the control arm is what makes it interpretable:
| threshold | **N=2** | **N=1 (control)** |
|---:|---:|---:|
| 300 W | 980.0 s | 1000.0 s |
| 700 W | 975.0 s | 1000.0 s |
| 1000 W | 950.0 s | 1000.0 s |
A square wave whose half period is about one control cycle opposes the command on
**every** cycle: the command chases the previous half-cycle's meter while the
meter has already reversed. **No window inside the billing quarter survives it and
no threshold up to 1000 W does either — at EITHER roster.** The N=1 column is
this document's whole reason for existing: this is a property of comparing a
lagged command against a meter, and it has nothing to do with the second
inverter.
It is not acted on here, in order of weight: it is **identical at the roster this
add-on ships**, so acting on it would be changing a live safety path on evidence
that has nothing to do with this card; a ~6 kW square wave at 0.1 Hz sustained
for a quarter of an hour is not a house (the captured healthy day's longest
opposed run is **30 s**); and the fix is not a number — it wants the detector to
notice that the disagreement is **alternating**, which is a different check.
**It is a card, and this section is its evidence.**
### D. The fault arm — because a survey of healthy data is not a derivation
210 runs with inverter B executing the **negation** of its share throughout,
sibling faithful, meter left to net:
| threshold | longest run the per-unit check detects | runs the SITE check also sees |
|---:|---:|---:|
| 250 W | 890.0 s | 210 / 210 |
| 300 W | 890.0 s | 180 / 210 |
| 700 W | 885.0 s | 112 / 210 |
| 1000 W | 885.0 s | 60 / 210 |
| 1500 W | 880.0 s | 45 / 210 |
| 2000 W | 0.0 s | 39 / 210 |
At the shipped 250 W the fault is detected continuously for the whole run in
every one of the 210 — an 85 s hold has ten times the evidence it needs. The
right-hand column is the honest half: on a *reversing* stimulus the site
comparison often does see something too, because the reversal is large enough to
move the meter. **The case it cannot see is the steady one**, and that is the
fixture `test_watchdog.py` part 4 runs: the shipped comparison is false on
**0 of 14** cycles while the per-unit check convicts B on every one.
## 4. Inverter B does not exist
Every two-inverter figure in §3 was produced with **inverter A's ramp and lag
copied onto B** (`plantsim.INVERTER_B`, `measured=False`); its 3000 W rating,
where this repository's fixtures use one, is a **hypothesis marked as one**.
[[SPIKE-04]] measures the real ones and is the revisit trigger for all four
numbers — not a reason to move any of them now.
Which figures depend on it, stated so nobody has to work it out:
* **`unit_sign_disagree_s: 85`** — most. Its lower bound is the 10.0 s crossing,
which is a direct function of B's ramp and lag. A slower second unit lengthens
it; the 8.5× is what buys headroom for that.
* **`site_sign_disagree_s: 325`** — yes, but less directly. Its 215 s is
dominated by the **rail** and by `slew_w`, which are configuration, not
hardware; B's dynamics move it at the margin.
* **`unit_sign_disagree_w: 250`** — **no.** It is `saturation_w / 2`, read off
the add-on's own control law. The rig only confirms that nothing legitimate
sits over it for long.
* **`site_sign_disagree_w: 300`** — **no.** It is the meter's noise floor and the
deadband, neither of which is a property of any inverter.
## 5. Mutation ledger
Every run on a **freshly copied tree of its own, no `__pycache__`, mounted
`:ro`** into the CI image — the structural immunity MUTATION.md records. ⚠️ The
first battery used ONE shared directory rebuilt between mutations and reported a
**RED baseline**; a container mounted it mid-copy and read a missing
`config.yaml` as a failing check. That whole run was discarded: MUTATION.md's
rule is that a run which could have been racing is not a result, and a battery
whose baseline is not green establishes nothing. The harness now copies a
directory per mutation and **refuses to report anything if the baseline is not
green**.
Byte deltas measured, not estimated; the `+0 B` ones are marked, since a
size-preserving edit is what TEST-15 turned into a false survivor once already.
| # | file | mutation | Δ | result |
|---|---|---|---|---|
| M1 | `main.py` | the per-unit comparison put back to `self.grid` at every roster | −30 B | **RED** — `test_watchdog.py`. This is the card |
| M2 | `main.py` | the per-unit comparison forced to `inv.batt` at N=1 too | −31 B | **RED** — AC 8 |
| M3 | `main.py` | the site half never evaluated | −6 B | **RED** — AC 3 |
| **M4** | `main.py` | **the site half armed at N=1 as well** | **+0 B** | **SURVIVOR on the first battery — GAP CLOSED**, then RED. See below |
| M5 | `main.py` | the `sign_site` claim never filed | −6 B | **RED** — `test_watchdog.py`. ⚠️ `test_peakguard.py` stayed **GREEN**, correctly: 10f's AST scan pins which sources CAN be filed and the append is still written; whether it is REACHED is a dynamic question no fixture there gets to |
| M6 | `main.py` | the site latch not persisted to the store | −58 B | **RED** — the flat-keys and restart checks |
| M7 | `main.py` | the operator clear leaves the site latch set | −42 B | **RED** — the clear check |
| M8 | `watchdog.py` | `arm()` clears `disagree_since` | +35 B | **RED** — "re-armed on every one of 38 cycles still trips" |
| M9 | `watchdog.py` | the reason hard-codes "a meter reading" again | +1 B | **RED** — `test_watchdog.py`. `test_inverter.py` stayed **GREEN**; its part-3 row reads the noun off `sign_wd.against` rather than out of the reason string, so the two checks bite in different places |
| M10 | `watchdog.py` | `unit_sign_disagree_w` 250 → 300 | **+0 B** | **RED** — the `saturation_w / 2` pin and the CFG-03 pin |
| M11 | `watchdog.py` | `site_sign_disagree_s` 325 → 180, i.e. **the number carried** | **+0 B** | **RED** — the measured-215 s check and the CFG-03 pin |
| M12 | `arbiter.py` | `sign_site` scoped `SCOPE_UNIT` | **+0 B** | **RED** — `test_arbiter.py` **and** `test_peakguard.py` |
| M13 | `validate.py` | the `unit_sign_disagree_w` rule removed | −126 B | **RED** — `test_validate.py` |
| **M14** | `main.py` | **`arm()` handed `self.sign_cfg` at EVERY roster** — the WIRING, not the values | −31 B | **SURVIVOR at review — GAP CLOSED**, then RED. See below |
| M15 | `main.py` | per-unit `arm()` given the right `min_w` and the SHIPPED hold — a HOLD-ONLY mis-wire | +78 B | **RED** — the same wiring pin |
| M16 | `main.py` | per-unit `arm()` given the right `min_w` and the SITE hold — hold-only again, and behaviour-preserving | +83 B | **RED** — the wiring pin, and the ONLY red in `test_watchdog.py` |
### M4 is recorded as a survivor because it was one
The check it should have gone red on read:
```python
not _c1s.site_sign_wd.tripped and _c1s.site_sign_wd.disagree_since is None
```
Arming the site detector at a roster of one left that **green**, and the reason
is worth reading because the check looked airtight. In the N=1 fixture the unit
detector trips first at its 1 s hold and parks the inverter; the site's standing
command is then **0 W**, so the site predicate is false, its window is never
opened, and `disagree_since is None` is true *whether or not the detector was
evaluated at all*. **The assertion ran, the sentence was true, and the data
could not reach the failure it named** — MUTATION.md's third failure mode,
inside the check written to prevent it.
Replaced with a **call counter installed on the object** before the run: twelve
cycles, zero calls, printed. A counter can only be zero for one reason. The
mutation was re-run against it and is red; the run that found it was discarded
along with its tree, so this is a result and not an artefact.
### M14: the VALUES were pinned and the WIRING was not
M10 and M11 mutate the numbers in `watchdog.SIGN_OPTION_DEFAULTS` and both are
red through the config pins. Neither of them touches the line that DELIVERS
those numbers to a detector:
```python
inv.sign_wd.arm(self.sign_cfg if one else self.unit_sign_cfg,
AGAINST_METER if one else AGAINST_OWN_POWER)
```
Drop the conditional — `arm(self.sign_cfg, ...)` — and every unit is armed with
SAFETY-02's meter-facing pair instead of the re-derived per-unit one. At review
that left **all 19 files green**. `grep -rn "sign_wd.cfg" test_*.py` found
exactly one threshold assertion, and it is §7's N=1 arm — `(300.0, 1.0)` —
which the mutation PRESERVES. Nothing anywhere read `inv.sign_wd.cfg` at a
roster of two.
The behavioural checks in part 3 cannot close it and it is worth saying why: B
is reversed at ~2000 W and every hold in that fixture is short, so B trips under
either pair. **A fault big enough and long enough to trip under both thresholds
is evidence about neither.**
What the survivor costs in the field is the whole product of §3: at
`config.yaml`'s own defaults the per-unit check would run at `sign_disagree_s`
**180 s instead of 85 s** — 2.1× slower to park a reversed inverter — and its
gate would move from 250 W to 300 W, so a unit reversing a share between the two
becomes invisible, while `SIGN_OPTION_DEFAULTS`, `config.yaml` and §3 all go on
describing a pair the running code does not use. With CI green.
**Closed by a wiring pin in `test_watchdog.py` part 3**, on the real
two-inverter Controller: every `inv.sign_wd.cfg` equals the per-unit pair,
`site_sign_wd.cfg` equals the site pair, and each detector's `against` is its
own instrument — all graded **against literals**, since `== self.unit_sign_cfg`
cannot tell *the per-unit pair* from *whatever this Controller was handed*.
⚠️ **And the fixture had to be changed for that pin to mean anything.**
`_sign_site` set `unit_sign_disagree_s: 1` **and** `site_sign_disagree_s: 1`
**and** `sign_disagree_s: 1`, with two of the three magnitude gates at 300 W. A
bare equality there discriminates on `min_w` alone: a mis-wiring that delivered
the right magnitude with the wrong hold would compare EQUAL to the pair it was
supposed to have. That is this document's own §5 lesson and MUTATION.md's third
failure mode — a check comparing two things that happen to be equal cannot see
the difference it names — reappearing inside the fix for it. The three pairs are
now pairwise distinct **in both coordinates** (250 W / 1 s, 320 W / 2 s,
300 W / 3 s), a PRECONDITION check asserts that distinctness so a later edit
collapsing them goes red rather than quietly vacuous, and both pairs are
**printed**. M15 and M16 exist to show the hold half actually bites: right
magnitude, wrong hold, red both times — and M16, whose wrong hold still trips
inside the drive, is red on the wiring pin and on **nothing else** in that file.
## 6. What this card does NOT close
* **The flapping-load blind spot in the SITE comparison.** §3, at length. Present
identically at the shipped roster of one; wants an alternation test, not a
number; a card of its own.
* **A unit misbehaving while it is NOT loop-driven.** Gate 1 (`following`) is
kept for the per-unit comparison, deliberately: the whole no-false-positive
argument is built on it, and the saturation freeze already grades that window.
So between the start of a maintenance cycle and its end, a unit reversing
against its own command is the freeze's to notice. Widening it is a card with a
rig campaign behind it, not an edit.
* **A sign inversion downstream of this add-on** — in the firmware, on the wire,
or in a future driver. Unchanged: our view stays self-consistent and both
comparisons stay silent. That is the witness's problem and it always was.
* **A false-alarm interaction with SAFETY-31 that nobody has to think about.**
They overlap in one scenario and both fire in it. That is correct — they
conclude different things — but an operator will see two alarms for one event.
Whether the banner should say so in one sentence is a UI card.
@@ -0,0 +1,316 @@
# SAFETY-31 — what "acted on" means for circulating power, and what it cannot mean
**Status: DECIDED 2026-09-04.** The trip **stops the site**: a `SET 0 W` claim
at `P_SAFETY` on the **site** actuator, latched, persisted, and re-announced
after a restart. This document records why that is an action rather than
theatre, given that [[HW-01]] established a wedged inverter cannot be commanded
at all — and it records the numbers the threshold and the window were read off,
because "establish the window from the rig, do not pick a round number" is an
acceptance criterion and a number without its measurement is a guess.
Filed with SAFETY-31. Card `6a99e0022b6a6c8ca15dbe3e`.
---
## 0. The two halves, and which one this card built
Half of this card was already shipped, and it is not the half below.
| | **ALLOC-01, AC 7 — the COMMAND half** | **SAFETY-31 — the MEASUREMENT half** |
|---|---|---|
| what it is | `allocator.REFUSE_SIGN` | `circulation.circulating_w()` + `CirculationWatchdog` |
| what it sees | the shares the allocator is about to hand out | each inverter's **own measured power** (`Inverter.batt`, register 0x0518) |
| what it does | **refuses** the allocation, names both units, returns no shares | **stops the site**, latches, alarms durably |
| what it covers | circulating power the allocator would have **commanded** | circulating power **nobody commanded** |
| graded by | `test_alloc.py` part 6 | `test_watchdog.py`, the SAFETY-31 section |
**They are complements, not duplicates.** The gate refuses an allocation before
it is written and cannot see one millisecond past that. This card reads the
hardware and does not care what was written. Neither replaces the other, and
**a sensor built on the allocation record would collapse the second into the
first and detect nothing** — see §2.
## 1. What "acted on" means
> **The trip files `Claim.set("circulation", P_SAFETY, 0.0)` on the SITE
> actuator. Every inverter is commanded 0 W and held there until an operator
> starts control again.**
### The objection, which is correct
[[HW-01]] is on the record: on 2026-09-02 the comms subsystem failed and the
power stage went on executing its last instruction for **6 h 25 m**, through
every command this add-on sent it. If the cause of the circulation is a unit
that has stopped listening, **a command is not a remedy**, and shipping one as
though it were is theatre.
### The answer
**A circulating loop needs two participants.** In every cause on this card's
list — a unit ignoring its share, a unit lagging it, a stale share still being
executed, a maintenance or [[SAFETY-25]] pin holding one unit while the loop
drives the other, or HW-01's wedged power stage — **exactly one participant is
the unit that stopped listening, and the other one is this controller**,
faithfully commanding the sibling to a share computed to sum with a number the
wedged unit is not actually producing.
Stopping the commanding half does two things a notification cannot:
1. **It halves the loop.** The unit that *is* still listening stops being driven
into the one that is not. That is real energy and real cycles off a real
pack, and it needs no cooperation from the wedged unit to take effect.
2. **It makes the residue visible — and this is the more important half.**
Circulating power hides *because it nets to zero at the meter*. With this
controller's contribution removed, whatever the wedged unit is still doing
stops being cancelled and appears at P1 as a plain net flow, where
SAFETY-02's sign watchdog, the peak guard and the capacity tariff can all see
it. **The fault stops being invisible.**
Measured on the [[TEST-19]] rig, and this is the number that makes the case:
in the card's own scenario — A at −3000 W, B at +3000 W, house load 0 W — the
meter reads **+0 W** and the shipped `SignWatchdog`'s predicate is **false on
every one of 30 cycles**, because it gates on `abs(grid_w) > 300` and the gate
never opens.
### What it does not do, said plainly
**It does not stop the wedged inverter. Nothing this add-on can send will.** If
the loop persists at the meter after this trip, the remaining actuator is a
human at the isolator, and the notification says so in those words.
### Why the claim is SITE-scoped
`arbiter.CLAIM_SCOPE` classifies `circulation` as `SCOPE_SITE`, beside `loop`,
`peak`, `arbitrage` and `safety`. The neighbouring `failsafe` entry looks like
it and is not: SAFETY-02 has site-wide *evidence* and a per-unit *conclusion*,
because it compares the meter against the command **this controller put on one
actuator**.
Circulating power has no such conclusion available. It is
`Σ|Bᵢ| − |ΣBᵢ|` — defined over the whole roster, **identically zero for any one
unit** — and there is no fact of the matter about which of two opposing
inverters is the offender: *a unit ignoring its share* and *a sibling faithfully
executing a share computed to sum with it* produce **identical readings**.
Filing this per-unit would require inventing an attribution the measurement
cannot support, and would park one inverter while the other went on feeding the
loop — quite possibly parking the only one still listening.
The same argument is why the latch is **flat** in the store (`circ_tripped`,
`circ_reason`) and not namespaced like SAFETY-02's. One site, one latch.
## 2. Why the sensor is MEASURED, and why the cheap version is worthless
The obvious cheap version computes the same formula over `Allocation.shares`.
It would be simpler, would never be `None`, and would be **worth nothing**, for
two independent reasons:
1. **It cannot fire.** ALLOC-01's sign-coherence gate already refuses any
allocation whose shares carry two signs. A record-derived sensor is therefore
a sensor over a set that is **guaranteed sign-coherent**. It reads zero *by
construction*, forever.
2. **It is [[MUTATION.md]]'s third failure mode.** It could only ever confirm
that the allocator agrees with itself — a check whose data cannot reach the
failure it names.
Verified rather than argued. On the rig, with inverter B wedged on a stale
discharge while PV drives the site to charge:
```
S = -2500 W shares a = -1250 W b = -1250 W <- record: ok, ONE sign, sums to S
MEASURED A = -1250 W B = +1000 W <- hardware
sensor over the RECORD : 0 W
sensor over MEASURED power : 2000 W -> trips at 190 s
```
And the card's own headline scenario, driven on the same rig — A at −3000 W,
B at +3000 W, house load 0 W:
```
METER (P1) : +0 W <- the site looks IDLE
sensor over MEASURED power : 6000 W -> trips at 100 s
SAFETY-02 SignWatchdog : predicate false on 30 of 30 cycles
```
The same pair is asserted in `test_watchdog.py` **with the precondition written
as its own check and printed**, per MUTATION.md's rule, and mutation **M10**
(the property rewritten to read `self.allocation.shares`) takes it **red**.
## 3. The numbers, and where they come from
Both were read off a curve produced on `admin/goodwe`'s `sim/` two-master rig,
used read-only: the add-on's own `compute()`, its own `allocator.plan()` and its
own `circulating_w()`, driving `plantsim.Plant` through the firmware's own
encoder, with the sensor input taken from each unit's holding register 0x0518.
**924 closed-loop runs in which nothing is faulty** — every unit executes the
share it was given — over both families of stimulus that can produce legitimate
opposition (7 reversals × 5 write staggers, and 7 flap periods × 4 amplitudes),
each swept across the **whole range `config.yaml` accepts** for the two settings
that decide how fast the site can turn around: `gain` `float(0.05,1.0)` and
`slew_w` `int(50,5000)`.
### Reproducing it
The rig lives in `admin/goodwe` (`sim/`) and was used **read-only**; the harness
is not committed here because it imports that repo's `plantsim`/`frame_check`,
which are not present in this one or in CI. What it does is small enough to
restate: build `Site([Inverter.from_spec("A", INVERTER_A),
Inverter.from_spec("B", INVERTER_B)])`, close the loop with the add-on's own
`compute()` and `allocator.plan()`, put each share on its unit's wire through
`Inverter.command()` (which goes out through the firmware's real encoder), and
read the sensor from `inv.reg(0x0518)` — **the same register the live add-on's
`batt_entity` binds**, so the input is the one the shipped code gets. Point it
at a checkout with `GOODWE_ADDON_REPO`. ⚠️ MUTATION.md's note applies: those
harnesses write `__pycache__` into **both** trees, so purge both by hand before
grading a mutation through one.
Every figure below was re-run against the final shipped `CirculationConfig`
(`min_w=700`, `hold_s=75`) rather than against the draft values they were first
measured at.
### Worst CONTINUOUS legitimate opposition, by threshold
| threshold | worst continuous | runs that ever cross it |
|---:|---:|---:|
| 100 W | **505.0 s** | 281 / 924 |
| 200 W | 445.0 s | 174 / 924 |
| 250 W | 40.0 s | 132 / 924 |
| 300 W | 10.0 s | 115 / 924 |
| **400 W** | **5.0 s** | 74 / 924 |
| 700 W | 5.0 s | 33 / 924 |
| 1000 W | 5.0 s | 16 / 924 |
| 1700 W | 0.0 s | 0 / 924 |
****With the shipped `min_w=700 W` and `hold_s=75 s`, 0 of those 924 runs trip.**
The knee is at 400 W and it is sharp.** Below ~250 W a flapping load holds the
sensor above the threshold for *minutes* at a time, and no window shorter than
the 900 s billing quarter could tell that from a fault. At 400 W and above the
worst legitimate episode collapses to **5.0 s — one control cycle — and stays
there**. The worst peak on any legitimate run is **1700 W**.
That 5.0 s is the serialised write path doing exactly what it should: on a
reversing cycle inverter B's new number lands up to a whole control cycle after
A's, both then slew through zero at 800 W/s behind a 10 s lag, and **between the
two zero crossings they genuinely oppose**. Nothing is wrong. A guard that
tripped on it would be the fourth false-alarm generator of the week, and this
project's doctrine on crying wolf is explicit ([[SAFETY-15]], [[SAFETY-19]]).
### `circulation_w: 700` — schema floor `400`
`700` is **1.75× the measured knee**. The headroom is bought for one named
reason: **inverter B does not physically exist.** Its ramp and lag in the rig
are inverter A's, *copied*, carrying `measured=False`; [[SPIKE-04]] measures the
real ones. A slower or faster second unit moves the transient's shape, and the
margin above the knee is what absorbs that without re-opening this card.
**Revisit when SPIKE-04 lands, not before.**
The **schema floor is the knee itself**, 400 W, so a legally configured install
cannot land in the 445–505 s regime. What the threshold costs: a circulating
loop smaller than 350 W per unit is not reported, which is deliberate — at that
scale the round-trip loss is a few watts.
### `circulation_hold_s: 75` — schema range `30..900`
Three bounds, and the value clears all three:
* **lower, from the rig — 5.0 s.** The worst continuous legitimate opposition
above 700 W across all 924 runs.
* **lower, from the firmware — 30 s (`inverter.LINK_STALE_S`).** A unit still
executing a stale share for less than the firmware's own veto window is a
*link* fault, and the add-on already answers it: liveness drops the unit and
the survivors carry its share, with the record saying so. Firing inside that
window would raise a second, louder alarm about a state already being handled.
* **upper, from the bill — 900 s**, the quarter that sets the capacity tariff.
**75 s** is fifteen control cycles: **15× the worst legitimate episode**, **2.5×
the firmware veto**, and **12× inside the quarter**. It is deliberately not 60
or 120 — a round number here would be a guess wearing a measurement's clothes,
and a check in `test_watchdog.py` asserts it is none of the values a guess
lands on.
## 4. Why the window cannot be defeated the way SAFETY-02's was
`allocator.py` records the measurement that makes SAFETY-02 blind to the
broadcast fight: the sign disagreement **flips on alternate ticks**, so
`disagree_since` is cleared between every pair of them and the 180 s hold never
accumulates.
Circulating power cannot do that. It is a **magnitude**, non-negative by
construction, and a sustained loop holds it high on *every* cycle rather than
every other one. An oscillation that genuinely alternated between opposing and
agreeing is not a circulating loop and should not be reported as one — which is
exactly the flapping-load case in §3, and it is why the window clears.
## 5. SAFETY-34: the latch is not the alarm
`persistent_notification` is **in memory**. Home Assistant restarts and the card
is gone while the fault runs on — which is precisely how the 2026-09-02 outage
went unseen for **6 h 25 m with the detector correct throughout**.
So the durable half and the visible half are joined, and the join is
`Controller._circ_announced`: a **per-process** flag, deliberately *not*
persisted. The latch in `/data/state.json` says *"this site is tripped"*; the
flag says *"this process has put that in front of a human"*. A restart clears
the flag and keeps the latch, so **the notification is re-raised on the first
cycle after every start** — which is the first cycle after a Home Assistant
restart, because the add-on restarts with it.
**One code path serves both** the fresh trip and the restart, on purpose: two
paths would be two chances for the restart one to rot unnoticed, and the restart
one is the case nobody exercises by hand. Mutations **M13** (flag initialised
from the latch) and **M18** (the call removed) both take it red.
## 6. Mutation ledger
Every run on a **freshly copied tree with no `__pycache__`, mounted `:ro`** into
the CI image — the structural immunity MUTATION.md records for CI and for
SAFETY-25 — so no stale `.pyc` could exist to be read. Byte deltas recorded;
**three are `+0 B`, the risky delta, and are marked**.
| # | file | mutation | Δ | result |
|---|---|---|---|---|
| M1 | `circulation.py` | `sum(abs(v))` → `sum(v)` in the sensor | −5 B | **RED** — the 6000 W, 2000 W and three-unit checks |
| M2 | `circulation.py` | N≤1 returns `None` instead of `0.0` | +1 B | **RED** — AC 5's nine-reading sweep |
| M3 | `circulation.py` | a missing reading at N≥2 returns `0.0` | −1 B | **RED** — "health from an absence" |
| M4 | `circulation.py` | drop `max(0.0, ...)` | — | **EQUIVALENT, not run as a claim.** For a same-sign roster the two sums accumulate the same magnitudes in the same order and are bit-identical; 700 000 random rosters produced no negative. Argued at the line and in the check's own text. |
| M5 | `circulation.py` | threshold `<=` → `<` | −1 B | **RED** — "exactly 700 W forever does not trip" |
| M6 | `circulation.py` | window `<` → `<=` | +1 B | **RED** — "trips at 75 s, not before" |
| M7 | `circulation.py` | the window removed entirely | −85 B | **RED** — both slew-transient checks |
| M8 | `circulation.py` | `None` no longer clears the window | +34 B | **RED** — the stale-reading gap check |
| M9 | `circulation.py` | the latch removed | −123 B | **RED** — "restored as tripped stays tripped" |
| **M10** | `main.py` | **the sensor derived from `self.allocation.shares`** | +60 B | **RED** — AC 2's headline check. This is the card. |
| M11 | `main.py` | the `circulation` claim never filed | −235 B | **RED** — `test_watchdog.py` **and** `test_peakguard.py` 10f/10g |
| M12 | `main.py` | the latch not persisted to the store | −112 B | **RED** — all three durability checks |
| M13 | `main.py` | `_circ_announced` initialised from the latch | +21 B | **RED** — SAFETY-34's re-raise |
| M14 | `main.py` | the operator clear leaves `_circ_announced` set | −45 B | **RED** — "the next trip would raise nothing" |
| M15 | `arbiter.py` | `circulation` scoped `SCOPE_UNIT` | **+0 B** | **RED** — `test_arbiter.py` ×3 and `test_peakguard.py` ×3 |
| M16 | `config.yaml` | schema floor `400` → `100` | **+0 B** | **RED** — the measured-knee check |
| M17 | `circulation.py` | default `700` → `500` | **+0 B** | **RED** — the CFG-03 pin and the not-a-round-number check |
| M18 | `main.py` | `await self.check_circulating()` removed | −39 B | **RED** — all four notification checks |
| M19 | `main.py` | publish `round(x or 0.0)` instead of `None` | −68 B | **survivor on the first battery — GAP CLOSED**, then RED |
**M19 is recorded as a survivor because it was one.** The first battery found no
check grading what `publish()` does when a per-unit reading is missing, so
turning *"I do not know"* into *"0 W"* on the one surface an operator actually
watches went unnoticed — the sensor's own `None` rule, defeated one layer out.
A check was added and the mutation re-run; it is red now. The run that found it
was purged, so it is a result and not an artefact.
## 7. What this card does NOT close
* **Inverter B's ramp and lag are placeholders.** Every transient number in §3
was produced with inverter A's parameters copied onto B (`measured=False`).
SPIKE-04 measures the real ones and is the revisit trigger for the 1.75×
margin. **Do not present any figure here as a measurement of inverter B.**
* **A wedged inverter still cannot be stopped by this add-on.** §1 says so; the
notification says so; there is no software fix and this card does not pretend
to one.
* **A loop below ~350 W per unit is not reported.** Deliberate, §3.
* **The saturation freeze fires under a wedged unit and leaves a standing grid
error.** Observed on the rig while producing §2's numbers: with B wedged, the
loop's anti-windup test compares a site target against a measured site power
that cannot track it, freezes the integrator and leaves the meter parked at
−3750 W. Nothing alarms on that today — a freeze is an ordinary control action
by design. It is a real finding, it is **not** in scope here, and it wants a
card of its own.
+203 -4
View File
@@ -55,6 +55,82 @@ Use the ESP32's readings rather than the inverter's cloud or dongle sensors:
those serve cached values, and a stale reading here ends the maintenance charge
phase having charged nothing.
### More than one inverter (`inverters`)
The six keys above describe **one** inverter, and if that is your site there is
nothing to do here — `inverters` ships empty and empty means *"the flat keys
above describe the one inverter"*. **An install that upgrades into 0.6.0 reads
identically to before: same entities, same rating, same behaviour, no operator
action.**
To run two, declare them. Each entry names its own actuator, its own rating and
its own sensors:
```yaml
setpoint_entity: "" # ⚠️ must be cleared — see below
inverters:
- name: inverter-a
setpoint_entity: number.goodwe_a_setpoint_w
soc_entity: sensor.goodwe_a_soc
batt_entity: sensor.goodwe_a_battery_power
max_w: 5000
- name: inverter-b
setpoint_entity: number.goodwe_b_setpoint_w
soc_entity: sensor.goodwe_b_soc
batt_entity: sensor.goodwe_b_battery_power
max_w: 3000
```
| per-entry key | required | meaning |
|---|---|---|
| `name` | yes | Short identifier. It namespaces this unit's SAFETY-02 latch, heartbeat and write bookkeeping in the add-on's state file, so **two units may not share one** |
| `setpoint_entity` | yes | This inverter's own ESPHome `number.*_goodwe_setpoint_w` |
| `max_w` | yes | The supervised cap on what may be written to **this** inverter. The site's ceiling is the **sum** |
| `soc_entity` | | This pack's state of charge |
| `batt_entity` | | This unit's battery power, `+` = discharging |
| `batt_invert` | | Flip if needed |
⚠️ **Nothing is inherited.** An entry that leaves out `soc_entity` has **no SoC
sensor** — it does *not* fall back to the flat one. That is deliberate: every
per-device value became per-instance in 0.5.x precisely so that no inverter is
ever graded against a sibling's numbers, and a silent fallback would rebuild
that in YAML. `name`, `setpoint_entity` and `max_w` are required of every entry
for the same reason: there is no rating to borrow.
⚠️ **Clear the flat `setpoint_entity` when you declare a roster,** or the add-on
refuses to start and says so. It is the single-inverter form and it is not read
once a roster exists, so leaving it set means one of two things: it names an
entity an entry also names — two writers on one actuator, which specs §1.5 makes
a non-goal and the add-on refuses outright — or it names a different one, which
nothing would ever write, leaving a site running quietly smaller than its
configuration reads. `soc_entity`, `batt_entity`, `batt_invert` and `max_w`
cannot be blanked (the schema gives them no empty value); they are simply not
read, and the add-on writes one line into its action log at every start saying
so.
⚠️ **Two inverters naming the same `setpoint_entity` are refused,** whichever
keys they are declared under and whatever the capitalisation. Two independent
setpoints on one inverter is the arbitration problem this add-on exists not to
have.
⚠️ **Update the add-on first, then add the roster.** Home Assistant validates the
options you save against the schema of the version that is *installed*, so
`inverters` cannot be set before 0.6.0 is installed. The order is: update, then
configure.
⚠️ **Going the other way — downgrading with a roster configured — is recoverable
but NOT uneventful, and the add-on will not start until you refill a field.**
The *schema* side is fine: the older version's schema has no `inverters` key, so
it drops the key with a warning rather than refusing the whole blob (measured —
`DECISIONS/CFG-04-inverter-roster.md` §E). The *add-on* side is not. Rule 9(e)
requires the flat `setpoint_entity` be **cleared** when a roster is declared, so
a config that downgrades cleanly is by construction a config whose flat
actuator is blank — and the older version has nothing else to write to. It stops
at startup validation with a refusal naming `setpoint_entity`, which is loud and
in the log rather than silent, but it is an outage until someone puts the
single-inverter entity back in that field. **Before downgrading, write down the
`setpoint_entity` of the unit you want to keep running.**
### P1 meter ingestion
`meter_entity` above expects one signed sensor, which usually means a template
@@ -272,7 +348,7 @@ behind it would trip the firmware watchdog on a system that is working fine.
| option | default | meaning |
|---|---|---|
| `max_w` | 2000 | Hard limit on what may be commanded. Start low, raise after commissioning |
| `max_w` | 2000 | Hard limit on what may be commanded. Start low, raise after commissioning. **Not read when `inverters` is declared** — each entry carries its own, and the site ceiling is their sum |
| `gain` | 0.6 | Correction per cycle. **At the limit — do not raise** |
| `slew_w` | 1000 | Maximum change per cycle |
| `deadband_w` | 15 | Ignore errors smaller than this |
@@ -287,6 +363,10 @@ behind it would trip the firmware watchdog on a system that is working fine.
| `auto_start` | false | Start controlling on boot (only after commissioning) |
| `sign_disagree_w` | 300 | Both the command and the meter must exceed this before a sign difference counts. Must stay **below `max_w`** or the watchdog can never fire, and the add-on refuses to start |
| `sign_disagree_s` | 180 | How long they must stay opposed, continuously, before the failsafe trips |
| `unit_sign_disagree_w` | 250 | **Two or more inverters only.** Both a unit's own share and its own measured power must exceed this before their sign difference counts. It is `saturation_w / 2`, so the smallest divergence it can see is exactly the gap at which the loop already calls the inverter "not following". Must stay **below `max_w`** or it can never fire, and the add-on refuses to start |
| `unit_sign_disagree_s` | 85 | **Two or more inverters only.** How long one unit's command and its own power must stay opposed before that unit is parked |
| `site_sign_disagree_w` | 300 | **Two or more inverters only.** Threshold for the site-wide check - the sum of the commands against the meter. The same 300 W as `sign_disagree_w`, for the same reason: near zero the sign is noise |
| `site_sign_disagree_s` | 325 | **Two or more inverters only.** How long the site's total command and the meter must stay opposed before every inverter is parked. Longer than `sign_disagree_s` because the command has to cross zero over a rail that is the sum of the roster, at a `slew_w` that is not - measured at 110 s with one inverter and 215 s with two |
#### The sign-disagreement failsafe
@@ -298,6 +378,43 @@ there. The banner reads `FAILSAFE`, the commissioning list says which two
numbers disagreed and for how long, and the `Controller status` entity reports
`failsafe`.
#### ⚠️ At two or more inverters this is TWO checks, not one (SAFETY-30)
The paragraph above describes what a **one-inverter** install does, and it is
unchanged: there is one meter, one actuator, and comparing the command against
the meter is comparing a thing with a view of itself.
With a second inverter that stops being true. The meter answers for **both**
units, so a command put on one of them can be opposed to it with nothing wrong
(inverter A charging while inverter B discharges more), and - the worse
direction - a unit genuinely driving the wrong way can be **hidden**, because its
sibling's watts arrive at the meter and the sum looks healthy. So the check
splits in two, and they are different faults:
- **Per inverter** — that unit's own share against **its own measured power**
(the `batt_entity` reading, register 0x0518). This catches *"this inverter is
not doing what it was told"*. Only that inverter is parked; the site keeps
running on the one that works. Thresholds: `unit_sign_disagree_w` /
`unit_sign_disagree_s`.
- **Site-wide** — the **sum** of what every inverter has standing, against the
meter. This catches *"the site as a whole is pushing the wrong way"*, which no
per-inverter check can see because every unit may be faithfully executing its
share of a number that is itself wrong. **Every** inverter is parked and the
banner names the site rather than an inverter. Thresholds:
`site_sign_disagree_w` / `site_sign_disagree_s`, latched under flat
`site_sign_tripped` in `/data/state.json`.
Both latch, both are cleared by the same *stop, then start*, and both survive a
restart. **On a one-inverter install neither pair does anything at all** - the
two questions are the same question there, and only the check described above is
armed.
This is **not** the circulating-power alarm further down: that one compares the
inverters *against each other* and catches them pushing power through each other,
which nets to zero at the meter and which no command is evidence about. It is
also not the saturation freeze, which is a *magnitude* test that shapes the loop
rather than a *direction* test that parks an inverter.
**It does not clear itself, and restarting the add-on does not clear it either.**
Pressing *Start / stop control* twice — stop, then start — is the only thing that
does. That is deliberate on both counts:
@@ -306,7 +423,13 @@ does. That is deliberate on both counts:
always vanishes the instant the trip works. A watchdog that took that as proof
the fault was over would hand the inverter straight back to the loop that was
driving the wrong way, three minutes later, forever.
- The trip is written to `/data/state.json` and restored on startup. Restarting
- The trip is written to `/data/state.json` — under
`unit/<inverter>/sign_tripped`, one key per inverter since DEV-02, so a trip
caused by one inverter cannot latch another — and restored on startup. The
pre-DEV-02 flat `sign_tripped` is written and cleared alongside it as the
**rollback view**, so downgrading the add-on past DEV-02 still finds the
latch, and a trip taken while the install is rolled back is re-armed by the
version that comes back up rather than silently lost. Restarting
the add-on is the first thing most people try when they see a red banner, and
a latch that a restart clears would bring the controller back **armed, into the
same fault, unattended** — and under a Supervisor that restarts a crashed add-on
@@ -755,6 +878,82 @@ unchanged is 12 W, which is inside the 15 W deadband — so the command there is
parked at 0 W and the two halves of the rule cannot both be true. At the schema
floor of 60 s that figure is 60 W and only the margin is left.
### The circulating-power alarm (SAFETY-31)
> **Only at two or more inverters.** At the shipped roster of one this quantity
> is identically zero for every reading, no claim is ever filed, and the status
> page says *n/a* rather than pretending to watch it.
Two inverters can move a great deal of energy while the meter reads almost
nothing. Inverter A charging at 3 kW while inverter B discharges at 3 kW nets
**~0 W at P1**: the site looks idle, and in reality the packs are being cycled
through two round-trip conversion losses continuously, for no benefit.
**Nothing else in this add-on can see it, and that is structural rather than an
oversight.** Every other guard is a consumer of the *net* figure at the grid
connection — the sign-disagreement failsafe gates on `abs(grid_w) > 300 W` and
that gate never opens at a netted zero; the capacity-peak guard and the tariff
both bill grid exchange. Circulating power is precisely the component of
per-inverter power that the sum destroys.
So the add-on computes a quantity none of them were computing:
```
circulating_w = Σ|Bᵢ| − |ΣBᵢ|
```
Zero when the units pull the same way. `2 × min(|B_a|, |B_b|)` when they oppose
— twice the power going round the loop, which is what both conversion stages are
processing between them. It is published as
`sensor.goodwe_circulating_power`, deliberately **beside** the grid figure:
*"grid 0 W, circulating 6000 W"* is the whole fault in two dashboard rows, and
no arithmetic on the grid figure alone can produce the second one.
**It is derived from each inverter's own measured power, not from what the
controller believed it commanded.** That matters because the allocator already
*refuses* to command opposite directions (ALLOC-01's sign-coherence gate), so a
figure computed from the allocation record would read zero by construction and
detect nothing. What this catches is circulation **nobody commanded** — a unit
ignoring or lagging its share, a stale share still being executed, or an
inverter doing something of its own accord.
| option | default | meaning |
|---|---|---|
| `circulation_w` | 700 | Watts of measured opposition below which nothing is reported |
| `circulation_hold_s` | 75 | Seconds it must stand there continuously before the trip |
**Why 700 W and 75 s, and why neither is a round number.** Both were read off
924 closed-loop runs on the two-master test rig in which *nothing* was faulty,
swept across the whole range the schema accepts for `gain` and `slew_w`. A
momentary opposition is **legitimate**: writes to the inverters are serialised,
so on a reversing cycle one unit gets its new number up to a control cycle
before its sibling, both slew through zero, and between the two crossings they
genuinely oppose. The worst *continuous* legitimate opposition, by threshold,
was **505 s at 100 W, 40 s at 250 W, 10 s at 300 W and 5.0 s — one control
cycle — at 400 W and above**. The knee is 400 W and it is the schema floor;
below it, ordinary operation would hold the sensor over the line for minutes and
no usable window could tell that from a fault. 700 W carries margin above the
knee because the second inverter's ramp and lag are not yet measured. 75 s is
15× the worst legitimate episode, 2.5× the firmware's own 30 s link-veto window,
and comfortably inside the 900 s quarter that bills the capacity tariff.
**What happens when it trips, and what it honestly cannot do.** The site is
commanded **0 W on every inverter** and latched there until you press start.
That is not aimed at making a misbehaving inverter stop — if a unit has stopped
listening, no command will reach it. It does two things that do not need its
cooperation: it removes *this controller* as one of the two participants in the
loop, and it makes anything still happening **visible at the meter** instead of
cancelled at it, where the ordinary guards can see it. **If the grid reading
does not move after the trip, one inverter is no longer listening and the
remaining actuator is a human at the isolator.**
**The alarm survives a Home Assistant restart.** The latch is written to `/data`
and the notification is re-raised on the first cycle after every start —
`persistent_notification` lives only in memory, and an alarm that vanishes with
a restart is how a real outage on this system went unseen for over six hours.
Restarting does **not** clear the trip; starting control from the add-on UI
does, and only after you have read why.
### Energy price providers
> **A fetched price moves energy only when you switch arbitrage on.** This
@@ -979,6 +1178,6 @@ abort one.
## Status entities
If an MQTT broker is available the add-on publishes setpoint, grid power,
battery power, state of charge, maintenance phase and controller status by MQTT
discovery. This is observability only — the controller works fine without a
battery power, circulating power, state of charge, maintenance phase and
controller status by MQTT discovery. This is observability only — the controller works fine without a
broker, and MQTT problems can never affect control.
+182
View File
@@ -127,6 +127,186 @@ Two rules come out of it, and both are cheap:
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.
## The third way a check lies: its DATA cannot reach the failure it names
Stale bytecode manufactures survivors from a mutation that never ran. Masking
manufactures them from a second guard doing the first one's work. This one
manufactures them from a **fixture**: the check runs, the assertion is
evaluated, the sentence above it is true — and the numbers it compares are
arranged so that the failure it describes could not have changed the answer.
It is not hypothetical and it is not rare. EIGHT instances in two weeks; four
were found by review, two - CFG-04's fixture pair - by an author's own mutation
battery, which is the cheaper place, one by review again, in the one
place nobody had thought to point the rule at: not a check in the suite, but a
COMMITTED EVIDENCE ARTIFACT four documents cite - and the eighth INSIDE THE FIX
WRITTEN TO CLOSE THE SEVENTH.
⚠️ **AND IT HAS NOW APPEARED IN SIX CONSECUTIVE CARDS.** The seventh instance,
MAINT-05's, is the one that says why: the defect is not carelessness about
fixtures, it is that **a check and the thing it checks were built from the same
constant**. Ask of every difference-claim not "is this assertion true" but
"where did each side of this comparison come from" - and if the answer is the
same place twice, the check is decoration.
* **ARB-03** shipped a call-site scan asserting that every `claims.append` in
`cycle()` routes through `actuator_of()`. Its own parse **saw 3 of the 8
appends**; the other five were invisible to it and would have passed however
they were routed.
* **ALLOC-01** shipped a replay generator to hunt for envelope escapes. It found
**0**. A widened generator over the same allocator found **39,991**.
* **DEV-02** shipped `"each unit's supervised bound is ITS OWN max_w — give
inverter B a different rating and the claim filed on inverter B moves with
it"`, comparing inverter B's bound against `_b2.max_w`. The fixture defaulted
B's rating to A's, so it compared `(-5000, 5000)` against `(-5000, 5000)` —
**a number against itself**. Filing both per-unit bounds from
`self.inverters[0]` left **all 19 files green**.
* **CFG-04** wrote *"an entry that omits `soc_entity` has NO SoC sensor and does
not borrow the flat one"* against a fixture whose **flat `soc_entity` was
blank**. Inherited and not-inherited were both `""`, so the mutation that
makes `build_roster()` fall back to the flat key survived. The fixture now
sets a real entity there, and the check asserts that the flat value is present
as well as that the entry's is empty.
* **CFG-04** also wrote *"main.py runs the per-unit range check
UNCONDITIONALLY"* as a **substring test over `app/main.py`'s source**. The
mutation that defeats it puts the call back inside `if entity:` — one level of
indentation — and the substring is still there. That is habit 4 below in a new
costume: the check asserted against the TEXT of the thing under test rather
than against its behaviour. It now drives the shipped `run_control()` on a
two-inverter config, **under a deadline**, because the mutation's real symptom
is that the controller enters its loop and never returns.
* **MAINT-05** shipped `Controller.__init__` calling
`migrate_maint_keys(store, self.inverters[0].name, ...)` under a comment
saying *"it targets `self.inverters[0].name` and NOT `UNIT_A` ... writing
`UNIT_A` here would deposit an install's whole maintenance history under a
name that is not on the roster at all"*. `inverter.UNIT_A` **is** the string
`"inverter-a"`, and every two-pack fixture in `test_maintenance.py` named its
first roster entry `inverter-a` — so the two expressions were the same value
in every check that existed, and swapping them left **all 19 files green**
while losing a real install's whole maintenance history. Two-pack fixtures are
now `["garage", "shed"]`, each behind a precondition check (habit 1) that the
first name is not `UNIT_A`.
⚠️ **AND THE POSTCONDITION HAD THE SAME SHAPE AS THE FIXTURE.**
`store._verify_moves()` read back the keys it had just written, under the
namespace it had just been handed — so it verified clean, and the caller
stamped the schema marker, on a migration nothing would ever read. *A check
that reads back the namespace it was handed cannot detect being handed the
wrong one*: it compared a thing against itself, exactly as DEV-02's fixture
compared `(-5000, 5000)` against `(-5000, 5000)`. The habit-2 fix is the same
one — grade against something the thing under test did not supply, here the
ROSTER the machines read.
⚠️ **AND THE FIX ITSELF CARRIED THE DEFECT, WHICH IS THE SIXTH CARD IN A ROW
AND THE FIRST TIME IT HAS APPEARED *INSIDE* A REMEDY.** The fix round's
recovery check was `migrate_maint_keys(_m5, ROSTER[0], ROSTER)` — the
**corrected** name. It measures recovery along the one path where the operator
has *already fixed the bug*, and nothing in the 19 files called
`migrate_maint_keys()` twice with the **same wrong** `unit`. So the refusal
the card was rejected twice to obtain lasted **exactly one start**: measured
at Controller level over one persisted store, roster `["garage", "shed"]` —
construction 1 `ok=False misdirected=4 moved=4 kept=0 marker=<absent>`,
construction 2 `ok=True misdirected=0 moved=0 kept=4 marker=1`. On start 2
rule 1 routes the wrongly-written keys to `rep.kept`, `rep.moved` is empty,
the roster loop iterates over nothing, and the marker is stamped on a
migration that reached no readable key — after which the early return skips it
forever, *including after the call site is fixed*. The check was true and
passed for the wrong reason. Habit **9** below is what falls out of it.
* **CFG-04's `tools/supervisor_shape_probe.py` §B** — and this one is the rule
reaching outside the suite. The probe is the committed evidence that
`config.yaml`'s `inverters: []` default is load-bearing, and four documents
quoted it as answering *"Missing option 'inverters' in root"*. §B validated
the reconstructed LIVE options blob, which is missing many required keys
unrelated to this card, so its refusal named whichever of THOSE the validator
reached first — `meter_freeze_s`, `p1_phase_export_entities` and
`sign_disagree_w` on three different runs. The quoted string was never
produced by the instrument. And the assertion was a bare **`not ok`**: delete
`inverters: []` from `config.yaml` and §B went on printing **PASS**, blind to
the exact regression it was cited for. §B is now an isolated counterfactual —
the shipped defaults, and the same defaults minus that one key — asserting on
the **key name in the refusal**; the mis-cited blob survives, relabelled, as
§B2. Re-run with the default deleted it prints `2 CASE(S) FAILED` and exits 1.
⚠️ **A committed transcript is a check, and it decays like one.** Nothing in
this document had been pointed at `tools/`, because the artifacts there are
filed as *measurements* rather than as *checks* — and a measurement whose
assertion cannot fail is exactly the thing this section is about. Two habits
follow, and both are habit 5 and 6 below.
Note what these have in common with a masked rung: the mutation *runs*, and the
suite is *honestly* green. Nothing in a purge, a fingerprint or a disassembly
can see it, because the code under test really did behave identically on the
stimulus it was given. The defect is upstream of the assertion, in what the
check was handed.
**The rule, and it is one line:**
> **Any check asserting "X differs from Y" must be run once with X and Y
> actually made different.**
Cheap habits fall out of it, and all of them are now used in this repository:
1. **Write the PRECONDITION as its own check.** `test_peakguard.py` 10g asserts
that A and B have different ratings *before* it asserts that B's bound is
B's. If a later edit makes them equal again, the precondition goes red rather
than the claim going quietly vacuous.
2. **Assert against literals, not against the expression under test.**
`== [(-_b2.max_w, _b2.max_w)]` cannot distinguish "B's number" from "the
number this fixture happens to have twice"; `== (-3000.0, 3000.0)` beside a
printed `A = 5000` can.
3. **Print what the check saw.** Every one of the three above would have been
caught by a human reading one line of output — `supervised bounds by
actuator: {'inverter-a': (-5000, 5000), 'inverter-b': (-5000, 5000)}` is
self-evidently not evidence of a difference.
4. **Assert on the BEHAVIOUR, not on the source text of the thing under test.**
A substring test over a module is a check on how the code is spelled;
whitespace, an alias or a moved line defeats it while the property it names
is gone. `test_inverter.py` part 10 has one of each — a source pin for a
claim that genuinely IS about the code's shape, and a driven `run_control()`
for a claim about behaviour — and the second replaced the first after the
mutation battery walked straight through it.
5. **A check whose failure mode is a HANG needs a deadline.** Otherwise the
mutation that defeats it produces a CI timeout with no name attached, which
reads like flaky infrastructure and gets retried rather than read.
6. **Assert on the CONTENT of a refusal, not on the fact that one happened.**
`not ok` is satisfied by any error at all, including one about a different
key on a different blob. `"Missing option 'inverters' in root" in out` goes
red the moment the refusal stops being about the thing it is cited for. This
is habit 2 in the negative direction: a refusal, like a difference, has to be
asserted against a literal.
7. **Vary ONE thing in a counterfactual, and vary it from an ACCEPTED
baseline.** `supervisor_shape_probe.py` §B validates the shipped defaults
first, precisely so the refusal on the next line has nowhere else to come
from. Without the accepted baseline the second line is a refusal of unknown
provenance, which is what §B used to print.
8. **A committed transcript is a check.** Anything under `tools/` that a
document quotes is subject to every rule above, and to the mutation battery:
break the property, re-run the instrument, and confirm the transcript goes
red. `inverters: []` was deleted from `config.yaml` and the probe re-run
against `ghcr.io/home-assistant/amd64-hassio-supervisor:2026.08.0` for
exactly that reason.
9. **Exercise a refusal a SECOND time with the SAME wrong input — not the
corrected one.** A guard that refuses once and then admits the same bad
caller is not a guard, it is a delay, and the second call is a *different
code path* whenever the first call left state behind. MAINT-05's roster
grading iterated the keys it had just **written**; on the second start the
same wrong caller found them already present, they moved to the
`already namespaced` list, and the loop graded an empty set. Re-running with
the **fixed** argument — which is what the check did — measures the operator's
recovery, never the persistence of the refusal. Ask of every refusal: *what
does this do when the caller has not been fixed and simply runs again?* And
assert the **shape** of that second report, not only its verdict, so the
check cannot silently revert to grading the first path.
And the mutation-table consequence: **a variant is not covered because a
near-miss of it is.** DEV-02's table listed the *actuator* variant of the
per-unit claim defect (`device`/`supervised` filed without `inv`), which the
static routing pin catches. The *bound* variant — right actuator, wrong
numbers — is a different defect with a different fix, and it was absent. Both
are in the table now.
## Where each surface stands
* **Local and dev-harness runs — the exposed one.** This is where FCST-03 hit
@@ -175,6 +355,8 @@ commit and PR bodies.
| **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. |
| **MAINT-05 round 3**, `migrate_maint_keys()` marker gate `if rep.ok:` → `if rep.ok or rep.kept:` (`+12 B`) | **was a survivor — now CLOSED** | measured against head `65cddf3` under the purge, tree mounted `:ro`, `19/19 PASS`. It stamps the schema marker on a migration that LOST state, defeating the older `lost` guard as well as the new `misdirected` one, because every check that reached the marker did so on a store whose `kept` list was empty. Closed by `test_maintenance.py` **9d**; the mutation is now red on three named checks. |
| **MAINT-05 round 3**, `migrate_unit_keys()` marker gate `if rep.ok:` → `if rep.ok or rep.kept:` (`+12 B`) | **found here — SAFETY-02's half, now CLOSED** | the SAME mutation one function up, on the LATCH migration rather than the history one. Measured a survivor against this branch under the purge, `:ro`, `19/19 PASS`, then closed by `test_inverter.py` part 10's new fixture — a store with `unit/inverter-a/sign_reason` already present (so `kept` is non-empty) whose `sign_tripped: true` write is dropped. Shipped: marker withheld. Mutant: marker stamped on a **disarmed latch**, and the next start skips the migration that would have re-armed it. |
| **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
+654
View File
@@ -0,0 +1,654 @@
"""One site grid target, divided across N inverters so that the shares SUM to it.
⚠️ THE REASON THIS EXISTS, AND IT IS NOT EFFICIENCY. The control primitive in
this system is METER EMULATION: the master reports a FABRICATED grid reading
(0x056E direction, 0x056F magnitude, FC 0x10, every 1-2 s) and the inverter
regulates ITSELF to it. So one number means "the battery moves X W" to this
add-on and "the grid is at X W" to the inverter - an identity that holds ONLY at
N=1. Hand two inverters the same target and each supplies it IN FULL: the loop
gain at the meter becomes N times the per-unit gain.
That is measured, not argued. On admin/goodwe's two-master rig (TEST-19,
`sim/sitesim.py --table`, the add-on's own `compute()` in the loop and the
firmware's own encoder on the wire):
N=2 gain 0.6 BROADCAST worst export -400 W (N=1: +10 W)
N=2 gain 1.0 BROADCAST commands [1000, 2000, 1000, 0] W,
grid [0, -2000, 0, +2000] W, tail p2p 4000 W,
FOREVER, and not one guard fires.
`gain: 1.0` is what config.yaml:374 accepts as its documented maximum. The sign
watchdog is evaluated on every one of those cycles and never trips, because the
disagreement flips on alternate ticks and never holds its 180 s window. So the
broadcast fault is not merely inefficient: it is invisible to every detector
this repository has.
THE FIX IS STRUCTURAL, WHICH IS WHY IT IS A MODULE AND NOT A TUNING CHANGE
=========================================================================
ONE integrator on P1, above the split (§10.3, and `compute()` is that
integrator). Its output S is the SITE's grid target. This module turns S into
per-unit shares with one invariant:
sum(shares) + unmet_w == S, with unmet_w == 0 whenever the envelopes allow
and each inverter is then told a function of ITS OWN SHARE, never of the shared
measurement. Write s_i = a_i * S with sum(a_i) = 1. Each unit closes its own
loop with per-unit gain g_i, so the gain seen AT THE METER is
gbar = sum(a_i * g_i)
which is a CONVEX COMBINATION of the per-unit gains and therefore lies in
[min g_i, max g_i] FOR ANY SPLIT. Compare the broadcast case, a_i = 1 for every
unit, where the same sum is N * g and grows without bound in N.
⚠️ THAT IS THE WHOLE ARGUMENT, AND IT IS WHY THE WEIGHTS ARE A COMFORT CHOICE.
Nothing above constrains the a_i beyond summing to 1. So SoC, thermals and pack
wear may set them freely and a BAD SPLIT CANNOT DESTABILISE THE SITE - it can
only be unkind to one pack. That property is the reason §6.2 chose share
allocation over a regulator/ballast arrangement, in which the ballast unit's
share is a function of the shared measurement and the gain question comes back.
⚠️ WEIGHTS EXPRESS PREFERENCE. ENVELOPES EXPRESS PERMISSION. A weight of 0
is "please do not use this unit", and it is honoured while any other unit
has headroom - but it is NOT a constraint, because the SUM is the safety
property and stranding capacity behind a preference would leave a standing
error for the site integrator to chase forever. To make a unit genuinely
unusable, close its envelope or leave it out of `live`. See `_fill()`.
WHAT THIS MODULE MUST NOT DO
============================
⚠️ IT MUST NOT READ P1. One integrator on the site measurement, above the split.
A second reader of the meter is a second controller, and two controllers on one
actuator is the failure the whole arbiter exists to prevent. Nothing in here
takes a measurement of any kind: the inputs are S, the per-unit intervals, and
per-tick liveness. That is checkable by reading the imports, and it is why there
are none beyond the standard library.
⚠️ IT MUST NOT CACHE AN ENVELOPE. `plan()` is a pure function called once per
tick with that tick's intervals. A unit's available range moves for reasons that
have nothing to do with the allocator - a stale link, a pack at its floor, a
device rating that failed to read - and an allocator holding a construction-time
envelope over-allocates into a unit that cannot take it. There is no state here
to hold one; that is deliberate and it is graded.
⚠️ ROUNDING IS A SAFETY PROPERTY. The setpoint register is 1 W (control.py says
so where it quantises). A per-unit `round()` biases the sum by up to N/2 W every
tick, and at 1-2 Hz a systematic 1 W bias is a PERMANENT standing error the site
integrator will chase forever - it is not a rounding artefact, it is a slow
offset with a control loop wound around it. So the sum is computed in INTEGER
ARITHMETIC from an integer target and the fractional parts are settled by
LARGEST REMAINDER (Hamilton): floor everything, then hand the leftover watts one
at a time to the units with the largest discarded fraction. The sum cannot drift
because no float ever enters it.
"""
from dataclasses import dataclass, field
from math import ceil, floor, inf
# The tolerance on a float comparison of watts. Envelopes arrive as floats from
# config and from device registers; this is the width below which two of them
# are the same number. It is never used on the sum - see the module docstring.
EPS = 1e-9
# --- why a unit is not in the envelope set, and why the whole thing refused ---
# Named rather than spelled inline so that main.py, SAFETY-28's write gate and
# the tests can all agree on which case fired without matching English.
DROP_STALE = "stale link"
DROP_CONTRADICTION = "contradicts itself"
DROP_NO_INTEGER = "no integer setpoint in its interval"
REFUSE_SCOPE = "mis-routed claim"
REFUSE_EMPTY = "no unit available"
REFUSE_SIGN = "opposite directions"
@dataclass(frozen=True)
class UnitPlan:
"""What ONE unit was told this tick, and why it was that and not more.
This is the per-unit half of the allocation record. `why` is written for an
operator reading an action log at 2 a.m., not for a developer: it says which
mechanism chose the number - the weighted fill, an envelope that ran out, a
claim of the unit's own that outranked the site.
"""
unit: str
share_w: int
lo: float
hi: float
weight: float
why: str
pinned: bool = False
clamped: bool = False
dropped: bool = False # not commanded at all - see `within_envelope`
@property
def span(self) -> str:
return (f"[{'-inf' if self.lo == -inf else format(self.lo, '.0f')}, "
f"{'+inf' if self.hi == inf else format(self.hi, '.0f')}]")
@property
def within_envelope(self) -> bool:
"""Is the number this unit was told ACTUALLY inside the interval?
⚠️ THIS IS ASKED, NOT ASSUMED. The record is what SAFETY-28 gates on,
and a record that describes a share it did not check is worth less than
no record: the half-open clamp defect shipped a line reading
`inverter-a -> +500 W in [2000, +inf] (weighted share)` - the record
stating, in the same breath, both the floor and the share below it, and
agreeing with itself. The clamp is fixed, so this should now be true on
every plan the allocator builds; that is exactly why it is cheap to
assert rather than to trust.
A DROPPED unit is always within: it was told nothing. Its interval may
be a contradiction (`lo > hi`), which no number is inside, and printing
that as a violation would cry wolf on the one case that is already
reported by name.
"""
if self.dropped:
return True
return self.lo <= self.share_w <= self.hi
def explain(self) -> str:
if self.dropped:
return (f"{self.unit} -> not commanded, envelope {self.span} "
f"({self.why})")
if not self.within_envelope:
# Unreachable as the allocator stands. If it ever is reachable
# again, the log says so in the line an operator is already reading
# rather than in a line nobody wrote.
return (f"{self.unit} -> {self.share_w:+d} W OUTSIDE {self.span} "
f"({self.why}) - ENVELOPE VIOLATED, DO NOT WRITE")
return f"{self.unit} -> {self.share_w:+d} W in {self.span} ({self.why})"
@dataclass(frozen=True)
class Allocation:
"""EVERY TICK PRODUCES ONE OF THESE, including the ticks that refused.
⚠️ IT IS DESIGNED TO BE GATEABLE, because SAFETY-28 gates the write path on
it. That means three things, and each is a decision rather than a
convenience:
* `ok` is ONE boolean and it is the only thing a gate has to read. A gate
that must parse a message, or check three fields in the right order, is a
gate somebody gets wrong.
* a REFUSAL still carries the record - `plans`, `dropped` and the reason -
so the gate can say WHY it stopped the write instead of only that it did.
A refusal that returns nothing is a refusal nobody can debug.
* `unmet_w` is separate from `ok`. An allocation that could not place every
watt is still SAFE TO WRITE and strictly better than commanding zero; it
is the site target that was not fully met, not a broken allocation. Fusing
the two would make a saturated inverter park the whole site.
`sum_w` is the integer the shares are required to add up to, and
`quantisation_w` is the ONE rounding that produced it from `target_w`. Both
are here so that "the shares sum to S" can be checked by a reader rather
than believed: `sum(shares.values()) + unmet_w == sum_w` is an identity over
integers, and `sum_w - target_w` is a single site-level rounding of at most
half a watt that is NEVER distributed into a per-unit bias.
"""
target_w: float
sum_w: int
shares: dict = field(default_factory=dict)
plans: tuple = ()
dropped: tuple = () # ((unit, why), ...) - order is roster order
unmet_w: int = 0
quantisation_w: float = 0.0
refused: str | None = None
passthrough: bool = False # N<=1: the share IS the site target, unrounded
# SAFETY-28. WHICH TICK PRODUCED THIS RECORD, as an opaque token minted by
# the caller - `Controller.alloc_tick`, incremented once per resolution.
#
# ⚠️ IT IS AN INPUT, NOT A COUNTER THIS MODULE KEEPS. `plan()` is a pure
# function and part 10 of test_alloc.py grades that by asserting the module
# holds no state at all; a serial number incremented in here would be
# exactly the cached-across-ticks thing the envelope rule forbids, wearing a
# different hat. So the tick is handed in and handed back out, and the
# freshness question is answered by whoever owns the clock.
#
# ⚠️ AND IT DEFAULTS TO None, WHICH THE WRITE GATE REFUSES. A record built
# without a tick is not "tick zero", it is a record that cannot say when it
# was made - and the gate fails closed on it. Every test in this repository
# that calls `plan()` for its arithmetic gets None and does not care;
# main.py stamps every record it puts on the write path.
tick: int | None = None
@property
def ok(self) -> bool:
"""The one boolean SAFETY-28's write gate reads."""
return self.refused is None
def authorises(self, unit: str, value: float, tick: int | None) -> str | None:
"""Why `unit` may NOT be written `value` on tick `tick`, or None if it may.
⚠️ THIS IS THE QUESTION SAFETY-28 REPLACED A CONFIG-SHAPE PROXY WITH, and
it lives on the record rather than in main.py so that the record is the
thing that answers it. Before this, "two writers can never reach one
actuator" was enforced by `len(validate.ACTUATOR_WRITE_KEYS) == 1` -
true, but a statement about the OPTIONS SCHEMA. Add a per-inverter
config (CFG-04) and there are two real writers with that length still 1:
the check stays green while the property it protects is gone.
Asking the record instead makes the property mechanical. A number
reaches the wire only if the single allocator placed it, on THIS tick,
for THIS unit. A second writer with its own arithmetic cannot produce
one, because it does not appear in a record; and it cannot borrow an old
one, because the tick has moved on.
⚠️ `unmet_w` IS NOT CONSULTED AND MUST NOT BE. An allocation that could
not place every watt is still SAFE TO WRITE - see this class's own
docstring. Fusing the two would let one saturated inverter park the
whole site, which is a worse outcome than the hole this gate closes.
⚠️ NOR IS 0 W ITS BUSINESS. The caller answers that one before it asks
this, and the reason is at `Controller.write_refusal()`: a gate that can
block the failsafe is worse than the hole it closes.
"""
if tick is None or self.tick is None or self.tick != tick:
return (f"the allocation record on hand was made on tick "
f"{self.tick!r} and this is tick {tick!r} - a record whose "
f"envelopes have moved cannot authorise a write")
if not self.ok:
return f"the allocator refused this tick ({self.explain()})"
if unit not in self.shares:
return (f"{unit} has no share in this tick's allocation "
f"({self.explain()})")
share = self.shares[unit]
if value != share:
return (f"{value:+.0f} W is not {unit}'s share of this tick's "
f"allocation, which is {share:+.0f} W ({self.explain()})")
# ⚠️ THE RECORD IS ASKED WHETHER IT AGREES WITH ITSELF. `within_envelope`
# exists because the half-open clamp defect once shipped a plan reading
# `inverter-a -> +500 W in [2000, +inf]` - stating the floor and a share
# below it in one breath - and `UnitPlan.explain()` renders that as
# ENVELOPE VIOLATED, DO NOT WRITE. This is the DO NOT WRITE.
#
# Unreachable at the shipped roster of one, where the pass-through's
# interval is (-inf, +inf) and every number is inside it. Graded anyway,
# on a constructed record, because the branch PR #40's reviewer replaced
# with `if False:` was unreachable too and the whole suite stayed green.
for p in self.plans:
if p.unit == unit and not p.within_envelope:
return (f"the record contradicts itself: {p.explain()}")
return None
def explain(self) -> str:
"""One line an operator can act on."""
if self.refused is not None:
return (f"REFUSED to allocate {self.target_w:+.0f} W: "
f"{self.refused}")
if self.passthrough:
return f"pass-through {self.target_w:+.0f} W (one unit, nothing to divide)"
body = ", ".join(f"{u}{s:+d}" for u, s in sorted(self.shares.items()))
out = f"{self.sum_w:+d} W as {body}"
if self.unmet_w:
out += f", {self.unmet_w:+d} W UNMET"
if self.dropped:
out += (" - dropped "
+ ", ".join(f"{u} ({w})" for u, w in self.dropped))
return out
def _int_envelope(b):
"""A unit's interval, narrowed to the integers a 1 W register can hold.
⚠️ NARROWED INWARD, ALWAYS. `ceil` on the floor and `floor` on the ceiling,
so every integer in the result is inside the real interval. Rounding the
other way would let a share of exactly the rating be commanded on a unit
whose rating is 2499.5 W, which is the one direction an envelope must never
move: the envelope is what `device` and `supervised` filed, i.e. what the
hardware said it can do.
Infinities pass through untouched - an absent bound is not a large bound,
and `ceil(-inf)` is not a number. A unit that filed nothing this cycle has
exactly that interval, which is why this case is the common one at N>=2 and
not an edge.
"""
lo = -inf if b.lo == -inf else ceil(b.lo - EPS)
hi = inf if b.hi == inf else floor(b.hi + EPS)
return lo, hi
def _clamp_int(v, lo, hi):
"""`v` as an int, pulled inside `[lo, hi]`. EACH END IS APPLIED ON ITS OWN.
⚠️ THE TWO ENDS ARE INDEPENDENT AND MUST BE TREATED SO. An earlier form
substituted `v` itself for a missing bound and fed both into one
`min(max(...))`, which reads as "an absent bound cannot bind" but is not
what it does: with `hi == inf` the whole expression collapses to
`min(max(v, lo), v) == v`, so a MISSING UPPER BOUND SILENTLY DISCARDED THE
LOWER ONE. `_clamp_int(0, 2142, inf)` returned 0 - a share below a 2142 W
floor the unit itself filed - and every caller here inherited it.
So: skip the end that is infinite, apply the end that is not, and never let
one end's absence reach the other. `UnitBounds()` defaults to
`(-inf, +inf)`, and this helper is the whole of the ticket's first
deliverable ("each share clipped to that unit's UnitBounds interval"), so a
one-sided envelope is the ordinary case, not an edge.
"""
v = int(v)
if lo != -inf:
v = max(v, lo)
if hi != inf:
v = min(v, hi)
return v
def _fill(order, weights, cap, amount):
"""WATER-FILL: place `amount` watts across `order`, capped, by weight.
`amount` and every `cap` are NON-NEGATIVE magnitudes; the direction has
already been taken out by the caller. Returns `(add, leftover)`.
THE LOOP IS THE STANDARD ONE and it terminates in at most len(order) rounds:
share the remaining amount in proportion to weight; any unit whose share
would exceed its cap is PINNED AT ITS CAP and dropped from the active set;
repeat with what is left. A unit that is not capped in a round is not capped
in any later round either, so nothing is revisited.
⚠️ AND THEN THE SECOND PASS, WHICH IS THE POLICY DECISION IN THIS FUNCTION.
Units with weight 0 are excluded from the weighted rounds - that is what a
zero weight is for. But if the weighted set fills up and watts remain, they
are offered to the zero-weight units, EQUALLY, rather than being reported as
unmet. The reason is the module docstring's: the weights are a comfort
choice and the sum is the safety property, so a preference must never
manufacture a standing error at the meter that the site integrator will then
chase. To make a unit genuinely unusable, close its envelope - `cap` is
obeyed absolutely and is never overridden here.
"""
add = {u: 0.0 for u in order}
rem = float(amount)
for pool in (
[u for u in order if weights[u] > 0.0],
[u for u in order if weights[u] <= 0.0], # the last-resort pass
):
# Inside the last-resort pass every weight is 0, so the proportional
# step needs a weight of its own; equal shares is the only choice that
# does not invent a preference the caller did not express.
w = {u: (weights[u] if weights[u] > 0.0 else 1.0) for u in pool}
active = [u for u in pool if cap[u] > 0.0]
while rem > EPS and active:
total = sum(w[u] for u in active)
capped = [u for u in active if rem * w[u] / total >= cap[u] - add[u]]
if capped:
for u in capped:
rem -= cap[u] - add[u]
add[u] = cap[u]
active = [u for u in active if u not in capped]
else:
for u in active:
add[u] += rem * w[u] / total
rem = 0.0
return add, rem
def plan(target_w, bounds, *, weights=None, live=None, scope_errors=(),
site_priority=None, site_key="site", tick=None) -> Allocation:
"""Divide the site grid target `target_w` across the units in `bounds`.
`bounds` unit name -> that unit's interval for THIS TICK (arbiter stage 1,
`UnitBounds`). Read per tick, never cached - see the module
docstring. Duck-typed on `.lo`, `.hi`, `.gate`, `.pinned_w`,
`.pinned_by` and `.contradiction` so that this module does not
import the arbiter and cannot grow a dependency on claims.
`weights` unit -> non-negative comfort weight. Missing units weigh 1.0.
`live` the units whose master has reported recently enough to be
commanded, or None for "all of them". A unit not listed is
DROPPED and the record says so; the survivors then carry the
whole site target, which is a real change in what the site can
do and must never happen silently (AC 6).
`scope_errors` the arbiter's mis-routing complaints. See REFUSE_SCOPE below.
`site_priority` the priority of the SITE claim that chose `target_w`. It is
what a unit's own winning SET is weighed against - see PINS.
`site_key` the name to use when there are no units at all.
`tick` an opaque token identifying the tick this record is FOR, handed
straight back on the record. SAFETY-28's write gate compares it
against the tick it is writing on, so that a record cannot be
replayed after its envelopes have moved. It is an input rather
than something this module counts, for the reason on the field.
⚠️ N<=1 IS A PASS-THROUGH AND IS BYTE-IDENTICAL TO WHAT SHIPPED. The share
IS the site target, as a float, unclamped and unrounded. That is §6.2's N=1
identity - with one inverter the fabricated grid reading and the battery
setpoint are the same number - and it is also the compatibility promise:
every existing test in this repository replays through here and must see the
number it saw before ARB-03. Do not "tidy" this branch into the general path
by giving it a roster of one; the general path rounds to an integer and
applies the envelope, and both are behaviour changes on the live install.
"""
units = tuple(sorted(bounds))
# --- REFUSAL 1: the claim list that produced S is known to be mis-routed --
# ⚠️ THIS IS THE ANSWER TO ARB-03's OPEN QUESTION, AND IT IS A REFUSAL
# RATHER THAN AN INPUT. `scope_violations()` reports a claim filed on an
# actuator its source's scope does not permit. It is tempting to CONSUME
# one - to read a unit-scoped claim that landed on the site as an allocation
# input - and that is wrong twice over. First, by the time this function
# runs the mis-routed claim has ALREADY been partitioned by `resolve()`, so
# its effect is baked into S or into somebody's interval and cannot be
# undone from here; consuming it would mean re-routing, which would make
# `actuator` advisory and hand every filing site a second chance to be
# wrong. Second, and worse, promoting a unit claim that landed on the site
# requires guessing WHICH unit it belonged to, and there is no information
# here to guess with - `actuator_for()` exists precisely because that answer
# is chosen where the claim is built. Applying it to ALL units would put one
# inverter's rating on a sibling that does not have it.
#
# So what is left is that S itself may be wrong, and dividing a number that
# may be wrong is worse than not dividing it. Refuse, and let main.py fail
# toward inaction and shout - which is the same answer clause 3 of the
# arbiter's own rule already gives to a contradiction.
#
# ⚠️ IT IS ABOVE THE N<=1 PASS-THROUGH ON PURPOSE, and that is the one place
# this card touches the pass-through's behaviour. A correctly routed
# one-inverter cycle CANNOT produce a scope violation - `scope_violations()`
# only complains about a unit source on the site when the site has named
# units, and a site source on a unit requires somebody to have hand-written
# `actuator=` past `actuator_for()` - so this cannot fire on the shipped
# install, and where it does fire the input is a known bug rather than a
# state to pass through.
if scope_errors:
return Allocation(
target_w=float(target_w), sum_w=int(round(float(target_w))),
shares={}, plans=(), dropped=(),
unmet_w=int(round(float(target_w))),
quantisation_w=float(int(round(float(target_w)))) - float(target_w),
refused=f"{REFUSE_SCOPE}: " + "; ".join(scope_errors), tick=tick)
if len(units) <= 1:
only = units[0] if units else site_key
share = float(target_w)
return Allocation(
target_w=float(target_w), sum_w=int(round(share)),
shares={only: share},
plans=(UnitPlan(only, int(round(share)), -inf, inf, 1.0,
"N<=1: the share IS the site target"),),
passthrough=True, tick=tick)
w = {u: 1.0 if weights is None else float(weights.get(u, 1.0))
for u in units}
for u, wu in w.items():
if wu < 0.0 or wu != wu:
raise ValueError(f"weight for {u!r} is {wu!r}; weights are "
"non-negative comfort factors, not signed targets")
# ⚠️ THE TARGET IS ROUNDED ONCE, HERE, AND NOWHERE ELSE. Everything below
# this line is integer arithmetic, which is what makes "the shares sum to S"
# an identity rather than a tolerance. `round()` is banker's rounding: over a
# long replay it is unbiased, where `int(x + 0.5)` would add a systematic
# half-watt in the discharge direction. In practice `target_w` arrives from
# `compute()` already quantised to `step_w` (10 W by default) so this is a
# no-op on the live path; it is not a no-op for a peak-shaving floor or an
# arbitrage setpoint, which are not quantised.
sum_w = int(round(float(target_w)))
quant = float(sum_w) - float(target_w)
# --- the envelope set, rebuilt from scratch every tick -------------------
dropped = []
ilo, ihi = {}, {}
considered = []
for u in units:
b = bounds[u]
if live is not None and u not in live:
# AC 6. The survivor is about to carry this unit's share and the
# record has to say so; `dropped` is how it says it, and main.py
# logs the transition.
dropped.append((u, DROP_STALE))
continue
if getattr(b, "contradiction", False):
# A unit contradicting ITSELF - its own `lo` above its own `hi`.
# Stage 1 already decided that parks THAT unit and not the site,
# which is the whole point of the partition; here it means the unit
# has no interval to allocate into.
dropped.append((u, DROP_CONTRADICTION))
continue
lo, hi = _int_envelope(b)
if lo > hi:
# An interval that contains no integer. The register is 1 W, so
# there is no number this unit could be commanded that both bounds
# accept - dropping it is the only answer that does not violate one.
dropped.append((u, DROP_NO_INTEGER))
continue
ilo[u], ihi[u] = lo, hi
considered.append(u)
def refuse(why):
return Allocation(
target_w=float(target_w), sum_w=sum_w, shares={}, plans=(),
dropped=tuple(dropped), unmet_w=sum_w, quantisation_w=quant,
refused=why, tick=tick)
# --- REFUSAL 2: nobody is available ------------------------------------
if not considered:
return refuse(f"{REFUSE_EMPTY}: "
+ ", ".join(f"{u} ({why})" for u, why in dropped))
# --- PINS: a unit's own SET, weighed against the site's -------------------
# ⚠️ THIS IS THE DECISION ARB-03 DEFERRED TO HERE, IN ITS OWN WORDS: "Stage 1
# states the constraint and records what it is gated on; deciding whether it
# applies is stage 3's business." `UnitBounds.gate` is the priority of the
# unit's own winning SET; `site_priority` is the priority of the SITE claim
# that chose S. Clause 1 of the arbiter's rule, transposed to a site with
# more than one actuator: the higher priority wins, and a tie goes to the
# unit, because a claim about one pack is more specific than a claim about
# the connection and specificity is what a tie has left to break on.
#
# A pinned unit is NOT in the water-fill. It is doing something of its own -
# a maintenance drain, a failsafe park - and what it does still counts
# toward the site sum, so the free units carry the REMAINDER. That is not
# the allocator compensating for a disturbance, which would be a second
# controller; it is the shares summing to S, which is the invariant. The
# meter's own answer arrives next tick through the one integrator above.
#
# ⚠️ AND site_priority=None MEANS "NO SITE SET WAS NAMED", so every pin
# stands. `resolve()` always passes the real one. A direct caller that
# passes nothing is saying it has no site claim to weigh, and honouring the
# unit's own highest-priority claim is the only safe reading of that.
pinned = {}
for u in considered:
b = bounds[u]
gate = getattr(b, "gate", None)
if gate is None:
continue
if site_priority is None or gate >= site_priority:
pv = getattr(b, "pinned_w", None)
if pv is None:
continue
pinned[u] = _clamp_int(round(float(pv)), ilo[u], ihi[u])
free = [u for u in considered if u not in pinned]
remainder = sum_w - sum(pinned.values())
# --- WATER-FILL over the free units --------------------------------------
# `base` is the point of each envelope nearest zero: 0 for an ordinary
# symmetric rating, and the forced end for an envelope that does not contain
# zero. Filling from there rather than from `lo` is what keeps a unit that
# is merely ALLOWED to charge from being TOLD to.
base = {u: _clamp_int(0, ilo[u], ihi[u]) for u in free}
placed = sum(base.values())
need = remainder - placed
up = need >= 0
cap = {u: (ihi[u] - base[u]) if up else (base[u] - ilo[u]) for u in free}
add, leftover = _fill(free, w, cap, abs(need))
exact = {u: base[u] + (add[u] if up else -add[u]) for u in free}
# --- LARGEST-REMAINDER ROUNDING -----------------------------------------
# Floor every share, then hand out the discarded watts one at a time, worst
# discarded fraction first. The sum is integer arithmetic end to end, so it
# cannot drift; ties break on the unit name so that the same inputs give the
# same allocation on every tick and on every host.
share = {u: int(floor(exact[u] + EPS)) for u in free}
for u in free: # floors can never leave the envelope,
share[u] = _clamp_int(share[u], ilo[u], ihi[u]) # but say so anyway
debt = remainder - sum(share.values())
frac_order = sorted(free, key=lambda u: (-(exact[u] - floor(exact[u])), u))
step = 1 if debt > 0 else -1
while debt != 0:
moved = False
for u in (frac_order if debt > 0 else list(reversed(frac_order))):
if debt == 0:
break
nxt = share[u] + step
if (step > 0 and nxt <= ihi[u]) or (step < 0 and nxt >= ilo[u]):
share[u] = nxt
debt -= step
moved = True
if not moved:
break
shares = dict(pinned)
shares.update(share)
unmet = sum_w - sum(shares.values())
# --- REFUSAL 3: SIGN COHERENCE, so circulating power is not expressible ---
# ⚠️ REFUSED, NOT AVERAGED. Two shares of opposite sign mean one pack
# discharging into the AC bus while another charges off it: energy round-
# tripping through two conversion stages for no reason, and - this is the
# part that makes it a safety property rather than an efficiency one -
# INVISIBLE. The meter sees the net, which is exactly S, so the site
# integrator is content; each unit sees a target it is meeting, so no
# per-unit guard fires; the sign watchdog compares a command against the
# meter and both agree. Nothing in this repository would ever report it.
#
# It cannot arise from an ordinary tick: the fill only ever moves shares in
# ONE direction from a base that is zero whenever the envelope contains
# zero, so opposite signs require an envelope that EXCLUDES zero (a forced
# floor) or a pin. Those are the cases worth refusing, and the refusal is a
# site-level one because the alternative - dropping the offending unit and
# re-filling - would silently override a claim that outranked the loop.
pos = sorted(u for u, s in shares.items() if s > 0)
neg = sorted(u for u, s in shares.items() if s < 0)
if pos and neg:
return refuse(
f"{REFUSE_SIGN}: {', '.join(pos)} would discharge while "
f"{', '.join(neg)} charges - circulating power, which nets to "
f"{sum_w:+d} W at the meter and is invisible to every guard")
plans = []
for u in units:
drop = dict(dropped).get(u)
if drop is not None:
plans.append(UnitPlan(u, 0, bounds[u].lo, bounds[u].hi, w[u],
f"DROPPED: {drop}", dropped=True))
continue
if u in pinned:
by = getattr(bounds[u], "pinned_by", None) or "its own claim"
plans.append(UnitPlan(u, pinned[u], ilo[u], ihi[u], w[u],
f"pinned by {by} at priority "
f"{bounds[u].gate}", pinned=True))
continue
at_edge = share[u] in (ilo[u], ihi[u])
why = "weighted share"
if at_edge and cap[u] - add[u] <= EPS and abs(need) > EPS:
why = "envelope full - its surplus went to the others"
elif w[u] <= 0.0 and share[u] != base[u]:
why = "last resort: the preferred units were full"
plans.append(UnitPlan(u, share[u], ilo[u], ihi[u], w[u], why,
clamped=at_edge))
return Allocation(target_w=float(target_w), sum_w=sum_w, shares=shares,
plans=tuple(plans), dropped=tuple(dropped),
unmet_w=int(unmet), quantisation_w=quant, tick=tick)
+489 -7
View File
@@ -25,11 +25,52 @@ Clause 2 is the interesting one. It is what makes "money outranks maintenance"
a consequence of the priorities instead of a special case somebody can forget:
the maintenance charge-only limit binds the loop, but a higher-priority peak
shaving claim simply is not bound by it.
⚠️ AND WHICH ACTUATOR IS A CLAIM ABOUT? THAT QUESTION HAS AN ANSWER AGAIN.
specs.md §6.1 declared `actuator: str` as the first field of `Claim` and the
implementation shipped without it, so every claim was implicitly about "the one
and only actuator" and `resolve()` returned one scalar. ARB-03 restores the
field, because §6.2 decided the site grid target is ALLOCATED across several
inverters and never broadcast to each of them - and an allocator needs a seam to
occupy that a single scalar does not have.
So resolution is now THREE STAGES, and they are separate functions so that a
test can construct a case at any one of them:
1. `pre_resolve()` - each inverter's OWN claims become an interval for that
unit. One unit's claims, one unit's bounds.
2. `site_resolve()` - the SITE claims become one grid target S. This is the
rule above, unchanged, and it is deliberately the same
code it was: at N=1 there are no unit claims, so this
stage sees the whole list and answers exactly what the
shipped arbiter answered.
3. `allocate()` - THE SEAM. It turns S into per-inverter shares subject to
stage 1's intervals. ALLOC-01 filled it: the allocator
itself is `app/allocator.py` and the reasoning lives
there, because it consumes intervals and a number and
must never learn about claims, priorities or P1.
⚠️ THE STRUCTURAL PROPERTY, AND IT IS THE REASON FOR THE SPLIT. A per-inverter
constraint is consumed by the allocator as an INTERVAL; it is never promoted
into the site claim list. So a unit `hi` and a site `lo` are never terms of the
same `lo > hi` test, and the contradiction clause below - which resolves to 0 W,
a battery parked inside a billed quarter - cannot be reached across two
inverters. That is DECISIONS/SAFETY-25-loop-soc-floor.md §0c, made mechanical:
not "guarded against", NOT EXPRESSIBLE. Filing a unit constraint as a site claim
to "keep it simple" is the whole bug, and `actuator_for()` is what stops a
strategy doing it by hand.
"""
from dataclasses import dataclass, field
from math import inf
# ⚠️ ONE WAY ONLY. `allocator` knows nothing about claims, priorities or
# this module - it consumes intervals and a number - so the dependency
# cannot become a cycle and the allocator stays testable on its own, which
# is what lets test_alloc.py sweep it hundreds of thousands of times
# without building a claim list for each one.
from . import allocator
# Priorities live here and nowhere else. The moment these become magic numbers
# scattered through the strategies, the whole point of this module is lost.
P_SAFETY = 100 # stopped, inputs missing, shutting down, device limits
@@ -50,6 +91,183 @@ P_LOOP = 10 # ordinary grid-following
SET = "set"
LIMIT = "limit"
# --- actuators, and the two scopes a claim can have -------------------------
# ⚠️ §6.2: THE GRID CONNECTION IS AN ACTUATOR TOO. It is the one every inverter
# at the site shares, and two inverters regulating against one meter are two
# writers on it - which is the failure this module exists to prevent, one level
# up from the one it was built for. So it gets a name, and claims about it are
# filed on that name rather than on nothing in particular.
ACTUATOR_SITE = "site"
SCOPE_SITE = "site" # about the grid connection: one of these per site
SCOPE_UNIT = "unit" # about one pack, one inverter, one device
# ⚠️ THE CLASSIFICATION, AND IT IS THE REAL OUTPUT OF ARB-03. Each entry is read
# off what the claim is ABOUT at its construction site in main.py, not off which
# module builds it. Getting an entry wrong is not cosmetic: a per-inverter
# reserve filed as a site `hi` against the peak guard's site `lo` is `lo > hi`,
# clause 3, 0 W - the battery parked in the billed quarter that SAFETY-25's memo
# calls fatal. The reasoning is recorded here, at the line, because this table is
# where a ninth source will be classified and the reasoning is what a future
# reader needs in order to classify it correctly.
CLAIM_SCOPE = {
# --- SITE: about the grid connection ---------------------------------
# main.py: `Claim.set("loop", P_LOOP, decision.target_w, ...)`. compute()
# regulates `grid_w` - the P1 measurement - to zero. Its subject is the
# meter, and §6.2's whole architecture is ONE integrator on P1 whose output
# is then split. A site claim, and the one the split exists for.
"loop": SCOPE_SITE,
# main.py: `peakguard.claim(...)`. The quantity is the 15-minute average
# OFFTAKE AT THE GRID CONNECTION, which is what the Belgian capacity tariff
# bills. There is one quarter-hour peak per site, not one per pack.
"peak": SCOPE_SITE,
# main.py: `arbitrage.claim(...)`. It buys and sells at the grid against a
# day-ahead price. The price is a property of the connection, and the energy
# it trades crosses the meter.
"arbitrage": SCOPE_SITE,
# main.py: `Claim.set("safety", P_SAFETY, 0.0, "stopped" | "inputs missing")`.
# ⚠️ READ BOTH CONSTRUCTION SITES BEFORE MOVING THIS ONE. Neither is about a
# pack. "stopped" is the operator switching control off for the SITE, and
# "inputs missing" is the SITE's own telemetry gone - the meter this whole
# controller regulates against. Both must stop every inverter, and a site
# SET at P_SAFETY is how that is said once rather than N times.
"safety": SCOPE_SITE,
# main.py: `Claim.set("circulation", P_SAFETY, 0.0, "circulating power")`.
# SAFETY-31, and this one is a SITE claim for a reason worth writing down,
# because the neighbouring `failsafe` entry looks like it and is not.
#
# `failsafe` is SAFETY-02: site-wide evidence, per-unit conclusion. It
# compares the meter against THE COMMAND THIS CONTROLLER PUT ON ONE
# ACTUATOR, so what it learns is about that actuator and the remedy is that
# actuator.
#
# Circulating power is not a property any single inverter has. It is
# `sum(|B_i|) - |sum(B_i)|`, defined over the whole roster and identically
# zero for any one unit, and there is NO FACT OF THE MATTER about which of
# two opposing inverters is the offender - a unit ignoring its share and a
# sibling faithfully executing a share computed to sum with it produce the
# same reading. Filing this per-unit would require inventing an attribution
# the measurement cannot support, and would park one inverter while the
# other went on feeding the loop. The evidence is site-level and so is the
# remedy: stop commanding, everywhere, and say why.
"circulation": SCOPE_SITE,
# main.py: `Claim.set("sign_site", P_SAFETY, 0.0, "site sign disagreement")`.
# SAFETY-30, and it is the twin of `failsafe` below rather than a duplicate
# of it - the two exist BECAUSE the same words describe two different
# measurements once there is more than one inverter.
#
# `failsafe` grades ONE unit's standing command against THAT UNIT'S OWN
# measured power (register 0x0518). Its conclusion is "the actuator I am
# driving is not doing what I told it", which is a fact about one device,
# so it parks one device.
#
# This one grades the SUM of the standing commands against P1. Its
# conclusion is "the site as a whole is driving the wrong way" - an inverted
# gain, an integrator wound past the rail, a strategy on the wrong side of
# the meter - and there is nothing per-unit about it: the quantity is a sum
# over the roster and the offending number is the site target, which no
# single inverter owns. Parking one unit on that evidence would leave the
# rest of the site pushing the same way with the guard satisfied.
#
# ⚠️ AT N=1 IT IS NEVER FILED, and that is the identity rather than a
# special case: with one inverter the sum of the commands IS that unit's
# command and `failsafe` already carries exactly this trip, under the keys,
# the banner and the claim an install has had since SAFETY-02 shipped.
# `Controller.cycle()` does not even arm the site detector there.
"sign_site": SCOPE_SITE,
# --- UNIT: about one pack, one inverter, one device -------------------
# main.py: `Claim.limit("device", P_SAFETY, self.dev_min, self.dev_max,
# "rating")`. The numbers are read off ONE inverter's own reported min/max.
# Another inverter has another rating; there is no site rating.
"device": SCOPE_UNIT,
# main.py: `Claim.limit("supervised", P_SAFETY, -max_w, max_w, "max_w")`.
# `max_w` is the supervised cap on what this controller may WRITE to a
# setpoint entity - §11.3's "the actuator is capped below the inverter
# rating". It bounds a write to one device, like `device` does and for the
# same reason, so it is scoped like `device`.
"supervised": SCOPE_UNIT,
# main.py: `Claim.set("failsafe", P_SAFETY, 0.0, "sign disagreement")`.
# ⚠️ THE EVIDENCE IS PER-UNIT AND SO IS THE REMEDY - AND SINCE SAFETY-30 THE
# FIRST HALF OF THAT SENTENCE IS TRUE. It used to read "the evidence is
# site-wide and the remedy is not", because the watchdog compared THIS
# unit's standing command against P1: a site measurement, attributed to one
# actuator on the strength of §6.2's N=1 identity. That identity does not
# survive a second inverter - at N>=2 the meter answers for a sibling this
# unit's command says nothing about, in both directions (a false trip when
# the sibling covers the meter, and a missed one when the sibling MASKS a
# unit that really is reversed).
#
# So at N>=2 the comparison behind this claim is THIS unit's command against
# THIS unit's own measured power - register 0x0518, per-instance since
# DEV-02 - and the scope that was already right for the wrong reason is now
# right for the right one. The site-wide half moved to `sign_site` above.
# At N=1 the two are the same comparison and this claim is the one filed,
# exactly as it shipped.
"failsafe": SCOPE_UNIT,
# main.py: `Claim.set("maintenance", P_MAINTENANCE, ...)` when the cycle owns
# the setpoint, and `Claim.limit("maintenance", P_MAINT_SHAPE, hi=...)` when
# it only shapes. §12's monthly recalibration is a PACK procedure - drain
# this pack to its floor, charge this pack to full, recalibrate this pack's
# coulomb counter. Two packs recalibrate on their own schedules.
"maintenance": SCOPE_UNIT,
}
def actuator_for(source: str, unit: str, units=()) -> str:
"""Which actuator a claim from `source` belongs on, given the site's roster.
⚠️ ROUTE THROUGH THIS, DO NOT PASS `actuator=` BY HAND. An unclassified
source raises `KeyError` here rather than defaulting to the site, which is
the one direction that is not safe to default in: a per-inverter constraint
that lands in the site claim list is exactly the `lo > hi` this card exists
to make unreachable. A ninth claim source has to be classified in
CLAIM_SCOPE before it can be filed, and test_peakguard.py part 10f is the
other half of that - it goes red on the line the ninth append is written.
⚠️ AND AT N=1 EVERY SOURCE ROUTES TO THE SITE. That is not the classification
being ignored, it is §6.2's identity: with one inverter the fabricated grid
reading and the battery setpoint are the same number, so the grid connection
and the only unit ARE the same actuator and there is nothing to allocate.
Splitting the list at N=1 would be a behaviour change on a live safety path -
the `failsafe` and `maintenance` SET claims would stop competing with the
site's for the winner, `explain()` would name a different source, and
`loop_is_following()` reads that name. The identity holds only at N=1, so
this function is the ONE place that stops relying on it, the day the roster
grows.
"""
if CLAIM_SCOPE[source] == SCOPE_SITE:
return ACTUATOR_SITE
return ACTUATOR_SITE if len(units) <= 1 else unit
def scope_violations(claims) -> list:
"""Claims filed on an actuator their source's scope does not permit.
A list of one-line complaints, empty when the routing is right. This is the
check `actuator_for()` cannot make on its own, because a caller can always
write `actuator=` by hand: it grades the claim list that actually reached the
arbiter, whatever built it.
"""
out = []
# ⚠️ THE SECOND TEST IS CONDITIONAL ON THE SITE HAVING NAMED UNITS AT ALL,
# and that is not laxity. At N=1 §6.2's identity holds and a per-inverter
# source filed on the site is CORRECT - it is what `actuator_for()` returns.
# The direction that produces `lo > hi` only exists once there is a second
# actuator for the constraint to have belonged to.
split = any(c.actuator != ACTUATOR_SITE for c in claims)
for c in claims:
scope = CLAIM_SCOPE.get(c.source)
if scope is None:
out.append(f"{c.source}: not classified in CLAIM_SCOPE")
elif scope == SCOPE_SITE and c.actuator != ACTUATOR_SITE:
out.append(f"{c.source}: a SITE claim filed on unit {c.actuator!r} - "
f"it would bound one inverter's share instead of the grid")
elif scope == SCOPE_UNIT and c.actuator == ACTUATOR_SITE and split:
out.append(f"{c.source}: a UNIT claim filed on the site while the "
f"site has named units - it can cross a site limit")
return out
@dataclass(frozen=True)
class Claim:
@@ -60,15 +278,76 @@ class Claim:
lo: float = -inf # for LIMIT
hi: float = inf # for LIMIT
reason: str = ""
# ⚠️ specs.md §6.1 DECLARES THIS FIELD FIRST AND IT IS LAST HERE, ON PURPOSE.
# The spec's point is that a claim NAMES its actuator; the tuple position is
# not the point, and it is load-bearing for two things that are. Every
# construction in this repository passes `source` first, and
# test_peakguard.py part 10f reads `Claim.set(...)`/`Claim.limit(...)`'s
# FIRST POSITIONAL ARGUMENT off main.py's AST to pin the claim-source set -
# the tripwire that guards SAFETY-25's deferred option. Moving `source` off
# position 0 would silently blind that scan, which is this repository's named
# failure mode. So the field is restored where it costs nothing.
#
# ⚠️ AND ITS DEFAULT IS THE SITE, EXPLICITLY. Not None, not "". A claim that
# does not name an actuator is a claim about the grid connection and says so;
# "unspecified" is what the shipped code already had, and it is what made
# every claim implicitly about the one and only actuator.
actuator: str = ACTUATOR_SITE
@staticmethod
def set(source: str, priority: int, value: float, reason: str = "") -> "Claim":
return Claim(source, priority, SET, value=value, reason=reason)
def set(source: str, priority: int, value: float, reason: str = "", *,
actuator: str = ACTUATOR_SITE) -> "Claim":
return Claim(source, priority, SET, value=value, reason=reason,
actuator=actuator)
@staticmethod
def limit(source: str, priority: int, lo: float = -inf, hi: float = inf,
reason: str = "") -> "Claim":
return Claim(source, priority, LIMIT, lo=lo, hi=hi, reason=reason)
reason: str = "", *, actuator: str = ACTUATOR_SITE) -> "Claim":
return Claim(source, priority, LIMIT, lo=lo, hi=hi, reason=reason,
actuator=actuator)
@dataclass(frozen=True)
class UnitBounds:
"""What one inverter's OWN claims say about that inverter's share.
STAGE 1's output, one per unit, and the thing ALLOC-01 consumes. It is an
INTERVAL plus the two facts an allocator cannot reconstruct from an interval:
* `pinned_w` - the value that unit's own winning SET asked for. A SET is not
a bound: `resolve()` CLAMPS a set value into the limits rather than
intersecting with it, and folding a 2500 W drain into `[2500, 2500]` would
turn "clamped to the rating" into "contradicts the rating". So it travels
beside the interval, not inside it.
* `gate` - the priority of that winning SET, or None. Clause 2 applies a
limit only at or above the winner's priority, and at N>=2 the winner may be
a SITE set chosen at stage 2, i.e. AFTER this. Stage 1 states the
constraint and records what it is gated on; deciding whether it applies is
stage 3's business. Guessing here is how a maintenance charge-only `hi`
would come to bind a peak discharge it does not outrank.
`contradiction` is a unit contradicting ITSELF - its own `lo` above its own
`hi`. It parks that unit and says so; it does not park the site, which is the
entire difference this card is about.
"""
lo: float = -inf
hi: float = inf
lo_src: str | None = None
hi_src: str | None = None
gate: int | None = None
pinned_w: float | None = None
pinned_by: str | None = None
contradiction: bool = False
def explain(self) -> str:
if self.contradiction:
return (f"CONTRADICTION within the unit ({self.lo_src} lo="
f"{self.lo:.0f} > {self.hi_src} hi={self.hi:.0f})")
span = (f"[{'-inf' if self.lo == -inf else format(self.lo, '.0f')}, "
f"{'+inf' if self.hi == inf else format(self.hi, '.0f')}]")
if self.pinned_by is not None:
return f"{span} around {self.pinned_by} -> {self.pinned_w:.0f} W"
return span
@dataclass
@@ -78,6 +357,32 @@ class Resolution:
bound_by: str | None = None # which limit actually changed it, if any
contradiction: bool = False
considered: list = field(default_factory=list)
# --- the three-stage fields. ⚠️ APPENDED, AND DEFAULTED, ON PURPOSE: every
# existing construction of this type is positional in its first five fields
# and `target_w` still means exactly what it meant - the SITE grid target.
# main.py assigns it to `self.target` unchanged.
unit_bounds: dict = field(default_factory=dict) # stage 1, per actuator
shares: dict = field(default_factory=dict) # stage 3, per actuator
allocated: bool = True # False when stage 3 declined to split
scope_errors: list = field(default_factory=list) # mis-routed claims
# ALLOC-01, appended for the reason the four above were: `target_w` still
# means the SITE grid target and every existing construction is untouched.
#
# `allocation` is stage 3's full record - what each unit was told and why,
# what could not be placed, what was dropped. `shares` and `allocated` are
# two fields OF that record, kept at the top level because main.py and four
# test files already read them there. ⚠️ IT IS THE RECORD, NOT THE PAIR,
# THAT SAFETY-28 GATES THE WRITE PATH ON: `allocated` says the allocator
# stands behind the split, and `unmet_w` says how much of the site target it
# could not place, and fusing those two would make one saturated inverter
# park the whole site.
allocation: object | None = None
# The priority of the SITE claim that chose `target_w`. Stage 3 weighs a
# unit's OWN winning SET against it - see `allocator.plan()`'s PINS note -
# and getting it from here rather than recomputing it is what stops the two
# rules drifting apart: this is set by the same line that picks the winner
# `explain()` names.
winner_priority: int | None = None
def explain(self) -> str:
"""One line an operator can act on - this is the point of the module."""
@@ -88,7 +393,107 @@ class Resolution:
return f"{self.winner} -> {self.target_w:.0f} W"
def resolve(claims: list) -> Resolution:
def pre_resolve(unit_claims: list) -> UnitBounds:
"""STAGE 1. One inverter's own claims -> that inverter's interval.
Clauses 1 and 2 of the rule, transposed: the unit's highest-priority SET
names what the unit wants and gates which of the unit's limits apply, and the
most restrictive of those limits gives the interval. Read UnitBounds on why
the SET value is not folded into the interval.
⚠️ THE INPUT IS ONE UNIT'S CLAIMS AND NOTHING ELSE. A site claim reaching
this function would become a bound on one inverter's share - the mirror image
of the fault this card removes, and the reason `resolve()` partitions rather
than filters twice.
"""
sets = sorted((c for c in unit_claims if c.kind == SET),
key=lambda c: c.priority, reverse=True)
gate = pinned_w = pinned_by = None
if sets:
gate, pinned_w, pinned_by = sets[0].priority, sets[0].value, sets[0].source
lo, hi = -inf, inf
lo_src = hi_src = None
for c in unit_claims:
if c.kind != LIMIT or (gate is not None and c.priority < gate):
continue
if c.lo > lo:
lo, lo_src = c.lo, c.source
if c.hi < hi:
hi, hi_src = c.hi, c.source
return UnitBounds(lo, hi, lo_src, hi_src, gate, pinned_w, pinned_by,
contradiction=lo > hi)
def allocate(target_w: float, bounds: dict, *, weights=None, live=None,
scope_errors=(), site_priority=None) -> tuple:
"""STAGE 3. THE SEAM, AND SINCE ALLOC-01 IT IS OCCUPIED. `(shares, allocated)`.
⚠️ THE ALLOCATOR ITSELF IS `app/allocator.py` AND THE REASONING LIVES THERE.
This is the adapter: it keeps the two-value shape every caller in this
repository already reads, and it exists as a separate name so that the
arbiter's three stages are still three functions a test can enter at any
one of them. `allocator.plan()` returns the full record - use that when you
need `unmet_w`, `dropped` or the per-unit reasons; `resolve()` stashes it on
`Resolution.allocation` for exactly that.
What §6.2 fixed and what this delivers:
* SUM-INVARIANT. `sum(shares) + unmet_w == round(target_w)`, in integer
arithmetic, so it cannot drift. Rounding is largest-remainder because a
per-unit `round()` biases the sum by up to N/2 W every tick and at 1-2 Hz
that is a PERMANENT standing error the site integrator chases forever.
* EACH UNIT IS TOLD A FUNCTION OF ITS OWN SHARE, never of the shared
measurement. That makes the gain at the meter a convex combination of the
per-unit gains for ANY split, which is why the weights are a comfort
choice and a bad split cannot destabilise the site.
* WITH AT MOST ONE UNIT IT IS STILL A PASS-THROUGH, byte-identical to what
ARB-03 shipped: the share IS the site target, as a float, unrounded and
unclamped. §6.2's N=1 identity, and the compatibility promise every
existing replay in this repository depends on.
⚠️ AND IT STILL DECLINES, WHICH IS NOT THE SAME LIST OF CASES AS BEFORE.
ARB-03 declined at N>=2 because it had no allocator; that trigger is gone
and the branch is NOT. It now fires when no safe split exists at all: a
mis-routed claim, no unit left in the envelope set, or a split that could
only be made by commanding one pack to charge while another discharges.
Read `allocator.plan()` for each. main.py's refusal path and
test_peakguard.py part 10h were re-aimed onto those rather than deleted -
PR #40's reviewer proved that guard was unreachable and untested once, and
removing its trigger without giving it a new one would rebuild the hole.
"""
return allocate_record(target_w, bounds, weights=weights, live=live,
scope_errors=scope_errors,
site_priority=site_priority)[:2]
def allocate_record(target_w: float, bounds: dict, *, weights=None, live=None,
scope_errors=(), site_priority=None, tick=None) -> tuple:
"""`allocate()` plus the record - `(shares, allocated, allocation)`.
`tick` is SAFETY-28's freshness token: it identifies the tick the record is
FOR and is handed straight through to `allocator.plan()`. Left None the
record is UNSTAMPED, which the write gate refuses - so a caller that intends
the record to authorise a write must pass one. Every existing caller in this
repository wants the arithmetic and not the authority, and gets None.
"""
rec = allocator.plan(target_w, bounds, weights=weights, live=live,
scope_errors=scope_errors,
site_priority=site_priority, site_key=ACTUATOR_SITE,
tick=tick)
return rec.shares, rec.ok, rec
def site_resolve(claims: list) -> Resolution:
"""STAGE 2. The SITE claims -> one grid target.
⚠️ THIS FUNCTION IS THE SHIPPED ARBITER, UNCHANGED. It is a separate name and
the same code, deliberately: at N=1 nothing is filed on a unit, so `resolve()`
hands it the whole claim list and it answers what it has always answered.
Every check in test_arbiter.py, test_watchdog.py, test_validate.py and
test_peakguard.py replays through here unedited, which is the proof that
ARB-03 changed no behaviour on the live path.
"""
sets = sorted((c for c in claims if c.kind == SET),
key=lambda c: c.priority, reverse=True)
@@ -113,7 +518,8 @@ def resolve(claims: list) -> Resolution:
if lo > hi:
return Resolution(0.0, winner.source, bound_by=None,
contradiction=True, considered=considered)
contradiction=True, considered=considered,
winner_priority=winner.priority)
target = max(lo, min(hi, winner.value))
bound_by = None
@@ -122,4 +528,80 @@ def resolve(claims: list) -> Resolution:
if binder is not None:
bound_by = f"{binder.source}({binder.reason})" if binder.reason else binder.source
return Resolution(float(target), winner.source, bound_by, False, considered)
return Resolution(float(target), winner.source, bound_by, False, considered,
winner_priority=winner.priority)
def resolve(claims: list, *, units=None, weights=None, live=None,
tick=None) -> Resolution:
"""The three stages, in order, over one cycle's claims.
`units` is the site's roster of inverters. Left None it is derived from the
claims themselves, which is right for a caller that files a claim for every
unit every cycle (main.py does - `supervised` is unconditional) and wrong for
one that does not, so main.py passes the real roster rather than let a silent
unit look like a smaller site.
`weights` and `live` are ALLOC-01's two per-tick inputs to stage 3, and both
are per-TICK on purpose. `weights` is the comfort choice - SoC, thermals,
wear - and cannot destabilise the site whatever it says. `live` is the set
of units whose master has reported recently enough to be commanded; a unit
left out of it is DROPPED from the envelope set and the record says so,
because the survivor carrying a dead unit's share silently is the failure
SAFETY-30 is about. ⚠️ NEITHER MAY BE CACHED BY A CALLER. A unit's range
moves for reasons unrelated to the allocator - a stale link, a pack at its
floor, a device rating that failed to read - so an envelope read once at
construction over-allocates into a unit that cannot take it.
⚠️ AND THE ARGUMENT HAS TO BE HONOURED, WHICH IS NOT THE SAME AS EXISTING.
Ignore it - derive always - and a unit that filed nothing this cycle ceases
to exist: a site of two reads as a site of one and stage 3 passes the whole
grid target through to the inverter that spoke, which is ARCH-01's fault
with its own evidence removed. That mutation survived the whole suite until
test_arbiter.py part 7 graded it on a SILENT unit.
⚠️ `tick` IS SAFETY-28's FRESHNESS TOKEN AND IT IS NOT OPTIONAL ON THE LIVE
PATH. It identifies the tick this resolution is FOR, and it ends up on
`Resolution.allocation.tick`, where the write gate compares it against the
tick it is writing on. A record with no tick cannot authorise a write, which
is why main.py passes `self.alloc_tick` and why a test that only wants the
arbiter's arithmetic can leave it out and be sure it has not accidentally
minted a licence to write.
⚠️ THE PARTITION IS BY `actuator`, AND IT IS A PARTITION, NOT A FILTER. Every
claim lands in exactly one stage. That is the whole structural argument: a
unit's `hi` and the site's `lo` are never both terms of the same `lo > hi`
test, so SAFETY-25 §0a's cross-inverter contradiction - 0 W inside the billed
quarter - is not something to guard against, it is something that cannot be
written down.
"""
site_claims = [c for c in claims if c.actuator == ACTUATOR_SITE]
if units is None:
units = {c.actuator for c in claims if c.actuator != ACTUATOR_SITE}
units = tuple(sorted(units))
# STAGE 1 - each unit's own claims become that unit's interval.
bounds = {u: pre_resolve([c for c in claims if c.actuator == u])
for u in units}
# STAGE 2 - the site claims become the grid target. At N=1 `site_claims` IS
# `claims`, so this is the shipped arbiter on the shipped list.
out = site_resolve(site_claims)
# STAGE 3 - the seam, and since ALLOC-01 the allocator behind it.
#
# ⚠️ THE ORDER MATTERS: `scope_violations()` IS COMPUTED BEFORE THE SPLIT,
# NOT AFTER, because stage 3 consumes it. A claim filed on an actuator its
# source's scope does not permit means the number about to be divided may
# itself be wrong, and dividing a number that may be wrong is worse than
# not dividing it - `allocator.plan()` carries the full argument, including
# why the mis-routed claim is NOT promoted into somebody's envelope. This
# was the open question ARB-03 left, and it is answered here rather than
# left as a log line nothing grades.
out.scope_errors = scope_violations(claims)
out.unit_bounds = bounds
out.shares, out.allocated, out.allocation = allocate_record(
out.target_w, bounds, weights=weights, live=live,
scope_errors=out.scope_errors, site_priority=out.winner_priority,
tick=tick)
return out
+6 -2
View File
@@ -146,7 +146,7 @@ import math
from dataclasses import dataclass
from datetime import datetime
from .arbiter import P_ARBITRAGE, Claim
from .arbiter import ACTUATOR_SITE, P_ARBITRAGE, Claim
from .price import Absence, price_option
_LOG = logging.getLogger("goodwe.arbitrage")
@@ -425,5 +425,9 @@ def claim(decision: ArbitrageDecision) -> Claim | None:
"""
if not decision.trading or decision.power_w is None:
return None
# ⚠️ ON THE SITE ACTUATOR, EXPLICITLY. A trade is bought and sold at the
# grid: the price is a property of the connection and the energy crosses the
# meter. So this is a claim on the SITE target, which the allocator then
# divides - not an instruction to any one pack.
return Claim.set(SOURCE, P_ARBITRAGE, float(decision.power_w),
decision.action)
decision.action, actuator=ACTUATOR_SITE)
+339
View File
@@ -0,0 +1,339 @@
"""SAFETY-31 - the power two inverters move through each other, which the meter cannot see.
Inverter A charging at 3 kW while inverter B discharges at 3 kW nets ~0 W at
P1. The site looks idle. In reality 3 kW is going round a loop through two
conversion stages continuously, for no benefit, and the wear on both packs is
real even though every instrument in this add-on says nothing is happening.
WHY NOTHING EXISTING SEES IT, AND IT IS STRUCTURAL RATHER THAN AN OVERSIGHT
==========================================================================
Every consumer of the site measurement is a consumer of the NET. SAFETY-02's
sign-disagreement watchdog gates on `abs(grid_w) > cfg.min_w` (300 W by
default) - with the grid at ~0 that gate never opens, on any cycle, for any
duration. The peak guard bills the quarter-hour average AT THE GRID
CONNECTION. The capacity tariff bills grid exchange. `freeze.looks_frozen()`
grades P1 against the site rail. There is one meter, it reads the sum, and
circulating power is exactly the component of per-unit power that the sum
DESTROYS. So this cannot be fixed by tuning a threshold on any existing
detector; it needs a quantity none of them are computing.
THE QUANTITY
============
circulating_w = sum(|B_i|) - |sum(B_i)|
Zero when every unit pulls the same way - then sum(|B_i|) == |sum(B_i)| by the
triangle equality. `2 * min(|B_a|, |B_b|)` at N=2 when they oppose, which is
twice the power going round the loop and is the right scale: that is what both
conversion stages are processing between them. It is non-negative always, it is
zero at N<=1 identically, and it needs no threshold to be interpretable - the
number IS the phenomenon in watts.
⚠️ IT IS COMPUTED FROM MEASURED PER-INVERTER POWER, AND THAT IS THE WHOLE CARD.
=============================================================================
The obvious cheap version reads the allocation record - the shares the
allocator just handed out - and reports the same formula over those. It would
be simpler, it would never see a `None`, and it would be worth NOTHING, for two
independent reasons.
The first is that it cannot fire. ALLOC-01 shipped the sign-coherence gate as
its AC 7 (`allocator.REFUSE_SIGN`, graded by `test_alloc.py` part 6): an
allocation whose shares carry two signs is REFUSED, both units named, no shares
returned. So a sensor over the allocation record is a sensor over a set the
allocator has already guaranteed is sign-coherent. It reads zero by
construction, forever, and a check written against it passes forever.
The second is the one MUTATION.md names as the third way a check lies. A sensor
derived from the allocation record can only ever confirm THE ALLOCATOR AGREES
WITH ITSELF. Every fault in this card's list is a divergence between what was
commanded and what the hardware is doing:
* a unit ignoring or lagging its share;
* a stale share still being executed by one inverter;
* SAFETY-25's deferred loop floor, or a maintenance drain, pinning one unit
while the loop drives the other;
* an inverter doing something of its own accord - and THIS HARDWARE HAS DONE
THAT TWICE. On 2026-09-02 the comms subsystem failed and the power stage
went on executing its last instruction for 6 h 25 m (HW-01). Through all of
it the allocation record was impeccable.
In every one of those the command side is coherent and the MEASUREMENT side is
not. So the input is `Inverter.batt` - this unit's own power, read from its own
`batt_entity`, which on the live system is holding register 0x0518, the
inverter's own AC power. DEV-02 made that per-instance; before it there was one
`batt` scalar on the Controller and this sensor could not have been written at
all.
⚠️ AND THIS IS THE MEASUREMENT HALF OF A PAIR. ALLOC-01's gate is the COMMAND
half: the allocator can no longer COMMAND circulating power. This module is the
detection half: circulating power the allocator never commanded. Neither one
replaces the other and neither is redundant - the gate refuses an allocation
before it is written, and cannot see a millisecond past that; this reads the
hardware and does not care what was written. Do not "unify" them.
THE TRIP, AND WHY A THRESHOLD ALONE IS A FALSE-ALARM GENERATOR
==============================================================
A momentary opposition is LEGITIMATE. Writes to the inverters are serialised
(one `hass.call()` at a time - see `Inverter`'s docstring on what a hung write
to A costs B), so on a cycle where the site target reverses, one unit receives
its new command up to a whole control cycle before its sibling. Both then slew
through zero, with a real ramp rate and a real first-order lag, and BETWEEN THE
TWO ZERO CROSSINGS THE UNITS GENUINELY OPPOSE. Nothing is wrong; the site is
turning around.
This project's doctrine on crying wolf is explicit (SAFETY-15, SAFETY-19) and
this is exactly the shape that generates it. So the trip is a threshold AND a
sustained window, and BOTH numbers were measured on the TEST-19 two-master rig
rather than chosen - see `CIRC_OPTION_DEFAULTS` for the measurements and
`DECISIONS/SAFETY-31-circulating-power.md` for the runs.
⚠️ THE WINDOW ACCUMULATES, WHICH IS WHY THIS IS NOT SAFETY-02's PROBLEM AGAIN.
The reason the sign watchdog is blind to the broadcast fight is that the
disagreement FLIPS SIGN on alternate ticks, so `disagree_since` is cleared
between every pair of them and the 180 s hold never accumulates (allocator.py's
docstring records the measurement). Circulating power cannot do that: it is a
MAGNITUDE, non-negative by construction, and a sustained loop holds it high on
every cycle rather than on every other one. An oscillation that genuinely
alternated between opposing and agreeing is not a circulating loop and should
not be reported as one.
"""
from dataclasses import dataclass
from datetime import datetime
# CFG-03. THE ONE IN-CODE COPY OF THESE DEFAULTS. `config.yaml`'s `options:`
# block is the source of truth an operator edits and the Supervisor reads;
# `schema:` holds the bounds. This dict exists for the reason
# `maintenance.MAINT_OPTION_DEFAULTS` does - the Dockerfile does not put
# config.yaml in the image, so the running add-on cannot read it - and
# `test_watchdog.py` pins the two together by READING config.yaml, so a drift
# goes red in CI rather than shipping.
CIRC_OPTION_DEFAULTS = {
# --- THE THRESHOLD, AND IT IS READ OFF A CURVE ------------------------
# ⚠️ MEASURED ON THE TEST-19 TWO-MASTER RIG, NOT CHOSEN. 924 closed-loop
# runs in which NOTHING is faulty - every unit executes the share the
# allocator gave it - over both families of stimulus that can produce
# legitimate opposition: single reversals (7 sizes x 5 write staggers) and a
# flapping load (7 periods x 4 amplitudes), each swept across the WHOLE
# range config.yaml accepts for the two settings that decide how fast the
# site can turn around, `gain` float(0.05,1.0) and `slew_w` int(50,5000).
# The worst CONTINUOUS opposition, as a function of the threshold:
#
# 100 W -> 505.0 s 300 W -> 10.0 s 700 W -> 5.0 s
# 200 W -> 445.0 s 350 W -> 10.0 s 1000 W -> 5.0 s
# 250 W -> 40.0 s 400 W -> 5.0 s 1700 W -> 0.0 s
#
# THE KNEE IS AT 400 W and it is sharp. Below ~250 W a flapping load holds
# the sensor above the threshold for MINUTES at a time - 505 s at 100 W -
# and no window shorter than the 900 s billing quarter could tell that from
# a fault. At 400 W and above the worst legitimate episode collapses to 5.0
# s, ONE control cycle, and stays there. So this number is not a sensitivity
# preference; it is the edge of the regime in which the guard is
# answerable at all.
#
# 700 W is 1.75x the knee, and the margin is bought for one named reason:
# INVERTER B DOES NOT PHYSICALLY EXIST. Its ramp and lag in the rig are
# inverter A's, COPIED, carrying `measured=False` - SPIKE-04 measures the
# real ones. A slower or faster second unit moves the transient's shape, and
# the headroom above the knee is what absorbs that without re-opening this
# card. Revisit it when SPIKE-04 lands, not before.
#
# What it costs: a circulating loop smaller than 350 W per unit is not
# reported. That is deliberate - at that scale the round-trip loss is a few
# watts and the wear is proportionate to it.
"circulation_w": 700,
# --- THE WINDOW -------------------------------------------------------
# Two lower bounds, one upper, and the chosen value clears all three.
#
# LOWER, from the rig: 5.0 s. The worst continuous legitimate opposition
# above 700 W across all 924 runs is exactly one control cycle - a
# reversing site whose second write lands a cycle after the first, which
# is what the serialised write path does on every reversal.
#
# LOWER, from the firmware: `inverter.LINK_STALE_S`, 30 s. A unit still
# executing a stale share for less than that is a LINK fault, and the
# add-on already has an answer for it - liveness drops the unit and the
# survivors carry its share, with the record saying so. Firing inside that
# window would raise a second, louder alarm about a state that is already
# being handled, which is the SAFETY-15/SAFETY-19 failure exactly.
#
# UPPER, from the bill: 900 s, the quarter that sets the capacity tariff.
# A circulating loop must be caught and acted on well inside one.
#
# 75 s: fifteen control cycles - 15x the worst legitimate episode this rig
# can produce, 2.5x the firmware's own veto window, and 12x inside the
# quarter. ⚠️ IT IS DELIBERATELY NOT 60 OR 120. A round number here would be
# a guess wearing a measurement's clothes, and the three bounds above are
# what the number has to answer to.
"circulation_hold_s": 75,
}
@dataclass(frozen=True)
class CirculationConfig:
"""Defaults, not constants - config.yaml carries both. See CFG-03 above."""
min_w: float = float(CIRC_OPTION_DEFAULTS["circulation_w"])
hold_s: float = float(CIRC_OPTION_DEFAULTS["circulation_hold_s"])
def circulating_w(powers):
"""`sum(|B_i|) - |sum(B_i)|` over MEASURED per-inverter power, in W.
`powers` one measured power per inverter, in roster order, + = discharge.
A unit whose reading did not arrive is `None`.
Returns a non-negative float, or `None` when the answer is unknown.
⚠️ N<=1 IS IDENTICALLY ZERO AND RETURNS ZERO EVEN FOR A MISSING READING
(AC 5). With one term `sum(|B|) - |sum(B)| == |B| - |B| == 0` for EVERY
value of B, including a value nobody read. Returning `None` there would be
reporting an unknown where the algebra has no room for one, and it would put
a shipped one-inverter install permanently in the "cannot tell" state on a
quantity that cannot be anything but zero. Nothing changes at the shipped
roster; that is the compatibility promise this card makes.
⚠️ AND AT N>=2 A MISSING READING IS `None`, NOT ZERO, WHICH IS THE OPPOSITE
DIRECTION AND FOR A REASON. Zero would be this sensor reporting HEALTH from
an absence - the precise shape of the 2026-09-02 outage, where a subsystem
stopped answering and its silence read as calm for 6 h 25 m. An unknown
circulating figure is an unknown, it CLEARS the trip's window rather than
accumulating it (see `CirculationWatchdog.evaluate`), and the site is
already stopped for a missing per-unit reading anyway - `inputs_ok` requires
every unit's `batt`, and §11.1 rule 1 commands 0 W without consulting this.
"""
vals = list(powers)
if len(vals) <= 1:
return 0.0
if any(v is None for v in vals):
return None
vals = [float(v) for v in vals]
# ⚠️ max(0.0, ...) IS DEFENSIVE, AND IT IS AN EQUIVALENT MUTANT - SAID HERE
# RATHER THAN LEFT FOR THE NEXT MUTATION SWEEP TO REDISCOVER. The triangle
# inequality makes this non-negative mathematically, and in floating point
# it is non-negative too: for a same-sign roster `abs(v)` is the list itself
# up to one sign, so the two sums accumulate THE SAME MAGNITUDES IN THE SAME
# ORDER and are bit-identical; for a mixed-sign roster the two differ by
# 2*min(...), which is enormous beside any rounding. Searched, not assumed -
# 700 000 random rosters of 2 to 12 units across 10 orders of magnitude
# produced no negative result.
#
# So removing this line changes no observable and no check here would go
# red. It stays because the cost is one call and the failure it would
# prevent - a power sensor publishing -1e-16 W, which is the kind of value
# somebody eventually writes a `< 0` branch against - is out of proportion
# to it. Do not report its survival as a gap in the checks.
return max(0.0, sum(abs(v) for v in vals) - abs(sum(vals)))
def opposing(powers, min_w: float = 0.0):
"""The units pulling each way right now, as `(discharging, charging)` names.
Indices, not names - the caller owns the roster order. Used for the operator
sentence: "which two inverters are pushing against each other" is the first
thing somebody woken by this alarm needs, and reconstructing it from the
number alone is impossible.
`min_w` ignores units below a magnitude, so a unit resting at 3 W of
standby draw is not named as a participant in a 3 kW loop.
"""
pos = [i for i, v in enumerate(powers)
if v is not None and float(v) > float(min_w)]
neg = [i for i, v in enumerate(powers)
if v is not None and float(v) < -float(min_w)]
return pos, neg
class CirculationWatchdog:
"""ONE PER SITE, evaluated once per control cycle.
⚠️ ONE PER SITE, WHERE SAFETY-02's IS ONE PER ACTUATOR, AND THE ASYMMETRY IS
THE WHOLE ATTRIBUTION ARGUMENT. `SignWatchdog` concludes "THE UNIT I AM
DRIVING is pushing power the wrong way" - evidence about one actuator, so
the remedy is that actuator (arbiter.CLAIM_SCOPE calls `failsafe` a UNIT
claim for exactly this reason). Circulating power is not a property any one
inverter has. It is a property of a PAIR, it is defined by a sum across the
roster, and there is no fact of the matter about which of the two is the
offender: a unit ignoring its share and a sibling faithfully executing a
share computed to sum with it produce identical readings. So the quantity is
site-level, the watchdog is site-level, and the remedy below is site-level.
Latches, for `SignWatchdog`'s reason: the trip removes its own evidence. The
moment the site stops commanding, the loop it detected either persists (a
wedged unit, now visible at the meter) or vanishes (the add-on was one of
the two participants) - and in the second case a non-latching detector would
de-assert and start the whole thing again, three minutes at a time, forever.
"""
def __init__(self, cfg: CirculationConfig | None = None, *,
tripped: bool = False, reason: str = ""):
self.cfg = cfg or CirculationConfig()
self.over_since: datetime | None = None
# ⚠️ RESTORED FROM THE STORE, NOT DEFAULTED - SAFETY-34, and it is the
# reason this card exists in the shape it does. `persistent_notification`
# is IN MEMORY: Home Assistant restarts and the card is gone, with the
# fault still running. That is precisely how the 2026-09-02 outage went
# unseen for 6 h 25 m while the detector had been correct for hours. The
# latch lives in `/data/state.json` - the add-on's only durable volume -
# and `main.py` RE-RAISES the notification from it on every start.
self.tripped = bool(tripped)
self.reason = reason if self.tripped else ""
# The worst figure seen during the current episode, for the operator
# sentence. Not persisted: it is colour on a reason string that IS.
self.peak_w = 0.0
def evaluate(self, circ_w, now: datetime) -> bool:
"""Advance the detector one cycle. Returns True while tripped.
`circ_w` this cycle's `circulating_w()` over MEASURED per-unit power,
or None when a reading is missing. None CLEARS the window
rather than accumulating it - see the module docstring, and
`SignWatchdog.evaluate` on the identical decision for a stale
meter. A frozen figure held against a moving one manufactures
a fault in about a window's worth of cycles.
`now` the caller's clock, so this is testable and replayable.
"""
if self.tripped:
# Latched. Do not re-evaluate: the trip removed the evidence.
return True
if circ_w is None or float(circ_w) <= self.cfg.min_w:
self.over_since = None
self.peak_w = 0.0
return False
circ_w = float(circ_w)
self.peak_w = max(self.peak_w, circ_w)
if self.over_since is None:
self.over_since = now
return False
held = (now - self.over_since).total_seconds()
if held < self.cfg.hold_s:
return False
self.tripped = True
self.reason = (
f"CIRCULATING_POWER: {circ_w:.0f} W measured going round between "
f"the inverters (peak {self.peak_w:.0f} W) for {held:.0f} s "
f"continuously - the meter cannot see it, because it nets to zero "
f"there (limits: over {self.cfg.min_w:.0f} W, held over "
f"{self.cfg.hold_s:.0f} s)")
return True
def held_s(self, now: datetime) -> float:
"""How long the current opposition has stood, for the status page.
Takes the clock rather than reading one, for `SignWatchdog.held_s`'s
reason: every observable on this object is a pure function of what it
was handed, and an unclocked function is one nothing can test.
"""
if self.over_since is None:
return 0.0
return (now - self.over_since).total_seconds()
def reset(self) -> None:
self.over_since = None
self.tripped = False
self.reason = ""
self.peak_w = 0.0
+418
View File
@@ -0,0 +1,418 @@
"""One inverter, as an OBJECT rather than as a set of Controller scalars.
WHAT THIS FIXES, in one sentence: every piece of per-device state in this
add-on used to be a single scalar on the Controller, and several of those
scalars are SAFETY INPUTS - so a second inverter would have been graded against
the first one's numbers.
The scalars, and what each one was silently asserting:
`dev_min` / `dev_max` ONE pair, read from ONE `setpoint_entity`. A second
inverter's rating was never read at all, so its clamp,
its freeze rail and the peak guard's `achievable_w`
were all inverter A's.
`soc` ONE state of charge into the maintenance FSM,
SAFETY-24's pack floor and arbitrage's bounds. An
average lets the emptier pack be driven below its own
floor; a maximum parks the fuller one.
`batt` ONE battery power into the anti-windup saturation
detector - see the SITE/UNIT note at the bottom of
this docstring, because this one goes the OTHER WAY.
`sign_wd` ONE SignWatchdog, whose own docstring says "one
instance per actuator", latched under FLAT store keys.
A trip caused by B latched A across restarts and one
operator action cleared both.
`last_write` ONE write bookkeeping, and ONE serialised `hass.call()`
behind it: a hung write to A ate B's 30 s layer-1
budget.
⚠️ WHAT IS DELIBERATELY *NOT* HERE, AND IT IS THE HALF THAT IS EASY TO GET
BACKWARDS. THERE IS NO `Tuning` ON THIS OBJECT AND THERE IS NO INTEGRATOR.
§6.2 and ALLOC-01's stability argument are ONE integrator on P1, ABOVE the
split: the site target S is divided into per-unit shares, so the gain seen at
the meter is a CONVEX COMBINATION of the per-unit gains and a bad split cannot
destabilise the site. Give each inverter its own `Tuning` and somebody will
eventually call `compute()` with it, and the moment two integrators regulate
one meter the whole argument is gone - that is the two-writers failure the
arbiter exists to prevent, one level up.
The one field of `Tuning` that genuinely IS per-device is `max_w`, the
supervised cap on what may be WRITTEN to one setpoint entity (§11.3), and it is
here as `max_w`. The SITE `Tuning` the loop runs on takes its bound from the
roster - `sum(inv.max_w)` - so at N=1 it is byte-identical to the shipped
number and at N>=2 it is what the site can actually deliver. That is the whole
of "the rating stops being a scalar"; a per-unit Tuning would be three more
numbers nobody reads and one more place a limit has to be kept in step (CFG-03
already tracks three).
------------------------------------------------------------------------------
SITE OR UNIT? THE TWO HALVES OF THE N=1 IDENTITY, AND THEY MOVE IN OPPOSITE
DIRECTIONS
At N=1 §6.2's identity holds: the fabricated grid reading and the battery
setpoint are the same number, so "the site" and "the inverter" are the same
thing and every scalar above was RIGHT. Splitting them is not one change, it is
two, and they point opposite ways:
COMMANDING becomes per-unit. One setpoint entity per inverter, one rating,
one clamp, one watchdog, one heartbeat.
SENSING, for the loop, becomes SITE. `compute()` regulates the METER. Its
`actual_w` is the anti-windup input to
`abs(prev_w - actual_w) > saturation_w`, where
`prev_w` is the SITE target. Feed it ONE unit's
power at a roster of two and that test compares
a site number against a unit number, trips the
freeze permanently and leaves a standing grid
error.
That second half is MEASURED, not argued. On admin/goodwe's two-master rig
(`tools/alloc_sim.py --splits --feedback unit`), with the loop fed one
inverter's power the aggregate trace at the meter becomes a function of the
split - up to 510 W apart at gain 0.2, 250 W at gain 0.4, 50 W at gain 0.6 -
while the allocator's shares sum to S in every one of those runs. The
counterfactual is the proof: change that ONE input to the site total and every
split is bit-identical at every gain the schema accepts. ALLOC-01's review
isolated it and test_alloc.py part 8 graded it as a disclosed defect waiting on
this card.
So this object owns `batt` - THIS inverter's own power, which is what a
per-unit consumer needs - and the Controller sums them into the site figure the
loop is fed. Getting that backwards reintroduces the divergence.
------------------------------------------------------------------------------
LIVENESS, AND WHY IT IS A METHOD WITH A REASON
`Controller.live_units()` decides which inverters may be commanded this tick,
and `allocator.plan()` DROPS what it does not list - the survivors then carry
the whole site target. A wrong answer there is a real change in what the site
can deliver, so `is_live()` answers one question and says which: CAN THIS
CONTROLLER PUT A NUMBER ON THIS INVERTER RIGHT NOW.
ONE way it cannot, and exactly one: every write has been REJECTED for a whole
`LINK_STALE_S` window. Not one rejection - `hass.set_number()` returns False for
a transient 400 as readily as for a device that has gone - but a continuous run
of them with no acceptance in between.
⚠️ AND NOT "IT HAS NO `setpoint_entity`", THOUGH THAT IS ALSO A UNIT THIS
CONTROLLER CANNOT COMMAND. The two look the same and want opposite answers. A
link that WAS working and stopped is an event: the survivors carry its share,
the record says so, and the site goes on running at reduced strength, which is
the best available outcome. A roster entry with no writer configured at all is a
CONFIGURATION that cannot be delivered - it was never reachable, nothing has
gone wrong on the wire, and quietly running the site at part strength on a
roster somebody wrote down wrong is how a half-driven site reads as healthy on
every dashboard. That one belongs to main.py's refusal branch, which commands
0 W and NAMES the inverter; putting it here would absorb it into the ordinary
drop and delete the last trigger that branch has. See `Controller.cycle()`.
⚠️ AND NOT "ITS SENSORS ARE MISSING" EITHER. A pack whose SoC did not answer is
a third fault with a third remedy: `inputs_ok` already stops the whole site at
P_SAFETY for that, and dropping the unit from the SPLIT instead would hand its
share to a sibling while the site kept regulating - the opposite of what a
missing measurement should cause. Liveness is about the WRITE PATH, and only
about a write path that has stopped answering.
"""
import math
from datetime import datetime
from .clamp import ClampResult
from .store import unit_key
from .watchdog import SignWatchdog, SignWatchdogConfig
# How long every write to one inverter must have been REJECTED before this
# controller stops claiming it can command it.
#
# ⚠️ IT IS LAYER 1'S OWN WINDOW, NOT A NEW OPINION ABOUT LINKS. The ESP32
# commands 0 W and keeps commanding it after ~30 s without a refresh
# (`validate.FIRMWARE_INGEST_VETO_S`), so a link this controller has not been
# able to write for a whole 30 s is a link the hardware is about to take away
# from it anyway. Claiming it as commandable past that point is the add-on
# telling the allocator it can deliver watts that the firmware has already
# decided it will not. No config key: CFG-03 tracks three places a default has
# to be kept in step and this does not earn a fourth - it is derived from a
# constant the firmware and validate.py already share.
LINK_STALE_S = 30.0
# The name of the inverter a SINGLE-INVERTER config describes. ⚠️ A NAME, NOT A
# CONFIGURATION - it exists so that a per-inverter claim has an actuator to be
# filed ON, which is what makes the site/unit split something a check can grade
# rather than a comment. It lives here rather than in main.py now that the
# roster does.
#
# ⚠️ CFG-04 DID NOT MAKE THIS "THE FIRST ONE". It is the name the flat-keys path
# gives its one unit, and nothing else; a declared `inverters:` roster names its
# own entries and this constant is not consulted. The store migration
# (`migrate_unit_keys`) still targets it, because the flat pre-DEV-02 keys can
# only ever have belonged to a single-inverter install.
UNIT_A = "inverter-a"
# The per-unit keys this object keeps in the Store, namespaced by unit name.
# ⚠️ THE VALUES ARE THE PRE-DEV-02 FLAT KEY NAMES, and that is what makes the
# migration mechanical rather than transcribed: `store.migrate_unit_keys()`
# reads this same mapping, so a key renamed here cannot silently stop being
# migrated. See store.py.
UNIT_STORE_KEYS = ("sign_tripped", "sign_reason")
class Inverter:
"""ONE inverter: its entities, its rating, its watchdogs, its store keys.
Constructed once per configured inverter and held in `Controller.inverters`.
Everything on it is about THIS device; nothing on it is about the site.
⚠️ `hass` IS NOT A CONSTRUCTOR ARGUMENT. This object is built in
`Controller.__init__`, which runs before any I/O and, in four existing
checks, with `hass=None` entirely. The device range is read LATER, by
`Controller.run_control()`, from THIS unit's own `setpoint_entity` - which
is the whole of "each instance's rating is read from its own entity".
"""
def __init__(self, name, *, setpoint_entity="", soc_entity="",
batt_entity="", batt_invert=False, max_w=2000.0,
store=None, sign_cfg=None):
self.name = str(name)
self.setpoint_entity = str(setpoint_entity or "")
self.soc_entity = str(soc_entity or "")
self.batt_entity = str(batt_entity or "")
self.batt_invert = bool(batt_invert)
# The supervised cap on what may be written to THIS setpoint entity.
# See the module docstring on why this is a number and not a `Tuning`.
self.max_w = float(max_w)
# --- the device's own reported range, read from its own entity -------
# None until `hass.limits()` has answered. NOT guessed at: ESPHome is
# often not up when the add-on boots, and (None, None) is the honest
# report that the range checks were skipped rather than invented.
self.dev_min = None
self.dev_max = None
# --- this unit's own measurements ------------------------------------
self.soc = None
self.batt = None
# --- what this unit was last told, and what it last accepted ---------
# `target` is THIS unit's share of the site target from the last
# resolution - the number its heartbeat re-emits and the number
# SAFETY-02 grades against the meter. At N=1 it IS the site target,
# because the allocator is a pass-through there.
self.target = 0.0
self.last_write = None
self.last_write_at = None
self.last_write_ok = None
# ⚠️ TWO TIMESTAMPS, NOT ONE FLAG. `last_write_ok` is the last write's
# verdict and it flips on a single transient 400; liveness needs a RUN
# of rejections, so `rejected_since` records when the current run
# started and is cleared by any acceptance.
self.rejected_since = None
# The heartbeat's own deadline, on the event loop's monotonic clock.
# ⚠️ PER UNIT, WHICH IS THE WHOLE OF AC 6. One shared `last_beat` and
# one serialised write meant a hung call to A pushed B's refresh past
# layer 1's ~30 s veto - i.e. one inverter's transport fault zeroing a
# healthy sibling. Starts at 0.0, which is what the single scalar did.
self.last_beat = 0.0
# --- SAFETY-03's per-write evidence ----------------------------------
# What THIS unit's last write clamped, or None before it has run. The
# ALARM (`ClampWatchdog`) stays one per controller - clamp.py says so in
# its own docstring, and it is an anti-flood counter over an event bus
# rather than a property of a device - but the EVIDENCE is per unit,
# because a clamp on B says nothing about A.
self.clamp_last: ClampResult | None = None
# --- SAFETY-02, one instance per actuator, under NAMESPACED keys -----
# ⚠️ THE WATCHDOG'S OWN DOCSTRING SAID "one instance per actuator" WHILE
# THE CONTROLLER HELD EXACTLY ONE. Restored from THIS unit's own keys,
# so a trip caused by B latches B and leaves A commanding - and an
# operator clearing one does not silently clear the other.
self.store = store
data = getattr(store, "data", {}) if store is not None else {}
self.sign_wd = SignWatchdog(
sign_cfg or SignWatchdogConfig(),
tripped=bool(data.get(self.key("sign_tripped"), False)),
reason=str(data.get(self.key("sign_reason"), "") or ""))
# -- store ---------------------------------------------------------------
def key(self, name: str) -> str:
"""This unit's namespaced Store key for `name`. See store.unit_key()."""
return unit_key(self.name, name)
def store_set(self, name: str, value) -> None:
if self.store is not None:
self.store.set(self.key(name), value)
# -- the numbers other modules ask this object for -----------------------
def rating_w(self) -> float:
"""The largest magnitude this unit can be commanded, in W.
`min(max_w, |dev_min|, |dev_max|)` - the supervised cap and whatever the
device itself reports, whichever is smaller. It is the same conjunction
`freeze.rail_ceiling_w()` computes for the freeze rail and the same one
main.py hands the peak guard as `achievable_w`, which is why it is
written once here: three transcriptions of a rating is three chances for
inverter B to be graded against inverter A's number.
A bound that could not be read is SKIPPED, not treated as zero: (None,
None) means ESPHome was not up, and answering 0 W there would say this
inverter can do nothing.
"""
out = abs(float(self.max_w))
for bound in (self.dev_min, self.dev_max):
if bound is not None and math.isfinite(float(bound)):
out = min(out, abs(float(bound)))
return out
def has_writer(self) -> bool:
return bool(self.setpoint_entity)
# -- liveness ------------------------------------------------------------
def note_write(self, ok: bool, now: datetime) -> None:
"""Record one write's verdict. The only thing that moves liveness."""
self.last_write_ok = bool(ok)
if ok:
self.rejected_since = None
elif self.rejected_since is None:
self.rejected_since = now
def is_live(self, now: datetime, stale_s: float = LINK_STALE_S):
"""`(live, why_not)` - may this controller command this unit THIS TICK?
Read the module docstring before widening this - in particular on why a
unit with NO `setpoint_entity` is deliberately still "live" here and is
refused one layer up instead. The allocator DROPS what `live_units()`
does not list and the survivors carry the whole site target, so a false
"not live" is a site target divided among fewer inverters than exist -
and at a roster of one it is the allocator refusing outright and the
site commanding 0 W.
⚠️ ANSWERED PER TICK, NEVER CACHED, for `allocator.plan()`'s reason: a
link goes stale between one cycle and the next.
"""
if self.rejected_since is not None:
held = (now - self.rejected_since).total_seconds()
if held >= float(stale_s):
return False, (f"every write rejected for {held:.0f} s "
f"(limit {float(stale_s):.0f} s)")
return True, ""
def link_note(self, now: datetime) -> str:
"""One line for the status page. Empty when there is nothing to say."""
if not self.has_writer():
return (f"{self.name}: NO SETPOINT ENTITY - this controller cannot "
f"command it, and the site refuses rather than running at "
f"part strength")
live, why = self.is_live(now)
if not live:
return f"{self.name}: NOT COMMANDABLE - {why}"
if self.rejected_since is not None:
held = (now - self.rejected_since).total_seconds()
return (f"{self.name}: writes rejected for {held:.0f} s - still "
f"commandable until {LINK_STALE_S:.0f} s")
return ""
def __repr__(self) -> str:
return (f"<Inverter {self.name} sp={self.setpoint_entity!r} "
f"max_w={self.max_w:.0f} dev=({self.dev_min}, {self.dev_max})>")
def roster_entries(opts: dict) -> list:
"""The `inverters:` option, normalised to a list of dicts. Never None.
Separate from `build_roster()` because validate.py needs to grade the SAME
list this builds from, and a second transcription of "what counts as an
entry" is a second answer to it. A non-list, or a list with non-dict
members, comes back as it was so the validator can name what it found -
dropping the junk here would hand the validator a clean list and a config
nobody refused.
"""
entries = opts.get("inverters")
if entries is None or entries == "":
return []
if not isinstance(entries, (list, tuple)):
return [entries]
return list(entries)
def build_roster(opts: dict, store, sign_cfg=None) -> list:
"""The site's inverters, in roster order.
TWO SHAPES, AND WHICH ONE IS IN FORCE IS DECIDED BY ONE TEST: is
`inverters:` empty?
EMPTY the five flat keys - `setpoint_entity`, `soc_entity`,
`batt_entity`, `batt_invert`, `max_w` - describe the ONE inverter,
exactly as the shipped scalars did. This is what every install
that upgrades into this version reads, without an operator
touching anything, and it is byte-identical to what DEV-02
shipped. config.yaml's default is `[]` for precisely that reason,
and Supervisor 2026.08.0 refuses the whole options blob without
it - see the options-block note on `inverters:`.
NON-EMPTY each entry describes one inverter and the flat keys describe
none of them. ⚠️ NOTHING IS INHERITED. An entry that omits
`soc_entity` has no SoC sensor; it does NOT borrow the flat one,
because "this unit's number came from somewhere else" is the
defect DEV-02 spent a card removing and a fallback here would
rebuild it in three lines. `name`, `setpoint_entity` and `max_w`
are required of every entry - the schema enforces it on the
Supervisor path, `validate.py` rule 9 enforces it for sim/inject.py
and the checks, which reach this function with any dict at all.
⚠️ THIS FUNCTION REFUSES NOTHING, AND THAT IS ON PURPOSE. A refusal here
happens inside `Controller.__init__`, before the startup gate has run and
before anything can render the reason to an operator; validate.py's rule 9
is the place that says no, with a message, through `refuse()`. So this
builds the most honest roster it can out of whatever it was handed - a
missing name becomes a positional one, a missing rating becomes 0.0 W - and
every one of those states is something rule 9 has already refused by the
time a control loop exists. Keep the two in step: a shape this tolerates
that rule 9 does not name is a shape that runs.
"""
entries = roster_entries(opts)
if not entries:
# ⚠️ THE UNCHANGED PATH. Same name, same entities, same rating, same
# store keys as before CFG-04 - an install that upgrades reads
# identically, which is AC 3.
return [Inverter(
UNIT_A,
setpoint_entity=opts.get("setpoint_entity", ""),
soc_entity=opts.get("soc_entity", ""),
batt_entity=opts.get("batt_entity", ""),
batt_invert=bool(opts.get("batt_invert")),
max_w=float(opts.get("max_w", 2000)),
store=store, sign_cfg=sign_cfg)]
roster = []
for i, entry in enumerate(entries):
entry = entry if isinstance(entry, dict) else {}
# ⚠️ THE FALLBACK NAME IS POSITIONAL, NOT `UNIT_A`. Two nameless entries
# both called `inverter-a` would share one Store namespace, so one
# unit's SAFETY-02 latch would be the other's - a fault on B latching A
# is the exact failure DEV-02's namespaced keys removed. Rule 9 refuses
# a nameless entry outright; this only decides what the refusal is
# allowed to call it in the meantime.
name = str(entry.get("name") or "").strip() or f"inverter-{i + 1}"
roster.append(Inverter(
name,
setpoint_entity=entry.get("setpoint_entity", ""),
soc_entity=entry.get("soc_entity", ""),
batt_entity=entry.get("batt_entity", ""),
batt_invert=bool(entry.get("batt_invert")),
# ⚠️ NOT `opts["max_w"]`. See the docstring: a rating an entry did
# not state is not the flat one, it is a rating rule 9 refuses.
max_w=_entry_max_w(entry),
store=store, sign_cfg=sign_cfg))
return roster
def _entry_max_w(entry: dict) -> float:
"""One entry's supervised cap, or 0.0 when it did not state a usable one.
0.0 rather than a borrowed number, and rather than an exception: rule 9
refuses `max_w` missing or unparseable by name, and a roster that cannot be
built at all would refuse it with a traceback instead.
"""
try:
return float(entry.get("max_w"))
except (TypeError, ValueError):
return 0.0
File diff suppressed because it is too large Load Diff
+309 -16
View File
@@ -18,16 +18,47 @@ OWNERSHIP, not priority. Exactly one thing writes the setpoint at any moment:
The loop is never "disabled" - it yields. The heartbeat to the inverter keeps
running in every phase, so the hardware watchdog stays fed and a crash here
still ends with the inverter at 0 W rather than latched.
ONE PACK AT A TIME (MAINT-05). There is now one `Maintenance` per roster entry,
each with its own schedule, its own phase and its own history under its own
Store keys - and therefore, for the first time, two of them able to move power
on ONE grid connection at once. Read `arbitrate()` before touching any of it:
the site holds exactly ONE maintenance slot, a pack that is not IDLE holds it,
and every other pack is held at IDLE under the loop until it is released. That
is not a scheduling nicety. A drain of pack A against a charge of pack B is two
power-moving phases pulling opposite ways across the meter - the circulating
power SAFETY-31 exists to DETECT, arriving here as something this module can
simply not do.
"""
import logging
import math
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
from .store import MAINT_UNIT_KEYS, unit_key
_LOG = logging.getLogger("goodwe.maint")
IDLE, DRAIN, CHARGE, HOLD = "idle", "drain", "charge", "hold"
# ⚠️ THE PHASES THAT MOVE POWER, WHICH IS NOT THE SAME LIST AS "owns the
# setpoint". The table above is about WHO WRITES the number; this is about
# whether the pack is being pushed. DRAIN and HOLD own the setpoint. CHARGE does
# NOT - the loop owns it - and CHARGE is in here anyway, because the charge-only
# clamp plus the cheap-window floor is what pulls a second pack full while the
# first is being emptied. Leaving CHARGE out is precisely the interlock hole
# this card is about: pack A charging from the grid at 2000 W while pack B
# drains 2000 W to export is 4 kW going round in a circle with the meter at
# zero, and both packs believing they are behaving.
#
# HOLD commands 0 W and moves nothing, and it is in here for the other half of
# the sentence: it OWNS the actuator - the pack is parked at the top for the BMS
# and is deliberately not available to the loop - so a second cycle starting
# under it would still be two recalibrations at once, which is the thing whose
# value is a clean uninterrupted coulomb count.
POWER_MOVING = (DRAIN, CHARGE, HOLD)
# A drain of a 13.8 kWh usable pack (300 Ah x 51.2 V, DoD 90) at the shipped
# 2000 W is ~6.9 h even with no house load helping - and less in practice, since
# house load drains alongside the export and soc_floor stops short of empty.
@@ -153,17 +184,102 @@ class MaintResult:
setpoint_w: float | None = None
charge_only: bool = False
events: list = field(default_factory=list)
# ⚠️ WHY A DEFERRAL IS A FIELD AND NOT JUST A LOG LINE. A pack that is due
# and is not starting looks, from every surface an operator has, exactly
# like a pack whose schedule has quietly stopped firing - §12's opening
# sentence, the failure this whole module exists because of. It is carried
# so the status page can SAY "waiting for the other pack" rather than
# showing an idle machine and a due date in the past. Empty on every path
# that is not deferring, so a roster of one never sees it.
deferred: str = ""
class UnitHistory:
"""One pack's maintenance history in the Store, under one spelling.
⚠️ THE NAMESPACE IS A CONSTRUCTOR ARGUMENT AND `None` IS A REAL VALUE, NOT
AN OMISSION. `unit=None` means the FLAT keys - `phase`, `phase_started`,
`last_completed`, `last_start_attempt` - which is what every install has
written since the add-on shipped and what a one-inverter site keeps writing
after MAINT-05. §6.2's identity: with one pack there is nothing for a
namespace to distinguish it FROM, and adding one would change the layout of
a live state file to say something it already said. `arbiter.actuator_for()`
makes the same move for the same reason and its docstring argues it.
⚠️ `mirror_flat` IS THE ROLLBACK VIEW AND IT IS ONLY EVER THE FIRST PACK'S.
At N>=2 pack A's history has been migrated into its namespace and is written
there; the flat keys are ALSO kept in step, so an operator who rolls the
add-on back to a single-FSM version finds a CURRENT history rather than one
dated the day the second inverter was declared. store.migrate_maint_keys()
carries the argument, and it is DEV-02's rule 2 applied to history instead
of to a latch: "left in the file" is not the same promise as "still true".
Pack B has no flat spelling to mirror to - the flat keys mean pack A on
every install that has them - so it is constructed with mirroring off, and
a mirror from B would OVERWRITE A's rollback view with B's phase.
"""
def __init__(self, store, unit: str | None = None, mirror_flat: bool = False):
self.store = store
self.unit = unit
self.mirror_flat = bool(mirror_flat)
def key(self, name: str) -> str:
"""The Store key this pack's `name` lives under."""
return name if self.unit is None else unit_key(self.unit, name)
def get(self, name: str, default=None):
return getattr(self.store, "data", {}).get(self.key(name), default)
def set(self, name: str, value) -> None:
self.store.set(self.key(name), value)
if self.mirror_flat:
self.store.set(name, value)
def get_time(self, name: str):
return self.store.get_time(self.key(name))
def set_time(self, name: str, when) -> None:
self.store.set_time(self.key(name), when)
if self.mirror_flat:
self.store.set_time(name, when)
class Maintenance:
def __init__(self, cfg: MaintConfig, store):
"""ONE pack's recalibration cycle: its schedule, its phase, its history.
⚠️ ONE PER ROSTER ENTRY SINCE MAINT-05, AND THE SLOT IS NOT ITS OWN. This
object decides WHEN ITS PACK would like to start; `arbitrate()` decides
which of them may, because the constraint is a property of the grid
connection and no single FSM can see it. Never call `tick()` in a loop
without passing the `blocked_by` that `arbitrate()` returned for it: that is
the two-packs-at-once bug with the interlock present but not wired.
"""
def __init__(self, cfg: MaintConfig, store, unit: str | None = None,
name: str = "", mirror_flat: bool = False):
self.cfg = cfg
self.store = store
# ⚠️ `self.store` IS THE VIEW, NOT THE Store. Everything in this class
# names an UNQUALIFIED key - "phase", "last_completed" - and the view is
# the one place that turns it into the key this pack owns. A raw
# `store.set("phase", ...)` anywhere below would write pack A's history
# from pack B's state machine, which is the shared-state bug this card
# is about, and there would be nothing to see at a roster of one.
self.store = UnitHistory(store, unit, mirror_flat)
self.unit = unit
# What an event or a refusal calls this pack. At a roster of one it is
# never rendered - a single machine cannot be deferred - so the shipped
# one-inverter reason strings are untouched.
self.name = str(name or unit or "the pack")
# Edge-memo for the deferral note. The action log holds 40 lines and a
# deferral lasts as long as the other pack's cycle - hours - so a line
# per cycle would flush the very context that explains it. Same pattern
# as `Controller._arb_action` and `_maint_shape_suspended`.
self._deferred = ""
# -- state ---------------------------------------------------------------
@property
def phase(self) -> str:
return self.store.data.get("phase", IDLE)
return self.store.get("phase", IDLE)
def _enter(self, phase: str, now: datetime, events: list, msg: str) -> None:
self.store.set("phase", phase)
@@ -185,14 +301,60 @@ class Maintenance:
last = self.store.get_time("last_completed")
return None if last is None else last + timedelta(days=self.cfg.interval_days)
def waited_days(self, now: datetime) -> float:
"""Days since this pack last COMPLETED a cycle; `inf` if it never has.
⚠️ THE ARBITRATION KEY, AND IT IS DELIBERATELY NOT `due()`. `due()` is a
yes/no and two packs that are both due are indistinguishable by it -
which is how a roster-order tie-break gets written and how the first
entry then wins every contested month forever while the second drifts.
This is an ORDERING: the pack whose coulomb counter has gone longest
without a recalibration goes first. `inf` for never-recalibrated is the
same statement `due()` makes about an absent `last_completed`, kept as
one so a fresh pack cannot lose to one that ran last month.
"""
last = self.store.get_time("last_completed")
return math.inf if last is None else (now - last).total_seconds() / 86400.0
def _cooled(self, now: datetime) -> bool:
"""Is the post-abort cooldown over?"""
last_try = self.store.get_time("last_start_attempt")
return (last_try is None
or (now - last_try) >= timedelta(minutes=RESTART_COOLDOWN_MIN))
def wants_start(self, now: datetime) -> bool:
"""Would this pack begin a cycle on this tick if the site let it?
⚠️ THE SAME PREDICATE `tick()` USES, NOT A COPY OF IT. `arbitrate()` has
to know who is asking before anybody moves, and a second transcription
of "enabled, in the start hour, due and cooled down" is a second opinion
about who was asking - so the IDLE branch of `tick()` calls this one.
"""
return (self.phase == IDLE and self.cfg.enabled
and now.hour == self.cfg.start_hour and self.due(now)
and self._cooled(now))
# -- operations ----------------------------------------------------------
def force_start(self, now: datetime) -> list:
def force_start(self, now: datetime, blocked_by: str = "") -> list:
"""Start a cycle regardless of the calendar.
Commissioning uses this: a cycle must be proven end to end before a site
is signed off, and nobody waits a month to find out the schedule never
fires.
⚠️ REGARDLESS OF THE CALENDAR, NOT REGARDLESS OF THE INTERLOCK. The
calendar is a preference and an operator may overrule it; "one pack
moves power at a time" is a property of the grid connection and an
operator pressing a button does not add a second one. A forced start
against a busy site is REFUSED, by name, and the phase machine does not
move - the refusal is returned as an event so the operator reads it in
the action log rather than watching nothing happen.
"""
if blocked_by:
msg = (f"maintenance: forced start REFUSED on {self.name} - "
f"{blocked_by}")
_LOG.warning("%s", msg)
return [msg]
events = []
self.store.set_time("last_start_attempt", now)
self._enter(DRAIN, now, events, "maintenance: forced start -> drain")
@@ -203,23 +365,80 @@ class Maintenance:
self._enter(IDLE, now, events, f"maintenance: ABORT ({why})")
return events
def _defer_note(self, why: str, events: list) -> list:
"""Say once, not every second, that this pack is waiting its turn.
⚠️ THE WORDING IS DELIBERATELY NOT AN ABORT AND NOT A TIMEOUT. §12's
notes are explicit that a 12 h phase timeout means "the battery is not
following commands - a FAULT, not a slow day", and the one thing that
must not happen here is an operator reading a deferral as that. This
line says the pack is WAITING, names the pack it is waiting for, and
says it will run next - none of which any failure path in this module
says.
"""
if self._deferred != why:
self._deferred = why
msg = (f"maintenance: {self.name} is due and is WAITING its turn - "
f"{why}. It is idle under the control loop and will "
f"recalibrate at the next start hour once the slot is free; "
f"this is not a stalled phase.")
_LOG.info("%s", msg)
events.append(msg)
return events
# -- the machine ---------------------------------------------------------
def tick(self, now: datetime, soc: float | None) -> MaintResult:
def tick(self, now: datetime, soc: float | None,
blocked_by: str = "") -> MaintResult:
"""One cycle of this pack's state machine.
`blocked_by` is `arbitrate()`'s answer for THIS pack: empty when the
site's one maintenance slot is available to it, otherwise the reason it
is not. It gates two things and nothing else - a start, and a phase that
is already moving power on a pack that does not hold the slot.
"""
events: list = []
phase = self.phase
# ⚠️ THE SLOT IS CHECKED BEFORE THE PHASE, AND THIS BRANCH IS A RECOVERY
# RATHER THAN AN EXPECTED PATH. `arbitrate()` grants the slot to the
# pack that is already mid-cycle, so a pack that is BOTH moving power
# and blocked means two histories on disk say "drain" - a hand-edited
# state file, or a store carried across a version that had no interlock.
# The fail-safe direction is unambiguous: two packs pulling against each
# other on one connection is the fault SAFETY-31 latches the whole site
# for. Stand this one down to 0 W and say why; the holder keeps its
# cycle, which is the outcome that loses no coulomb count at all.
if blocked_by and phase in POWER_MOVING:
events += self.abort(now, f"interlock - {blocked_by}")
return MaintResult(IDLE, True, 0.0, False, events)
if phase == IDLE:
if self.cfg.enabled and now.hour == self.cfg.start_hour and self.due(now):
last_try = self.store.get_time("last_start_attempt")
cooled = (
last_try is None
or (now - last_try) >= timedelta(minutes=RESTART_COOLDOWN_MIN)
)
if cooled:
self.store.set_time("last_start_attempt", now)
self._enter(DRAIN, now, events,
"maintenance: due -> drain (exports the surplus)")
return MaintResult(DRAIN, True, self.cfg.discharge_w, False, events)
if self.wants_start(now):
if blocked_by:
# ⚠️ `last_start_attempt` IS NOT STAMPED HERE, AND THAT IS
# THE STARVATION FIX RATHER THAN AN OMISSION. That key is
# the post-ABORT cooldown: it exists so a cycle that failed
# does not re-trigger inside the same start hour. A deferral
# is not an attempt - nothing was tried and nothing failed -
# and stamping it would put this pack under a 90 minute
# cooldown for a start hour that is 60 minutes long, so the
# pack that lost the arbitration would still be locked out
# at the moment the winner released the slot.
#
# ⚠️ AND THE PHASE DOES NOT MOVE, WHICH IS THE OTHER HALF.
# `phase_started` is untouched, so the 12 h DRAIN and 36 h
# CHARGE timeouts - which mean "the battery is not following
# commands, a fault" - cannot be reached by waiting. A
# deferred pack is IDLE under the loop, not a stuck one.
return MaintResult(IDLE, False, None, False,
self._defer_note(blocked_by, events),
blocked_by)
self._deferred = ""
self.store.set_time("last_start_attempt", now)
self._enter(DRAIN, now, events,
"maintenance: due -> drain (exports the surplus)")
return MaintResult(DRAIN, True, self.cfg.discharge_w, False, events)
self._deferred = ""
return MaintResult(IDLE, False, None, False, events)
# ⚠️ Fail toward inaction. Without a state-of-charge reading none of the
@@ -273,3 +492,77 @@ class Maintenance:
_LOG.error("maintenance: unknown phase %r, forcing idle", phase)
events += self.abort(now, f"unknown phase {phase!r}")
return MaintResult(IDLE, True, 0.0, False, events)
def _days(n: float) -> str:
return "never recalibrated" if n == math.inf else f"{n:.0f} d since its last cycle"
def arbitrate(machines, now: datetime) -> list:
"""Grant the site's ONE maintenance slot. Returns a list parallel to
`machines`: "" for the pack that may move power, otherwise the reason the
pack may not.
⚠️ THE SLOT IS A PROPERTY OF THE GRID CONNECTION, WHICH IS WHY IT IS NOT ON
`Maintenance`. Each FSM can see its own pack's schedule and nothing else; the
quantity being rationed - "how many phases are moving power across one
meter" - is a sum over the roster, exactly like `sum(|B_i|) - |sum(B_i)|` in
SAFETY-31 and for the same reason. A per-pack answer to a site-level
question is the shape of defect this repository keeps finding.
⚠️ IT IS DERIVED, NOT PERSISTED, AND THAT IS DELIBERATE. The holder is
"whichever pack's stored phase is not IDLE" - a fact already on disk, in the
per-pack history the packs themselves write. A separate `maint_slot_holder`
key would be a second opinion about the same thing, and the two would
disagree the first time the add-on was killed between writing the phase and
writing the holder. Restart-safe by construction: a controller that comes
back up mid-drain reads the drain and re-derives the holder from it.
TWO CLAUSES, IN ORDER:
1. A PACK ALREADY MOVING POWER KEEPS THE SLOT. Nothing preempts a cycle in
flight, because a recalibration interrupted halfway is worth less than
nothing - the coulomb counter is graded on ONE uninterrupted drain and
refill, so a cycle stopped at 40 % has spent the energy and bought no
calibration. If more than one pack somehow comes up moving power, the
FIRST in roster order holds and `tick()` stands the others down; see the
recovery branch there.
2. OTHERWISE THE LONGEST-WAITING CANDIDATE STARTS. `wants_start()` is asked
of every pack, and among those that say yes the slot goes to the one with
the largest `waited_days()`. NOT roster order: two packs on one monthly
schedule are due in the same hour every month, and a roster-order tie
would hand the slot to `inverters[0]` every single time while the second
pack's coulomb counter drifted forever - which is, in a different
costume, the exact defect this card was opened for. Roster order breaks a
genuine numeric tie and nothing else.
⚠️ AT A ROSTER OF ONE THIS IS THE IDENTITY FUNCTION. One machine is never
another machine's blocker: clause 1 finds at most itself and clause 2 has at
most one candidate, so it returns `[""]` on every tick and no reason string
it can build is ever rendered. That is what makes the one-inverter behaviour
byte-identical rather than merely similar.
"""
blocks = [""] * len(machines)
busy = [(i, m) for i, m in enumerate(machines) if m.phase in POWER_MOVING]
if busy:
held, holder = busy[0]
for i, m in enumerate(machines):
if i != held:
blocks[i] = (f"{holder.name} is mid-cycle ({holder.phase}) and "
f"holds the site's one maintenance slot")
return blocks
wants = [(i, m) for i, m in enumerate(machines) if m.wants_start(now)]
if len(wants) <= 1:
return blocks
# Largest waited_days wins; `-index` makes a numeric tie fall to roster
# order rather than to whatever `max()` happens to see first.
won, winner = max(wants, key=lambda p: (p[1].waited_days(now), -p[0]))
for i, m in wants:
if i != won:
blocks[i] = (f"{winner.name} has waited longer "
f"({_days(winner.waited_days(now))} against "
f"{_days(m.waited_days(now))}) and takes the site's "
f"one maintenance slot first")
return blocks
+13
View File
@@ -43,6 +43,19 @@ SENSORS = [
("grid", "goodwe_grid_power", "Grid power", "W", "power", "measurement", None),
("battery", "goodwe_battery_power", "Battery power", "W", "power", "measurement", None),
("soc", "goodwe_battery_soc", "Battery SoC", "%", "battery", "measurement", None),
# SAFETY-31. `sum(|Bi|) - |sum(Bi)|` over MEASURED per-inverter power: the
# power going round between the inverters, which the grid sensor above
# CANNOT SHOW because it nets to zero there. The two are published side by
# side on purpose - "grid 0 W, circulating 6000 W" is the whole phenomenon
# in two rows of a dashboard, and no arithmetic on the grid figure alone can
# ever produce the second one.
#
# ⚠️ Published as 0 at the shipped one-inverter roster, not omitted, and
# that is a deliberate difference from `p1_age` below. An absent entity is
# right for a watchdog input nothing is feeding; this is a quantity whose
# value is KNOWN at N=1 - identically zero, for every reading - and a
# dashboard row reading 0 W is the honest report of it.
("circulation", "goodwe_circulating_power", "Circulating power", "W", "power", "measurement", "mdi:sync-alert"),
("phase", "goodwe_maintenance_phase", "Maintenance phase", None, None, None, "mdi:battery-sync"),
("status", "goodwe_controller_status", "Controller status", None, None, None, "mdi:heart-pulse"),
# ⚠️ THE LIVE ENTITY IS `sensor.goodwe_p1_sample_age`, NOT what this
+9 -2
View File
@@ -372,7 +372,7 @@ not need re-testing. Nothing here indexes a phase.
from dataclasses import dataclass
from .arbiter import P_PEAK, Claim
from .arbiter import ACTUATOR_SITE, P_PEAK, Claim
from .control import peak_at_risk
from .tariff import QUARTER_S
@@ -744,7 +744,14 @@ def claim(decision: PeakDecision) -> Claim | None:
# 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.
# ⚠️ ON THE SITE ACTUATOR, EXPLICITLY. The billed quantity is the quarter's
# average offtake AT THE GRID CONNECTION - one per site, whatever the site
# has behind it - so this floor bounds the site target and is divided by the
# allocator along with it. It is never a bound on one unit's share: SAFETY-25
# §0c's table has this `lo` at the SITE stage precisely so the deferred loop
# reserve's per-inverter `hi` cannot become its counterpart in a `lo > hi`.
return Claim.limit(SOURCE, P_PEAK, lo=float(decision.floor_w),
reason=("blind" if decision.blind
else "SoC floor" if decision.floor_limited
else "quarter peak"))
else "quarter peak"),
actuator=ACTUATOR_SITE)
+491
View File
@@ -39,6 +39,56 @@ _LOG = logging.getLogger("goodwe.store")
# commanding -1000, -2000 W before re-tripping 180 s later. Under a supervisor
# that restarts a crashed add-on that is a loop, three minutes of wrong-direction
# power at a time, forever.
#
# ⚠️ AND SINCE DEV-02 THE TWO SAFETY-02 KEYS ARE THE *LEGACY* SPELLING. They are
# FLAT - one `sign_tripped` for a controller that now holds a LIST of inverters -
# so a trip caused by inverter B would latch inverter A across restarts, and one
# operator action would clear both. The LIVE latch is per inverter, under
# `unit/<name>/...`, and that is the one the watchdog is restored from.
#
# ⚠️ THE FLAT PAIR IS NOT DEAD, THOUGH: it is the ROLLBACK VIEW. It is written
# alongside the namespaced keys on a trip and cleared alongside them on the
# operator's clear, so an add-on that is DOWNGRADED past this schema still finds
# the latch it should - and so that a trip taken while the install was rolled
# back is still visible to the version that comes back up. Rule 2 of
# `migrate_unit_keys()` and `Controller._grade_store_migration()` carry the
# argument; the short version is that a latch is only worth persisting if it
# survives the version change an operator makes while staring at the banner.
#
# ⚠️ AND SAFETY-31's PAIR IS FLAT ON PURPOSE, WHICH IS THE OPPOSITE DECISION TO
# THE ONE ABOVE AND NEEDS ITS OWN SENTENCE. `circ_tripped` / `circ_reason` are
# NOT in `LEGACY_UNIT_KEYS` and must never be moved into a unit namespace.
# Circulating power is `sum(|B_i|) - |sum(B_i)|` - a quantity DEFINED over the
# whole roster, which is identically zero for any single unit. There is no fact
# of the matter about which of two opposing inverters is the offender: a unit
# ignoring its share and a sibling faithfully executing a share computed to sum
# with it read identically. Namespacing this latch would mean inventing an
# attribution the measurement cannot support, and would then let an operator
# clear "inverter B's" half of a site-wide loop. One site, one latch.
#
# It is persisted for SAFETY-34's reason, which this add-on has already paid
# for once: `persistent_notification` is IN MEMORY. Home Assistant restarts and
# the card is gone while the fault runs on - exactly how the 2026-09-02 outage
# went unseen for 6 h 25 m with the detector correct throughout. main.py
# re-raises the notification from this key on every start.
#
# ⚠️ AND SAFETY-30's PAIR IS FLAT FOR THE SAME REASON SAFETY-31's IS, WHICH IS
# NOT THE SAME REASON THE ONES ABOVE ARE NAMESPACED. `site_sign_tripped` /
# `site_sign_reason` hold the SITE sign-disagreement latch: the SUM of every
# standing command opposed the meter, continuously. That is a statement about
# the grid connection - the offending number is the site target, which no single
# inverter owns - so there is no unit to hang it on, and hanging it on one would
# let an operator clear "inverter B's half" of a fault that has no halves.
# `unit/<name>/sign_tripped` above stays what it always was and now means what
# it says: THAT unit's own command against THAT unit's own measured power.
#
# ⚠️ AND THEY ARE NOT IN `LEGACY_UNIT_KEYS`, MUST NEVER BE, AND ARE NOT WRITTEN
# AT A ROSTER OF ONE AT ALL. At N=1 the site comparison and the unit comparison
# are the same sentence and `Controller.cycle()` arms only the per-unit
# detector, so a one-inverter install's state file is byte-identical to what it
# was before this card - these two keys sit at their defaults and nothing reads
# them. A rollback therefore finds exactly the flat `sign_tripped` mirror it
# always found.
DEFAULTS = {
"phase": "idle",
"phase_started": None,
@@ -46,8 +96,449 @@ DEFAULTS = {
"last_start_attempt": None,
"sign_tripped": False,
"sign_reason": "",
"circ_tripped": False,
"circ_reason": "",
"site_sign_tripped": False,
"site_sign_reason": "",
}
# --------------------------------------------------------------------------- #
# DEV-02: PER-INVERTER KEYS, AND THE MIGRATION IS THE RISKY HALF
#
# ⚠️ A LATCH THAT SILENTLY FAILS TO MIGRATE IS A DISARMED SAFETY GUARD ON AN
# INSTALL THAT BELIEVES IT IS PROTECTED. SAFETY-02's whole reason for being
# persisted is that "restart the add-on" is the FIRST thing an operator staring
# at a FAILSAFE banner tries, and a latch held only in memory comes back armed,
# into the fault, unattended. A latch that is written down under a key nothing
# reads any more is exactly the same failure with a longer paper trail: the file
# still says `sign_tripped: true`, the banner is green, and the controller
# resumes driving the wrong way.
#
# So this is a MIGRATION WITH A POSTCONDITION, not a copy. `migrate_unit_keys()`
# reports what it did AND reads the result back; `Controller.__init__` grades
# that report and refuses to come up quietly if the latch did not survive. The
# test that grades it BREAKS the migration and watches the guard fire.
# --------------------------------------------------------------------------- #
# 0 = the flat, one-inverter layout that shipped before DEV-02.
# 1 = per-inverter keys under `unit/<name>/...`.
SCHEMA_VERSION = 1
SCHEMA_KEY = "schema_version"
# Which flat keys belong to ONE inverter, and therefore move into its namespace.
# ⚠️ THE MAINTENANCE KEYS ARE STILL NOT IN HERE, AND SINCE MAINT-05 THAT IS A
# DIFFERENT DECISION RATHER THAN THE SAME ONE. They DO move now - one
# `Maintenance` per roster entry needs one history per roster entry - but they
# move on their OWN marker, `MAINT_SCHEMA_KEY`, and only on a site that actually
# has more than one pack. Two conditions the SAFETY-02 keys do not share, so
# folding them into this tuple would either drag them across on a
# single-inverter install (which is the byte-identical store layout MAINT-05
# must not change) or hold the sign latch hostage to a roster count it has
# nothing to do with. `MAINT_UNIT_KEYS` below carries them.
LEGACY_UNIT_KEYS = ("sign_tripped", "sign_reason")
# --------------------------------------------------------------------------- #
# MAINT-05: THE SECOND MIGRATION, AND WHY IT IS A SECOND ONE
#
# 0 = the flat, one-history layout every install has had since the add-on
# shipped: `phase` / `phase_started` / `last_completed` /
# `last_start_attempt` describe THE pack, because there was one FSM.
# 1 = one history per roster entry, under `unit/<name>/...`.
#
# ⚠️ ITS OWN MARKER, NOT A BUMP OF `SCHEMA_VERSION`, AND THE REASON IS THAT THE
# TWO MIGRATIONS DO NOT HAVE THE SAME PRECONDITION. DEV-02's runs on every
# install exactly once and is monotone in the version number. This one runs ONLY
# WHERE THE ROSTER HAS MORE THAN ONE PACK, because at N=1 §6.2's identity holds
# and the flat keys ARE that pack's namespace - moving them would add four keys
# and a version marker to a store MAINT-05's own acceptance criterion requires
# to be byte-identical. A single monotone counter cannot express "migrated on
# this site, deliberately not migrated on that one" without lying to the next
# version that reads it: a one-inverter store would have to be left at the old
# number forever, and then a genuine v2 migration could never be told apart from
# a site that simply never grew.
#
# ⚠️ AND IT IS TWO MARKERS, NOT TWO COPIES OF THE THREE RULES.
# `_move_flat_keys()` and `_verify_moves()` below are shared verbatim by both
# migrations, so rules 1 and 3 and the READ-BACK POSTCONDITION are one
# implementation. A second transcription of a migration is a second opinion
# about what "it landed" means.
MAINT_SCHEMA_VERSION = 1
MAINT_SCHEMA_KEY = "maint_schema_version"
# The flat maintenance-history keys, in the order they are moved.
# ⚠️ THE VALUES ARE THE FLAT SPELLINGS AND THE MODULE THAT READS THEM INDEXES
# THIS SAME TUPLE (`maintenance.UnitHistory`), so a key renamed here cannot
# silently stop being migrated - the same property `UNIT_STORE_KEYS` gives the
# SAFETY-02 pair.
MAINT_UNIT_KEYS = ("phase", "phase_started", "last_completed",
"last_start_attempt")
def unit_key(unit: str, key: str) -> str:
"""The namespaced Store key for `key` on inverter `unit`.
⚠️ ONE SPELLING, IN ONE PLACE. `Inverter.key()` calls this and so does the
migration, so a check can assert that what was migrated is what is read.
Two transcriptions of a key name is one copy plus a future disagreement
about which one holds the latch - and the copy that drifts is always the one
that reads.
"""
return f"unit/{unit}/{key}"
class MigrationReport:
"""What `migrate_unit_keys()` did, and whether it can be believed.
⚠️ IT CARRIES `verified`, WHICH IS READ BACK FROM THE STORE RATHER THAN
ASSUMED FROM THE ASSIGNMENT. That is the difference between this and a
two-line copy: the caller is able to ask "is the latch that was in the file
before now under the key the watchdog reads", and a `False` there is a
disarmed guard, which is an ERROR and not a log line nobody sees.
"""
def __init__(self):
self.ran = False # did anything need moving
self.from_version = 0
self.moved = {} # new key -> value written
self.kept = [] # keys already namespaced, left alone
self.verified = True # every move read back equal
self.problems = [] # human-readable, one per failed move
# ⚠️ THE SUBSET THAT MATTERS, AND THE DISTINCTION IS NOT PEDANTRY. A
# store that drops a write of `sign_tripped=False` has lost the
# DEFAULT - the same statement "absent" already makes, so nothing is
# gone. One that drops a write of `True` has lost A LATCH. Only the
# second is a disarmed safety guard, and only the second may be allowed
# to shout: an alarm that fires on the harmless case is an alarm an
# operator learns to dismiss before the real one arrives.
self.lost = []
# ⚠️ A DIFFERENT FAILURE FROM `lost`, AND IT HAS TO BE, BECAUSE THE
# READ-BACK CANNOT SEE IT. `lost` is "the store took the write and
# dropped it". This is "the store took the write, kept it perfectly, and
# NOTHING WILL EVER READ IT" - the migration was handed a unit name that
# is not on the roster, so every machine looks under a different key and
# finds nothing. There is no harmless-default version of this the way
# there is for `lost`: a write nobody reads is not information, whatever
# its value, so anything in here fails `ok` on its own.
self.misdirected = []
# Why nothing ran, when nothing ran. Empty means "already at schema".
self.skipped = ""
@property
def ok(self) -> bool:
"""Nothing that CARRIED STATE failed to land, and it landed WHERE THE
MACHINES LOOK."""
return not self.lost and not self.misdirected
def explain(self) -> str:
if not self.ran:
# ⚠️ `skipped` RATHER THAN A SECOND SENTENCE ABOUT VERSIONS. Since
# MAINT-05 there are two reasons a migration does not run - the
# store is already at this schema, or the roster has one pack and
# the flat keys ARE its namespace - and an operator reading the
# startup log needs to be told which, because only one of them
# changes when a second inverter is declared.
return self.skipped or (f"store already at schema "
f"{self.from_version}; no "
f"per-inverter migration needed")
out = (f"migrated {len(self.moved)} flat key(s) to inverter "
f"namespaces: " + ", ".join(sorted(self.moved)))
if self.kept:
out += " (left alone, already namespaced: " + ", ".join(sorted(self.kept)) + ")"
if self.problems:
out += " - PROBLEMS: " + "; ".join(self.problems)
if self.lost:
out += " - STATE LOST: " + "; ".join(self.lost)
if self.misdirected:
out += " - WRONG NAMESPACE: " + "; ".join(self.misdirected)
return out
def migrate_unit_keys(store, unit: str) -> MigrationReport:
"""Move the pre-DEV-02 flat per-inverter keys into `unit`'s namespace.
`unit` is the FIRST inverter in the roster, which on every install that can
possibly have a flat key is the only one it ever had. A store written by a
version that knew about more than one inverter is already at
SCHEMA_VERSION and is not touched.
THE THREE RULES, each one a case that would otherwise be a wrong answer:
1. IT NEVER OVERWRITES AN EXISTING NAMESPACED VALUE. A store that has both
spellings has been written by this version, and the namespaced one is
where the WATCHDOG is restored from. Preferring the flat one HERE would
resurrect a trip the operator has already cleared, because a migration
runs before anything can tell the two apart. Deciding between them is
main.py's job and it has the one rule that can: the flat key carries new
information only when NOTHING namespaced is latched.
2. THE FLAT KEYS ARE LEFT IN THE FILE, AND THEY ARE KEPT LIVE. Deleting
them buys tidiness and costs a rollback: an operator who downgrades the
add-on after a migration would find no latch at all, which is the
disarmed guard again in the other direction. Left in place, a downgrade
finds the trip it had.
⚠️ AND "LEFT IN PLACE" IS NOT ENOUGH ON ITS OWN, WHICH IS WHAT THIS RULE
USED TO SAY. The sentence here read "they go stale from this moment -
nothing writes them again - and the direction that staleness fails in is
a SPURIOUS latch, never a missing one". That was true of the latch this
migration MOVES and false of every trip that happens AFTERWARDS: nothing
flat was written for those, so a rollback found `sign_tripped: false` and
came up DRIVING. So main.py mirrors both keys on a trip and clears both
on the operator's clear. The flat pair is the ROLLBACK VIEW of the latch,
maintained, not a fossil - which is also what lets main.py's
`_grade_store_migration()` run on every start and catch a trip that
happened while the install was rolled back (see its docstring: the flat
key saying tripped while no inverter came up tripped is the one
disagreement that can occur, and it is a DOWNGRADE-WINDOW LATCH).
3. THE VERSION MARKER IS WRITTEN LAST. A crash between the copies and the
marker leaves the migration to run again, and rule 1 makes running it
again a no-op. A marker written first would leave a half-migrated store
looking finished.
"""
rep = MigrationReport()
data = getattr(store, "data", {})
rep.from_version = int(data.get(SCHEMA_KEY, 0) or 0)
if rep.from_version >= SCHEMA_VERSION:
return rep
rep.ran = True
_move_flat_keys(store, unit, LEGACY_UNIT_KEYS, rep)
_verify_moves(store, rep)
if rep.ok:
store.set(SCHEMA_KEY, SCHEMA_VERSION)
else:
# ⚠️ NOT MARKED DONE. A migration that lost state must run again on the
# next start rather than be recorded as finished - the one thing worse
# than a failed migration is a failed migration a later version skips.
_LOG.error("per-inverter store migration LOST STATE and has not been "
"marked done: %s", rep.explain())
return rep
def _move_flat_keys(store, unit: str, keys, rep: MigrationReport) -> None:
"""Rule 1, once, for both migrations.
Copies each flat `key` to `unit/<unit>/<key>` UNLESS the namespaced spelling
is already present - a store that has both has been written by a version
that knew about the namespace, and that value is the live one. Rule 2 is the
absence of a delete: the flat keys are left exactly where they were.
"""
data = getattr(store, "data", {})
for legacy in keys:
target = unit_key(unit, legacy)
if target in data:
rep.kept.append(target)
continue
# ⚠️ `DEFAULTS[legacy]` RATHER THAN A LITERAL. An install that never
# tripped has no `sign_tripped` in its file at all, and the value it
# then lands on has to be the one `Store.load()` would have supplied -
# otherwise "absent" and "never tripped" stop being the same statement,
# which is the distinction store.py's own header is about. The same
# sentence holds for `last_completed`: absent means "never recalibrated"
# and a literal here would be a second opinion about that.
value = data.get(legacy, DEFAULTS.get(legacy))
store.set(target, value)
rep.moved[target] = value
def _verify_moves(store, rep: MigrationReport, roster=None) -> None:
"""THE POSTCONDITION, AND IT IS A READ-BACK RATHER THAN AN ASSUMPTION.
This is the difference between these functions and a two-line copy: the
caller can ask "is the latch that was in the file before now under the key
the watchdog reads" - and, since MAINT-05, "is the history that was in the
file before now under the key THIS PACK's state machine reads" - through the
same `unit_key()` those readers read through. A `False` here is a guard that
is off, or a month of coulomb-count history gone, on an install whose state
file says otherwise.
⚠️ AND `roster` IS THE OTHER HALF, WHICH THE READ-BACK ON ITS OWN CANNOT BE.
A POSTCONDITION THAT READS BACK THE NAMESPACE IT WAS HANDED CANNOT DETECT
BEING HANDED THE WRONG ONE. That is not a hypothetical: MAINT-05 shipped
with `migrate_maint_keys()` taking a bare `unit` string, and a call site that
passed `inverter.UNIT_A` instead of the first roster entry's name migrated an
install's whole maintenance history into `unit/inverter-a/...` on a roster of
`["garage", "shed"]`, read all four keys back under that same name, was
SATISFIED, and stamped the schema marker - so the next start skipped the
migration too and both packs came up believing they had never been
recalibrated. Every symptom of a clean migration, and the history gone.
`build_roster()` names a declared roster's entries from the config and falls
back to a POSITIONAL `inverter-N`, so `inverter-a` is not even the default
there; there is no roster on which that write could have been read.
So the namespace is graded against the one the MACHINES read - the roster -
rather than against the argument this function was handed, which is the
thing under test. A unit that is not on the roster is `misdirected`, which
fails `ok`, which means the caller does NOT stamp the version marker and the
next start runs the migration again. A re-run is recoverable, by rule 1; a
silent skip is the state store.py's header says must never happen.
⚠️ AND THE GRADED SET IS `moved` UNION `kept`, WHICH IS WHAT MAKES THAT
PARAGRAPH TRUE ON THE SECOND START AS WELL AS THE FIRST. Graded over `moved`
alone the refusal lasted exactly one start: the wrong call site is still
wrong next time, finds the keys it wrote already present, and rule 1 routes
every one of them to `kept` - so `moved` is empty, this loop sees nothing,
`ok` comes back True and the marker is stamped on a migration that has
reached no readable key. The measurement is in the comment on the loop
itself. `test_maintenance.py` section 9c calls this twice with the SAME
wrong `unit` over one store, which is the shape nothing in the suite had.
`roster=None` means "not graded", and the one caller that passes it is
`migrate_unit_keys()`, which runs BEFORE `build_roster()` for the reason its
own docstring gives - the `Inverter` objects restore their latch in their
constructors, so the keys have to be in place before there is a roster to
check against. That gap is real and is recorded as a running check rather
than left to a comment: see test_maintenance.py section 13.
"""
for target, value in rep.moved.items():
got = getattr(store, "data", {}).get(target, "<<missing>>")
if got == value:
continue
rep.verified = False
note = f"{target} was written as {value!r} and reads back as {got!r}"
rep.problems.append(note)
legacy = target.rsplit("/", 1)[-1]
if value != DEFAULTS.get(legacy):
rep.lost.append(note)
if roster is None:
return
names = [str(n) for n in roster]
# `unit_key()` builds `unit/<unit>/<key>`, so the unit is field 1. Split
# through the same spelling the writer used rather than re-deriving it.
#
# ⚠️ `moved` UNION `kept`, AND THE UNION IS THE WHOLE OF THE SECOND FIX
# ROUND. Grading only `moved` made the refusal last EXACTLY ONE START.
# Measured at Controller level over one persisted store, roster
# ["garage", "shed"], flat `last_completed` 2026-08-07, with the call site
# still handing `inverter-a` on both starts:
#
# construction 1: ok=False misdirected=4 moved=4 kept=0 marker=<absent>
# construction 2: ok=True misdirected=0 moved=0 kept=4 marker=1
#
# On start 2 the four keys the WRONG start 1 wrote are already present, so
# rule 1 routes every one of them to `rep.kept`, `rep.moved` is EMPTY, this
# loop iterates over nothing, `misdirected` is empty and `ok` is True - so
# the caller stamps the marker and start 3 takes the `from_version >=
# SCHEMA` early return FOREVER, including after the call site is fixed.
# Loud-and-recoverable became silent-and-permanent after one restart: the
# exact state this module's header says must never happen, reached by the
# fix that was written to prevent it.
#
# The union is sound by construction rather than by hope: every entry in
# both `rep.moved` and `rep.kept` is a `unit_key(unit, legacy)` built from
# the SAME `unit` argument, so grading `kept` grades the same namespace
# decision `moved` does. A correct call site puts its `kept` entries under a
# roster name and they pass; a wrong one cannot launder its namespace by
# having already written it.
for target in sorted(set(rep.moved) | set(rep.kept)):
parts = target.split("/")
unit = parts[1] if len(parts) > 2 else ""
if unit in names:
continue
rep.verified = False
note = (f"{target} was migrated into namespace {unit!r}, which is NOT "
f"on the roster {names!r} - nothing reads that key")
rep.problems.append(note)
rep.misdirected.append(note)
def migrate_maint_keys(store, unit: str, roster) -> MigrationReport:
"""Move the flat maintenance history into the FIRST pack's namespace.
MAINT-05. Until this card there was one `Maintenance` and one history, and
`store.py`'s own header argued the keys should stay flat because per-pack
scheduling was a card of its own. This is that card: there is now one FSM
per roster entry, so there is one history per roster entry, and the flat one
belongs to the pack that was being recalibrated - `inverters[0]`, which is
what `Controller.maint_unit` named and what `validate.py` rule 6 graded
against.
⚠️ `len(roster) <= 1` IS A RETURN, NOT A SPECIAL CASE. At one inverter the
flat keys ARE that pack's namespace (§6.2's identity, the same one
`arbiter.actuator_for()` leans on), `Maintenance` is constructed to read
them directly, and a migration would add four keys plus a marker to a store
that must come out byte-identical. The migration happens on the day the
roster grows, which is the day the flat spelling stops being able to answer
"which pack".
⚠️ `roster` IS REQUIRED, AND IT REPLACED AN `n_units: int`. Two reasons, and
the second is the one MAINT-05 was rejected over.
The small one: `n_units` was `len(self.inverters)` at the only call site, so
the roster carries it - `len(roster)` - and a count passed beside the names
is a second opinion about how many packs there are.
The load-bearing one: THE NAMES ARE THE POSTCONDITION. `unit` says which
pack the flat keys belonged to and that is genuinely a decision - the first
roster entry, because that is the pack the one FSM was driving - but a
decision the caller can get WRONG, and until this signature existed nothing
could tell. `_verify_moves()` read back the namespace it was handed, so a
migration into a name no machine reads verified clean and stamped the
marker. Handing the roster in means the read-back is graded against the
keys the MACHINES read, and a `unit` that is not among these names comes
back `misdirected`: not `ok`, marker NOT written, migration runs again next
start - and again the start after that, because `_verify_moves()` grades
`kept` as well as `moved`. See `_verify_moves()` for the install this was
measured on, and for what grading `moved` alone cost on start 2.
THE THREE RULES ARE `migrate_unit_keys()`'s, SHARED IN CODE rather than
restated: `_move_flat_keys()` is rule 1 (never overwrite a namespaced value)
and rule 2 (the flat keys are left in the file), `_verify_moves()` is the
read-back postcondition, and the marker is written LAST so a crash before it
leaves the migration to run again - which rule 1 makes a no-op.
⚠️ AND RULE 2 IS KEPT LIVE HERE TOO, WHICH IS THE HALF DEV-02 HAD TO ADD
LATER. "Left in place" alone makes the flat history a fossil dated the day
the second inverter was declared: an operator who rolls back to a
single-FSM add-on would find a `last_completed` months old and recalibrate a
pack that does not need it, or - worse - a stale `phase` and a
`phase_started` old enough to abort on the 12 h timeout the moment it comes
up. So `maintenance.UnitHistory` MIRRORS the first pack's writes back onto
the flat keys for as long as the roster has more than one entry. The flat
pair is the ROLLBACK VIEW of the history, maintained, exactly as
`sign_tripped` is the rollback view of the latch.
"""
rep = MigrationReport()
data = getattr(store, "data", {})
names = [str(n) for n in roster]
rep.from_version = int(data.get(MAINT_SCHEMA_KEY, 0) or 0)
if len(names) <= 1:
rep.skipped = ("one inverter: the flat maintenance keys ARE that pack's "
"history and are read in place, so there is nothing to "
"move and the store layout does not change")
return rep
if rep.from_version >= MAINT_SCHEMA_VERSION:
rep.skipped = (f"maintenance history already at schema "
f"{rep.from_version}; written by a multi-inverter "
f"version and not touched")
return rep
rep.ran = True
_move_flat_keys(store, unit, MAINT_UNIT_KEYS, rep)
_verify_moves(store, rep, roster=names)
# ⚠️ `rep.ok` AND NOTHING ELSE - NOT `ok or kept`, NOT `not lost`, NOT
# `not misdirected`. BOTH guards gate this line and each one is pinned by a
# check that the other cannot satisfy: section 9c refuses a store whose
# failure is `misdirected` with `lost` empty, and section 9d refuses one
# whose failure is `lost` with `misdirected` empty AND `kept` non-empty -
# the mutation `if rep.ok or rep.kept:` stamps the marker on a migration
# that lost a month of history, and until section 9d existed all 19 suites
# were green on it.
if rep.ok:
store.set(MAINT_SCHEMA_KEY, MAINT_SCHEMA_VERSION)
else:
# ⚠️ NOT MARKED DONE, FOR EITHER FAILURE. The same sentence
# `migrate_unit_keys()` carries: the one thing worse than a failed
# migration is a failed migration a later version skips. Rule 1 makes
# the re-run a no-op where the keys did land, so refusing the marker
# costs one repeated pass and buys the difference between a migration
# that can still be fixed and one the store says already happened.
_LOG.error("per-pack maintenance-history migration did NOT land and "
"has not been marked done: %s", rep.explain())
return rep
class Store:
def __init__(self, path: str = "/data/state.json"):
+481 -29
View File
@@ -74,7 +74,8 @@ NOT READY banner already names the problem, (b) does not apply.
was overruled. That firmware file's own comment says a lower bound on this
"belongs in CFG-01, not here" - so here it is.
5. `sign_disagree_w` at or above `max_w`. [(a)]
5. `sign_disagree_w` - or SAFETY-30's `unit_sign_disagree_w` - at or above
`max_w`. [(a)]
The arbiter's `supervised` limit bounds every command to +-max_w, and
SAFETY-02's predicate needs `abs(command) > sign_disagree_w`. Set the
threshold at or above the ceiling and the command side of the comparison
@@ -150,6 +151,32 @@ NOT READY banner already names the problem, (b) does not apply.
permits equality because equality there leaves one reachable point that
works; here it leaves none.
9. An `inverters:` roster that cannot mean what it says. [(a) and (b)]
CFG-04's five cases are enumerated on `_roster_problems()`. Three of them
are (b) - an entry with no `setpoint_entity`, or no rating, is a unit that
takes a share of the site target every cycle and delivers none of it, on a
status page that reports a site running at full strength. Two are (a): two
entries sharing a name share one Store namespace, so one unit's SAFETY-02
latch IS the other's and an operator clearing one clears both; and a flat
`setpoint_entity` left set beside a declared roster is an actuator the
configuration names and nothing writes.
⚠️ RULES 5 AND 6 CHANGED SHAPE FOR THIS, and that is the part worth
reading. Both compared a threshold against the flat `max_w`, which was
right while there was exactly one inverter and is a PERMISSIVE READER the
moment there are two: `max_w: 5000` left over from a single-inverter
install, beside a roster of two 2000 W units, passed rule 5 at
`sign_disagree_w: 3000` while the watchdog could fire on NEITHER unit -
rule 5's own failure mode, reached through rule 5. They now read
`unit_caps()`, which is the roster's caps and, at one inverter, is
`[max_w]` exactly.
What rule 9 deliberately does NOT do is grade a rating against a device.
`dev_min`/`dev_max` here are one device's range and there are now N of
them, none of which has answered at startup. `validate_unit_ranges()` is
the per-unit form and main.py runs it from `run_control()`, once every
unit's own ESPHome has replied.
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
@@ -202,11 +229,13 @@ WHAT IS DELIBERATELY *NOT* REFUSED, because it is untidy rather than unsafe:
import logging
from .arbitrage import enabled as arbitrage_on
from .inverter import roster_entries
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
from .watchdog import SIGN_OPTION_DEFAULTS
_LOG = logging.getLogger("goodwe.config")
@@ -229,17 +258,307 @@ _LOG = logging.getLogger("goodwe.config")
# a matching integer means a matching rule.
FIRMWARE_INGEST_VETO_S = 30.0
# ⚠️ The complete set of option keys through which this add-on can reach an
# actuator. specs §1.5 makes "any configuration in which two writers can reach
# one actuator" a non-goal, and the way that non-goal is ENFORCED here is by
# construction: there is exactly one such key, so a second writer is not
# expressible in the options schema at all. sim/inject.py's `two_writers`
# scenario asserts on this tuple - if a second write path is ever added, that
# scenario goes red and somebody has to decide how the two are arbitrated
# BEFORE the config that allows both can ship.
# ⚠️ THE OPTION KEYS UNDER WHICH A WRITER CAN BE DECLARED - AN ENUMERATION, AND
# SAFETY-28 DEMOTED IT TO ONE. This tuple used to BE the guarantee. The comment
# that stood here said specs §1.5 makes "any configuration in which two writers
# can reach one actuator" a non-goal, and that the non-goal was ENFORCED by
# construction: exactly one such key, so a second writer is not expressible in
# the options schema at all.
#
# That was true, and it graded THE SHAPE OF THE OPTIONS SCHEMA rather than the
# writes. Add CFG-04's per-inverter config - a list of inverters, each with its
# own `setpoint_entity` - and there are two real writers with `len()` of this
# tuple still equal to 1. The check stays green while the property it protects
# is gone, which is this repository's named failure mode: a check that observes
# something other than what it claims to observe.
#
# So the guarantee moved to `actuator_writers()` below, which counts WRITERS PER
# ACTUATOR rather than keys, and finds them wherever in the options tree they
# are declared. This tuple survives only because a census has to know which key
# NAMES an actuator; it is not a bound on how many writers there can be, and
# nothing should ever assert on its length again.
ACTUATOR_WRITE_KEYS = ("setpoint_entity",)
def _collect_writers(node, path: str, out: list) -> None:
"""Walk the options tree, collecting `(where, entity)` for every writer.
⚠️ STRUCTURAL, NOT NAME-BASED ON THE CONTAINER, and that is the point. A
census that looked for a key called `inverters` would be guessing the name
CFG-04 has not chosen yet, and a guess that is wrong goes GREEN while two
writers exist - the same defect one level along. This walks whatever shape
the options happen to have and reports every `setpoint_entity` in it,
however deeply nested and under whatever container.
"""
if isinstance(node, dict):
for k, v in node.items():
here = f"{path}.{k}" if path else str(k)
if k in ACTUATOR_WRITE_KEYS:
entity = str(v or "").strip()
if entity:
out.append((here, entity))
continue
_collect_writers(v, here, out)
elif isinstance(node, (list, tuple)):
for i, v in enumerate(node):
_collect_writers(v, f"{path}[{i}]", out)
def actuator_writers(opts: dict) -> dict:
"""actuator -> the configured writers that can reach it. INSTANCE-AWARE.
The replacement for `len(ACTUATOR_WRITE_KEYS) == 1`. It answers HOW MANY
THINGS CAN WRITE TO EACH ACTUATOR, which is the property §1.5 actually
names, and it keeps answering it when the schema grows a per-inverter list:
two inverters with two entities are two writers on two actuators and fine,
two declarations naming ONE entity are the non-goal and are refused.
The key is the entity id, lowercased - Home Assistant entity ids are
lowercase by construction, and folding case here means a config cannot
smuggle a second writer past the census on `Number.X` versus `number.x`.
⚠️ SAY WHAT THIS STILL DOES NOT OBSERVE, because the argument that demoted
the tuple applies to its replacement too. This is a census of CONFIGURED
writers. A second write path added in CODE - a `hass.set_number()` call next
to some new strategy - declares nothing and is invisible here, exactly as it
was invisible to the tuple. That hole is not closed at startup and cannot
be: it is closed at runtime, by `Controller.write_refusal()`, which refuses
any value the single allocator did not place on this tick and does not care
what the options look like. The two checks are deliberately different
kinds - one grades the config, one grades the writes - and only the second
one survives a schema this file has not seen yet.
"""
found: list = []
_collect_writers(opts, "", found)
census: dict = {}
for where, entity in found:
census.setdefault(entity.lower(), []).append(where)
return census
def unit_caps(opts: dict) -> list[float]:
"""Each configured inverter's supervised cap, in roster order.
⚠️ WHY THIS EXISTS AT ALL, AND IT IS THE PERMISSIVE-READER PROBLEM IN THIS
FILE. Rules 5 and 6 both compare a threshold against "max_w", and both of
them are really comparing it against WHAT ONE UNIT MAY BE COMMANDED - the
arbiter files `supervised` per inverter, from `inv.max_w`, and there is no
such thing as a site rating on the wire. At one inverter those are the same
number and reading the flat option was right. At two they are not: a config
with `max_w: 5000` left over from a single-inverter install and a roster of
two 2000 W units would pass rule 5 at `sign_disagree_w: 3000` while the
watchdog could not fire on EITHER unit - the disarmed-guard-reporting-armed
state those rules exist to refuse, reached through the rule itself.
So the caps come from the roster the add-on will actually build
(`inverter.roster_entries()`, not a second reading of the option), and fall
back to the flat `max_w` only where that roster is the flat one too.
"""
return [cap for _, cap in unit_caps_indexed(opts)]
def unit_caps_indexed(opts: dict) -> list[tuple[int, float]]:
"""`unit_caps()`, but each cap carries the ROSTER INDEX it came from.
⚠️ WHY THE INDEX HAS TO TRAVEL WITH THE NUMBER. This function SKIPS entries
with no usable `max_w`, so position i in the caps list is not position i in
the roster the moment one entry is malformed. Rules 5 and 6 used to feed a
caps-list index straight into `_unit_label()`, which indexes `entries` - so
on a roster whose first entry has a junk `max_w`, the refusal named the
WRONG INVERTER. An operator told to lower a number on `inverter-a` when the
number is on `inverter-b` is being sent to the wrong device by the very
message that exists to stop that. Rule 9(d) already refuses such a config so
the two lists cannot desynchronise in shipped use - but "unreachable" is a
claim about today's rule ordering, not a property of this function, and
`validate_startup_config()` is also `sim/inject.py`'s entry point.
"""
entries = roster_entries(opts)
if not entries:
cap = _number(opts, "max_w", 2000.0)
return [] if cap is None else [(0, cap)]
caps: list[tuple[int, float]] = []
for index, entry in enumerate(entries):
if not isinstance(entry, dict):
continue
cap = _number(entry, "max_w", None)
if cap is not None:
caps.append((index, cap))
return caps
def _unit_label(opts: dict, index: int) -> str:
""""" at a single-inverter config, " (inverter-b)" at a roster.
The messages below have to read identically on the install that upgrades
into this version - it is the same configuration, refused for the same
reason - and have to NAME THE UNIT the moment there is more than one, or an
operator with three inverters is told a number is wrong and not which one.
"""
entries = roster_entries(opts)
if len(entries) <= 1:
return ""
entry = entries[index] if index < len(entries) else {}
name = ""
if isinstance(entry, dict):
name = str(entry.get("name") or "").strip()
return f" ({name or f'inverters[{index}]'})"
def _roster_problems(opts: dict) -> list[str]:
"""Rule 9 (CFG-04): the `inverters:` roster, refused where it cannot mean
what it says.
⚠️ THE SUPERVISOR ALREADY ENFORCES MOST OF THIS AND THAT IS NOT A REASON TO
DROP IT. `config.yaml`'s schema makes `name`, `setpoint_entity` and `max_w`
required per entry, and Supervisor 2026.08.0 refuses a blob that omits one
by name - measured, not assumed. But `validate_startup_config()` is also
`sim/inject.py`'s entry point and every check's, and those reach it with a
dict the Supervisor never saw; the same argument `price_provider` makes two
rules up. A rule the Supervisor duplicates costs nothing and covers the
callers it does not.
Five things are refused, and each is a config that would otherwise RUN:
a. `inverters` is not a list. `roster_entries()` wraps a scalar so this
can name it; without the rule the roster would be one inverter built
out of a string's `.get`, i.e. an immediate AttributeError.
b. An entry with no usable `name`. Store keys are namespaced BY NAME
(`store.unit_key`), so two nameless entries would share one namespace
and one unit's SAFETY-02 latch would silently be the other's.
c. Two entries with the SAME name - (b) reached the long way round.
d. An entry with no `setpoint_entity`, or no usable `max_w`. The first is
a unit this controller cannot command; the second is a unit whose
supervised claim would be `+-0 W`, which is a unit pinned at zero by a
missing key rather than by a decision.
e. A flat `setpoint_entity` alongside a declared roster. The flat keys are
the SINGLE-inverter shape; leaving one set while a roster is declared
means one of two things and neither is safe. If it names an entity an
entry also names, SAFETY-28's census below already refuses it as two
writers on one actuator. If it names a DIFFERENT one, nothing writes
it, the site runs quietly smaller than the configuration reads, and the
one place it would show up is a status page nobody compares against the
config. Refused rather than ignored, for §1.5's reason and for this
card's: a config that silently becomes a different config is worse than
one that refuses to load.
"""
problems: list[str] = []
raw = opts.get("inverters")
if raw is None or raw == "" or raw == []:
return problems
if not isinstance(raw, (list, tuple)):
return [f"inverters is {type(raw).__name__} {raw!r}, and it must be a "
"LIST of inverter objects - one per inverter, each naming its "
"own name, setpoint_entity and max_w. A single inverter needs "
"no list at all: leave `inverters` empty and the flat "
"setpoint_entity/soc_entity/batt_entity/max_w keys describe it."]
entries = roster_entries(opts)
seen: dict = {}
for i, entry in enumerate(entries):
where = f"inverters[{i}]"
if not isinstance(entry, dict):
problems.append(
f"{where} is {type(entry).__name__} {entry!r}, and every entry "
"must be an object with at least name, setpoint_entity and "
"max_w.")
continue
name = str(entry.get("name") or "").strip()
if not name:
problems.append(
f"{where} has no name. Every inverter needs one: the Store "
"namespaces this unit's SAFETY-02 latch, its heartbeat and its "
"write bookkeeping under it, so two unnamed units would share "
"one namespace and a trip caused by one would latch the other. "
"Any short identifier works - inverter-a, inverter-b, garage.")
elif name in seen:
problems.append(
f"{where} and {seen[name]} are both called {name!r}. The Store "
"keys every per-unit latch under the unit's name, so two units "
"with one name share one SAFETY-02 latch and one heartbeat "
"deadline - a trip caused by either would stop both, and an "
"operator clearing it would clear both. Give them different "
"names.")
else:
seen[name] = where
who = f"{where} ({name})" if name else where
if not str(entry.get("setpoint_entity") or "").strip():
problems.append(
f"{who} has no setpoint_entity, so this add-on cannot command "
"it. It would sit in the roster, take a share of the site "
"target every cycle and deliver none of it, while the status "
"page showed a site running at full strength. Give it the "
"ESPHome number entity that carries ITS setpoint, or remove "
"the entry.")
if _number(entry, "max_w", None) is None or (_number(entry, "max_w", None) or 0) <= 0:
problems.append(
f"{who} has no usable max_w (got {entry.get('max_w')!r}). It is "
"the supervised cap on what may be written to THIS inverter, it "
"is not shared with any other unit and it is deliberately not "
"inherited from the flat max_w - a rating borrowed from a "
"sibling is exactly what DEV-02 removed. State this unit's own "
"rating in watts.")
flat_sp = str(opts.get("setpoint_entity") or "").strip()
if entries and flat_sp:
problems.append(
f"setpoint_entity is set to {flat_sp} AND an inverters list of "
f"{len(entries)} is declared. The flat setpoint_entity/soc_entity/"
"batt_entity/max_w keys are the SINGLE-inverter shape and are not "
"read at all once a roster exists, so this config declares an "
"actuator that nothing will ever write - a site running quietly "
"smaller than its own configuration. Move that inverter into the "
"list as its own entry and clear setpoint_entity.")
return problems
def validate_unit_ranges(units, *, skip_entity: str = "") -> list[str]:
"""Rule 2, per inverter, against each unit's OWN reported device range.
⚠️ THE READER THIS REPLACES FAILED PERMISSIVE, WHICH IS THE DIRECTION THAT
HIDES A DEFECT. `run_control()` re-ran rule 2 behind `if
self.o.get("setpoint_entity")` - the FLAT key - because the flat options
were the only per-device options there were. Declare a roster and that key
is blank by rule 9(e), so the whole re-check was skipped and NO inverter's
`max_w` was ever graded against the device it is written to. That is rule
2's own failure mode restored by a config shape: the operator's stated
ceiling is not the ceiling and nothing says which won.
`units` is the roster (anything with `.name`, `.setpoint_entity`, `.max_w`,
`.dev_min`, `.dev_max`). A unit whose device did not answer is SKIPPED, not
guessed at, for the reason in this module's docstring: ESPHome is often not
up when the add-on boots and (None, None) means "not read", not "zero".
`skip_entity` is the flat `setpoint_entity` when the caller has already
graded it through `validate_startup_config(opts, dev_min, dev_max)`. At a
single-inverter config that is the one unit, and grading it twice would
report the same conflict twice under two wordings.
"""
problems: list[str] = []
skip = str(skip_entity or "").strip().lower()
for unit in units:
entity = str(getattr(unit, "setpoint_entity", "") or "").strip()
if not entity or entity.lower() == skip:
continue
cap = float(getattr(unit, "max_w", 0.0) or 0.0)
dev_min = getattr(unit, "dev_min", None)
dev_max = getattr(unit, "dev_max", None)
name = getattr(unit, "name", entity)
if dev_max is not None and cap > float(dev_max):
problems.append(
f"{name}: max_w is {cap:.0f} W but {entity} accepts at most "
f"{float(dev_max):.0f} W - THE DEVICE WINS, so the {cap:.0f} W "
f"configured for this inverter would silently never happen. "
f"Lower this entry's max_w to {float(dev_max):.0f} W or less.")
elif dev_min is not None and -cap < float(dev_min):
problems.append(
f"{name}: max_w is {cap:.0f} W, so this controller may command "
f"{-cap:.0f} W, but {entity} accepts no less than "
f"{float(dev_min):.0f} W - THE DEVICE WINS on the charge side. "
f"Lower this entry's max_w to {abs(float(dev_min)):.0f} W or "
"less.")
return problems
class ConfigRefused(Exception):
"""The configuration is wrong. Not "something broke" - see main.py's handler.
@@ -265,9 +584,8 @@ def validate_startup_config(opts: dict, dev_min=None, dev_max=None) -> list[str]
"""
problems: list[str] = []
# --- 1. an actuator to write to ------------------------------------------
writers = [k for k in ACTUATOR_WRITE_KEYS
if str(opts.get(k, "") or "").strip()]
# --- 1. an actuator to write to, and AT MOST ONE WRITER PER ACTUATOR -----
writers = actuator_writers(opts)
if not writers:
problems.append(
"setpoint_entity is not set, so this add-on has no actuator: every "
@@ -275,8 +593,45 @@ def validate_startup_config(opts: dict, dev_min=None, dev_max=None) -> list[str]
"ESP32 heartbeat that holds off the layer-1 failsafe never happens. "
"It would run, look healthy, and move no energy at all. Set it to "
"the ESPHome number entity that carries the setpoint.")
# SAFETY-28. The §1.5 non-goal, graded on the writers rather than on the
# count of option keys. Read `actuator_writers()` for why the old check went
# green on the very config this one is here to refuse.
#
# ⚠️ AND IT REFUSES A DUPLICATE DECLARATION EVEN WHEN BOTH NAME THE SAME
# ENTITY, which is the case an author of the per-inverter config will meet
# first: keep `setpoint_entity` as inverter A's and add A to the list again
# and there are two config sites aimed at one actuator, each with its own
# neighbouring options. "They happen to be the same entity, so it is fine"
# is precisely the reasoning that makes two writers invisible. Declare each
# actuator exactly once and the refusal does not fire.
for actuator, who in sorted(writers.items()):
if len(who) > 1:
problems.append(
f"{len(who)} configured writers can reach the one actuator "
f"{actuator}: {', '.join(who)}. specs §1.5 makes any "
"configuration in which two writers can reach one actuator a "
"non-goal - two independent setpoints on one inverter is the "
"arbitration problem this add-on refuses to have, and at "
"runtime it is a meter-emulation target being written twice a "
"second by two strategies that cannot see each other. Give "
"each actuator exactly one writer, or point the second one at "
"its own entity.")
# --- 9. CFG-04's roster, graded BEFORE anything reads a per-unit number --
# ⚠️ FIRST, THOUGH IT IS THE NEWEST RULE. Rules 5 and 6 below now ask the
# roster what one unit may be commanded, so a roster that is nonsense has to
# have been named as nonsense before they read it - otherwise an entry with
# no `max_w` silently contributes no cap, `min()` sees a shorter list, and
# the operator is told about a sign watchdog when the real problem is a
# missing rating one line up.
problems.extend(_roster_problems(opts))
# --- 2. the configured ceiling against the device's own rating -----------
# ⚠️ THE FLAT `max_w`, AND ONLY THE FLAT ONE. `dev_min`/`dev_max` are ONE
# device's range - the flat `setpoint_entity`'s - so this rule can only ever
# speak for the single-inverter shape. The per-unit form of it is
# `validate_unit_ranges()`, which main.py runs once every unit's own device
# has answered; it is not called from here because at startup no device has.
max_w = _number(opts, "max_w", 2000.0)
if max_w is None:
problems.append(f"max_w {opts.get('max_w')!r} is not a number")
@@ -355,20 +710,71 @@ def validate_startup_config(opts: dict, dev_min=None, dev_max=None) -> list[str]
# below max_w, so threshold == max_w is already unsatisfiable. Anything
# BELOW max_w is reachable and therefore fine - this refuses the disarmed
# case only, not "close to the rail".
#
# ⚠️ AND IT IS GRADED AGAINST THE SMALLEST UNIT'S CAP, NOT AGAINST THE FLAT
# `max_w`. There is one SignWatchdog PER INVERTER (DEV-02) and each grades
# its own unit's standing command, which the arbiter bounds by THAT UNIT's
# `supervised` claim - so the watchdog that can never fire is the one on the
# smallest inverter, and a threshold under the site's largest cap says
# nothing about it. At one inverter `unit_caps()` is `[max_w]` and this is
# the identical comparison it always was.
sign_w = _number(opts, "sign_disagree_w", 300.0)
# ⚠️ (index, cap) PAIRS, NOT BARE CAPS. `unit_caps()` skips entries with no
# usable `max_w`, so `caps.index(weakest)` was an index into the CAPS list
# being handed to `_unit_label()`, which indexes the ROSTER - and the message
# named the wrong inverter as soon as the two lengths differed. The index
# travels with the number now, so the name is the name of the unit the
# number came off.
caps_ix = unit_caps_indexed(opts)
caps = [cap for _, cap in caps_ix]
weakest = min(caps) if caps else None
if sign_w is None:
problems.append(f"sign_disagree_w {opts.get('sign_disagree_w')!r} is not a number")
elif max_w is not None and max_w > 0 and sign_w >= max_w:
elif weakest is not None and weakest > 0 and sign_w >= weakest:
where = _unit_label(opts, min(caps_ix, key=lambda p: p[1])[0])
problems.append(
f"sign_disagree_w is {sign_w:.0f} W but max_w is {max_w:.0f} W, so "
f"sign_disagree_w is {sign_w:.0f} W but max_w{where} is "
f"{weakest:.0f} W, so "
"the SAFETY-02 sign-disagreement watchdog can never fire: the "
"arbiter never lets a command exceed max_w, and the watchdog needs "
f"a command over {sign_w:.0f} W. It would sit there reporting "
"'armed' on the status page while being incapable of tripping - the "
f"one runaway failure mode this system has actually observed. Lower "
f"sign_disagree_w below {max_w:.0f} W (300 W is the measured "
f"sign_disagree_w below {weakest:.0f} W (300 W is the measured "
"default), or raise max_w.")
# ⚠️ AND THE SAME RULE FOR SAFETY-30's PER-UNIT THRESHOLD, WHICH IS A
# SEPARATE COMPARISON AND THEREFORE A SEPARATE WAY TO DISARM. It grades a
# unit's own SHARE against that unit's own measured power, and a share is
# bounded by the same `supervised` claim at +-max_w - so a threshold at or
# above the ceiling makes the command side unsatisfiable by construction,
# exactly as above. Written as its own branch rather than folded into the
# one above because the two produce different sentences and an operator
# needs to be told WHICH watchdog they have disarmed.
#
# ⚠️ REFUSED EVEN AT A ROSTER OF ONE, WHERE THIS CHECK IS NOT ARMED. A
# config that cannot work is refused when it is WRITTEN, not on the day a
# second inverter is added - which is the day nobody is watching the startup
# log. This is `meter_max_age_s`'s rule read the same way: the failure it
# prevents is silent.
unit_sign_w = _number(opts, "unit_sign_disagree_w",
float(SIGN_OPTION_DEFAULTS["unit_sign_disagree_w"]))
if unit_sign_w is None:
problems.append(f"unit_sign_disagree_w "
f"{opts.get('unit_sign_disagree_w')!r} is not a number")
elif max_w is not None and max_w > 0 and unit_sign_w >= max_w:
problems.append(
f"unit_sign_disagree_w is {unit_sign_w:.0f} W but max_w is "
f"{max_w:.0f} W, so the SAFETY-30 per-inverter sign-disagreement "
"watchdog can never fire: no inverter is ever commanded past max_w, "
f"and the watchdog needs a command over {unit_sign_w:.0f} W. At two "
"inverters that is the guard which catches a unit doing the "
"OPPOSITE of what it was told while its sibling covers for it at "
"the meter - the case the site-level watchdog is structurally "
f"blind to. Lower unit_sign_disagree_w below {max_w:.0f} W "
f"({SIGN_OPTION_DEFAULTS['unit_sign_disagree_w']:.0f} W is the "
"measured default), or raise max_w.")
# --- 6. a maintenance charge the ceiling can actually accommodate --------
# ⚠️ Strictly `>`, matching the arbiter exactly. The shaping is
# `Claim.limit(hi=-charge_w)` against `supervised`'s `lo=-max_w`, so
@@ -395,22 +801,63 @@ def validate_startup_config(opts: dict, dev_min=None, dev_max=None) -> list[str]
# 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.
#
# ⚠️ MAINT-05: IT IS GRADED AGAINST THE WEAKEST UNIT'S CAP NOW, AND THE
# COMMENT THIS REPLACES SAID SO WOULD HAPPEN. It read: "there is exactly ONE
# `Maintenance` in this add-on and `Controller.maint_unit` names the pack it
# recalibrates - the first in the roster, because the cycle's history lives
# under un-namespaced Store keys. The shaping claim is filed on THAT
# actuator and on no other, so the cap that can contradict it is THAT
# unit's. Taking `min()` here would refuse a perfectly workable site - a
# 5000 W pack being recalibrated beside a 2000 W sibling the cycle never
# touches ... When `maint_unit` stops being `inverters[0]`, this line moves
# with it."
#
# `maint_unit` has stopped being `inverters[0]`. There is one `Maintenance`
# per roster entry, each with its own namespaced history, and EVERY pack is
# recalibrated on its own schedule - so the sibling "the cycle never
# touches" does not exist any more and the over-refusal argument has no
# subject. The shaping claim is filed on whichever pack is charging, so the
# cap that can contradict it is any cap on the roster, and the one that
# contradicts it FIRST is the smallest. This is rule 5's conjunction for
# rule 5's reason: a threshold that is fine against the biggest unit says
# nothing about the smallest, and the smallest is the one that goes to 0 W.
#
# ⚠️ THIS REFUSES CONFIGS THAT USED TO START, AND THAT IS THE POINT RATHER
# THAN A SIDE EFFECT. `max_w` 5000 on pack A beside 2000 on pack B with
# `maintenance_charge_w` 3000 was accepted before this card and was correct
# while only pack A was ever recalibrated. Pack B now recalibrates too, and
# its cheap-window charge asks the arbiter for `hi = -3000` against a
# supervised `lo = -2000`: `lo > hi`, arbiter clause 3, 0 W, contradiction -
# a maintenance charge that silently never happens on that pack, which is
# exactly what rule 6 exists to refuse at the moment it is WRITTEN. At a
# roster of one `min()` over one cap is that cap and the comparison, the
# message and the boundary are identical.
charge_w = _number(opts, "maintenance_charge_w",
float(MAINT_OPTION_DEFAULTS["maintenance_charge_w"]))
# ⚠️ THE SAME PAIRING AS RULE 5, FOR THE SAME REASON: `unit_caps_indexed()`
# SKIPS entries with no usable `max_w`, so a caps-list position is not a
# roster position and `_unit_label()` indexes the roster. The index travels
# with the number, so the unit the message names is the unit the number came
# off - which on a roster whose first entry has a junk `max_w` is not the
# same thing at all.
maint_index, maint_cap = (min(caps_ix, key=lambda p: p[1]) if caps_ix
else (0, None))
maint_where = _unit_label(opts, maint_index)
if charge_w is None:
problems.append(
f"maintenance_charge_w {opts.get('maintenance_charge_w')!r} is not a number")
elif max_w is not None and max_w > 0 and charge_w > max_w:
elif maint_cap is not None and maint_cap > 0 and charge_w > maint_cap:
problems.append(
f"maintenance_charge_w is {charge_w:.0f} W but max_w is "
f"{max_w:.0f} W, so a maintenance charge in a cheap window can "
f"maintenance_charge_w is {charge_w:.0f} W but max_w{maint_where} is "
f"{maint_cap:.0f} W, so a maintenance charge in a cheap window can "
"never happen: the shaping asks the arbiter for at most "
f"{-charge_w:.0f} W while the supervised limit allows no less than "
f"{-max_w:.0f} W, which is a contradiction it resolves to 0 W - "
f"{-maint_cap:.0f} W, which is a contradiction it resolves to 0 W - "
"THE CEILING WINS, and what you would see is an ARBITER "
"CONTRADICTION line that reads like a bug rather than like these "
f"two numbers. Lower maintenance_charge_w to {max_w:.0f} W or less, "
f"or raise max_w to at least {charge_w:.0f} W.")
f"two numbers. Lower maintenance_charge_w to {maint_cap:.0f} W or "
f"less, or raise max_w to at least {charge_w:.0f} W.")
# --- 7. two price sources on one site ------------------------------------
problems.extend(_price_problems(opts))
@@ -470,18 +917,23 @@ def validate_startup_config(opts: dict, dev_min=None, dev_max=None) -> list[str]
# 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.
# ⚠️ AND AGAINST THE MAINTENANCE UNIT'S CAP, for rule 6's reason: it is the
# same one actuator being clamped, so grading the warning against the flat
# `max_w` would warn about a site number while the clamp is a unit number.
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:
if (disch_w is not None and maint_cap is not None and maint_cap > 0
and disch_w > maint_cap):
_LOG.warning(
"maintenance_discharge_w %.0f W is above max_w %.0f W. Not refused - "
"the drain phase SETS the setpoint and the arbiter clamps it to "
"%.0f W and names the clamp ('limited by supervised(max_w)'), so "
"nothing is silent and the cycle still completes. But it drains at "
"%.0f W, not the %.0f W you configured, and the drain phase has a "
"720 min timeout. Lower it to %.0f W or raise max_w to remove the "
"maintenance_discharge_w %.0f W is above max_w%s %.0f W. Not "
"refused - the drain phase SETS the setpoint and the arbiter clamps "
"it to %.0f W and names the clamp ('limited by supervised(max_w)'), "
"so nothing is silent and the cycle still completes. But it drains "
"at %.0f W, not the %.0f W you configured, and the drain phase has "
"a 720 min timeout. Lower it to %.0f W or raise max_w to remove the "
"surprise.",
disch_w, max_w, max_w, max_w, disch_w, max_w)
disch_w, maint_where, maint_cap, maint_cap, maint_cap, disch_w,
maint_cap)
return problems
+351 -18
View File
@@ -164,11 +164,106 @@ saturation freeze's question (|command - the battery's actual power| > 500 W,
NOTES.md §4.7 row 4), and the two checks are complementary rather than
overlapping. Neither substitutes for the other.
⚠️ THAT PARAGRAPH IS ABOUT THE COMMAND-VERSUS-METER COMPARISON, AND SINCE
SAFETY-30 THAT IS NOT THE ONLY ONE THIS MODULE DRIVES. At a roster of two or
more each unit is ALSO graded against its own measured power, which is exactly
the comparison the paragraph says nothing here makes - see the SAFETY-30 section
below, which says what that does and does not take away from the freeze. At the
shipped roster of one the paragraph stands unchanged, word for word: the site
comparison is the only detector armed and the freeze is still the whole answer.
Nor does it see a sign inversion introduced DOWNSTREAM of this add-on - in the
firmware, on the wire, or in a future driver. Our view stays self-consistent and
this stays silent. That is a wire-versus-intent problem and it belongs to the
witness, which is the only vantage point that sees both.
------------------------------------------------------------------------------
SAFETY-30 - AT TWO INVERTERS THIS IS TWO QUESTIONS, NOT ONE
Everything above was written at a roster of ONE, and at N=1 it is right for a
reason that stops being true at N=2. `commanded_w` is what THIS controller put
on THIS actuator. `grid_w` is what the WHOLE SITE is exchanging with the
network. At one inverter those are two views of one thing - §6.2's identity -
which is what makes comparing them sound. At two they are not:
* A FALSE TRIP THE COMPARISON CANNOT AVOID. "Inverter A commanded -1500 W
while the meter reads +1500 W" is evidence of nothing at N=2: inverter B may
be discharging 3000 W and doing exactly what it was told. No fault anywhere,
and the check NOTES.md calls the highest-value entry in the safety table -
93 % agreement while healthy against 4 % during runaway, four episodes, zero
false positives - fires.
* THE CONVERSE, WHICH IS WORSE. A unit genuinely driving the wrong way is
MASKED, because the site figure NETS. Commanded +1500 W, measured -1500 W,
beside a sibling measured at +1500 W: the meter sits exactly where a healthy
site leaves it. This is not a threshold that is set too high - the
information is destroyed by the summation, and no tuning recovers it.
So the one comparison becomes two, each asked of the evidence that can answer
it, and they are DIFFERENT FAULTS rather than one fault at two scales:
PER UNIT this unit's standing command against ITS OWN measured power -
`Inverter.batt`, which on the live system is holding register
0x0518, this inverter's own AC power, per-instance since DEV-02.
Conclusion: "THE ACTUATOR I AM DRIVING IS NOT DOING WHAT I TOLD
IT". The evidence is about one unit, so the remedy is that unit:
the `failsafe` SET, which arbiter.CLAIM_SCOPE has called a UNIT
claim from the day it was written, for this exact reason.
SITE the SUM of the standing commands against the meter. Conclusion:
"THE SITE AS A WHOLE IS DRIVING THE WRONG WAY" - an inverted gain,
an integrator wound past the rail, a strategy pushing the wrong
side of the meter. That is the fault the 2026-08-20 capture
contains and it is a property of the CONNECTION, so the remedy is
the connection: a SITE SET that stops every inverter.
⚠️ AND AT N=1 THERE IS EXACTLY ONE ARMED DETECTOR, WHICH IS THE ONE THAT
SHIPPED. The two questions above are the SAME SENTENCE at a roster of one: the
sum of one command is that command, and "the site" and "the unit" name one
actuator. Arming both would be arming a duplicate - two latches, two banners and
two chances to spend a false-positive record that was earned by ONE comparison
on two captured bus days. `Controller.cycle()` therefore hands the single unit's
watchdog THE METER, under the shipped `sign_disagree_w` / `sign_disagree_s`,
exactly as before, and never arms the site one. `arm()` below is where that
choice is written down. Nothing about a one-inverter install changes - not the
comparison, not the thresholds, not the store keys, not the claim, not the
banner.
⚠️ WHAT THE PER-UNIT COMPARISON IS NOT. Two guards that overlap without saying
so is how a false-alarm generator gets built, so both neighbours are named:
* IT IS NOT SAFETY-31. `circulation.py` compares the units AGAINST EACH OTHER
- `sum(|B_i|) - |sum(B_i)|` over MEASURED power - and catches two inverters
pushing THROUGH each other, which nets to zero at the meter and about which
no single command is evidence at all. This compares each unit against ITS
OWN COMMAND. Take two units faithfully executing an allocation that ALLOC-01
would refuse: circulating power is the whole loop, and every per-unit sign
check here reads perfect agreement. Take one unit doing the exact opposite
of its share while its sibling covers for it: this reads the whole
disagreement, and circulating power can be zero, because the two measured
powers may well agree in sign. Neither is the other with a different
threshold.
* IT IS NOT THE SATURATION FREEZE, AND THE OVERLAP IS REAL AND BOUNDED. The
freeze asks `|command - measured| > saturation_w` (500 W) and concludes "the
inverter cannot follow"; it then stops the integrator winding, which is a
control action taken every day, on a unit that is merely SATURATED as
readily as on one that is reversed, and it neither latches nor parks
anything. This asks for OPPOSITION - a sign, on both sides of a threshold,
held continuously - which a saturated-but-obedient unit cannot produce at
all, and it LATCHES and commands that unit to zero. The freeze is a
magnitude test that shapes the loop; this is a direction test that stops an
actuator.
⚠️ GATE 1 STILL APPLIES TO BOTH, AND THAT IS A DELIBERATE CHOICE WITH A COST.
The per-unit comparison could have been armed whenever ANY non-zero command is
standing - a unit should do what it is told whoever told it - and that would
catch a wedged inverter during a maintenance charge. It is not, because the
whole no-false-positive argument above is built on `following`, because the
freeze already grades that window, and because this card's own warning is that
SAFETY-02's record was earned at N=1 and must not be spent on a check that fires
when nothing is wrong. What it costs is written here rather than discovered:
between the start of a maintenance cycle and its end, a unit reversing against
its own command is the freeze's to notice, not this module's. Widening it is a
card, with a rig campaign behind it, not an edit.
------------------------------------------------------------------------------
STATE, TRIP AND LATCH
@@ -198,6 +293,178 @@ from dataclasses import dataclass
from datetime import datetime
# SAFETY-30. CFG-03: THE ONE IN-CODE COPY OF THE FOUR MULTI-INVERTER DEFAULTS.
# `config.yaml`'s `options:` block is the source of truth an operator edits and
# the Supervisor reads, and `schema:` holds the bounds. This dict exists for the
# reason `circulation.CIRC_OPTION_DEFAULTS` and `maintenance.MAINT_OPTION_DEFAULTS`
# do - the Dockerfile does not put config.yaml in the image, so the running
# add-on cannot read it - and `test_watchdog.py` pins the two together by READING
# config.yaml, so a drift goes red in CI rather than shipping.
#
# ⚠️ EVERY KEY HERE IS DEAD AT A ROSTER OF ONE, and that is the point rather
# than a caveat. `Controller._arm_sign_watchdogs()` arms the single unit's
# detector against the meter with the SHIPPED `sign_disagree_w` /
# `sign_disagree_s`, which are read in main.py exactly where they always were
# and are not in this dict. Nothing below is consulted until a second inverter
# exists.
SIGN_OPTION_DEFAULTS = {
# --- THE MAGNITUDE GATE, AND IT IS NOT SAFETY-02's 300 W BY ACCIDENT ---
# ⚠️ DERIVED FROM `control.Tuning.saturation_w`, WHICH IS 500 W, AND THE
# DERIVATION IS THE POINT. This check gates on BOTH sides being over
# `min_w`, so the smallest divergence it can ever see between a command and
# the power that command produced is `2 * min_w` - the two are OPPOSED, so
# the gap is the sum of the magnitudes. At 250 W that is exactly 500 W: the
# gap at which `compute()`'s own anti-windup test already concludes THE
# INVERTER IS NOT FOLLOWING and freezes the integrator. So this watchdog
# cannot fire on a divergence the shipped control law itself calls ordinary
# tracking, and the two guards meet at a number rather than overlapping in a
# band nobody has drawn.
#
# MEASURED, on 1890 closed-loop two-inverter runs in which NOTHING is faulty
# (every unit executes the share the allocator gave it), swept over the
# WHOLE range config.yaml accepts for `gain` float(0.05,1.0) and `slew_w`
# int(50,5000), across both families of stimulus that can produce legitimate
# opposition. Worst CONTINUOUS opposition between a unit's standing command
# and its own 0x0518 power, as a function of this threshold:
#
# 50 W -> 25.0 s 250 W -> 10.0 s 700 W -> 5.0 s
# 150 W -> 15.0 s 300 W -> 10.0 s 1000 W -> 0.0 s
# 200 W -> 15.0 s 500 W -> 5.0 s
#
# ⚠️ AND THE CURVE IS FLAT, WHICH IS THE FINDING THAT DECIDED THE SHAPE OF
# THIS PAIR. Unlike the site comparison - where the meter is driven by the
# LOAD and a flapping load holds it opposed for minutes - a unit's own power
# CHASES ITS OWN COMMAND through a bounded ramp and a first-order lag, so the
# opposition can only last as long as the crossing does. Dropping the
# threshold from 300 W to 50 W buys 15 s of extra transient and nothing else.
# The work is therefore done by the WINDOW below, and this number is set
# where the control law already draws its line rather than being tuned.
#
# The largest opposed magnitude seen anywhere in those 1890 runs is 875 W;
# a threshold above that would gate NOTHING legitimate in at all, and is
# rejected because it would also be blind to a unit reversing a 900 W share.
"unit_sign_disagree_w": 250,
# --- THE WINDOW -------------------------------------------------------
# Three bounds, and the value clears all three.
#
# LOWER, from the rig: 10.0 s - two control cycles, the worst CONTINUOUS
# legitimate opposition above 250 W across all 1890 runs. It is a
# reversing site whose second write lands a cycle after the first, both
# units then slewing through zero behind a 10 s lag; nothing is wrong.
#
# LOWER, from the firmware: `inverter.LINK_STALE_S`, 30 s. A unit not
# executing its share for less than the firmware's own veto window is a
# LINK fault, and the add-on already answers it - liveness drops the unit
# and the survivors carry its share, with the record saying so. Firing
# inside that window would raise a second, louder alarm about a state
# already being handled, which is the SAFETY-15/SAFETY-19 failure exactly.
#
# UPPER, from SAFETY-02 itself: 180 s, the SITE hold. A unit that is not
# doing what it was told must not be parked LATER than the site would be
# parked for the same watts, and unlike the site comparison this one needs
# nothing to net out before it can conclude - the evidence is complete on
# the first cycle it appears.
#
# 85 s: seventeen control cycles - 8.5x the worst legitimate episode this
# rig can produce, 2.8x the firmware's own veto window, and under HALF the
# site hold. ⚠️ IT IS DELIBERATELY NOT 60, 75, 90, 120 OR 180. A round
# number here would be a guess wearing a measurement's clothes, and the
# three bounds above are what the number has to answer to.
#
# ⚠️ AND INVERTER B DOES NOT PHYSICALLY EXIST. Its ramp and lag in the rig
# are inverter A's, COPIED, carrying `measured=False` - SPIKE-04 measures
# the real ones. A slower second unit lengthens every crossing above, which
# is what the 8.5x buys headroom for. SPIKE-04 is the revisit trigger for
# both numbers here, not a reason to move them now.
"unit_sign_disagree_s": 85,
# --- THE SITE COMPARISON AT N>=2, AND IT IS NOT THE SHIPPED PAIR -------
# ⚠️ THE THRESHOLD IS CARRIED AND THE WINDOW IS NOT, WHICH IS A FINDING
# RATHER THAN A COMPROMISE. Only one of the two arguments behind 300 W /
# 180 s depends on how many inverters the site has:
#
# THE THRESHOLD is about NOISE. "Near zero the sign is noise, and near
# zero is where a healthy loop LIVES" - the deadband holds the command
# still while the meter wanders either side of `target_grid_w`. The
# deadband is 15 W and P1 is one meter whatever the roster, so nothing
# about that argument moves. 300 W, carried - and the two-inverter
# campaign says the carry is safe rather than merely convenient: in the
# load-reversal family the site figure ever goes opposed AND over 300 W in
# 994 of 1050 runs at two inverters and 955 of 1050 at one. The gate opens
# about as often either way; what changed is how LONG it stays open, which
# is the window's problem and not the threshold's.
#
# THE WINDOW is about a TRANSIENT, and the transient scales with the site.
# The measured worst legitimate case is a load reversal that the loop
# crosses zero slowly: the command has to travel the whole rail at
# `slew_w` per cycle, and at N>=2 the rail is `Controller.site_max_w` - the
# ROSTER SUM - while `slew_w` is unchanged. So the crossing takes about
# twice as long at two inverters as at one, and that is exactly what the
# rig measures.
#
# 1890 closed-loop runs in which nothing is faulty, the SAME campaign the
# per-unit pair above is read off, run at BOTH rosters as its own control.
# Worst CONTINUOUS opposition between the standing command(s) and the meter,
# LOAD-REVERSAL family, at a 300 W threshold:
#
# N=1 (the shipped comparison) 110.0 s - inside 180 s, 1.6x
# N=2 (the sum, same stimuli) 215.0 s - OVER 180 s
#
# ⚠️ SO CARRYING 180 s WOULD HAVE SHIPPED A FALSE TRIP, and it is a config a
# schema-legal install can reach: `gain` 0.05 and `slew_w` 50 are both the
# floor of what config.yaml accepts, and a +-2200 W load reversal is an oven
# and a heat pump. That is the number this card exists to not assume.
#
# 325 s: 1.51x the measured worst, well inside the 900 s quarter that bills
# the capacity tariff, and still inside every episode the fault day
# contains - 2026-08-20's four clusters run 16, 30, 77 and 77 minutes and
# its opposed runs reach 1750 s, so a 325 s window fires in all of them.
# What it costs is stated rather than hidden: about two and a half extra
# minutes of wrong-direction SITE power before the stop, bought to remove a
# false trip that a legal configuration produces. ⚠️ DELIBERATELY NOT 300 OR
# 360; the measurement is what it answers to.
#
# ⚠️ AND IT IS NOT THE PER-UNIT WINDOW EITHER, IN THE OTHER DIRECTION. The
# per-unit comparison is 85 s because a unit's own power CHASES ITS OWN
# COMMAND and the transient is two cycles; the site comparison is 325 s
# because the meter is driven by the LOAD and the transient is the loop
# crossing zero. Same predicate, two instruments, two windows, both measured.
"site_sign_disagree_w": 300,
"site_sign_disagree_s": 325,
}
# ⚠️ A LIMIT OF THE SITE COMPARISON THAT SAFETY-30 DID NOT INTRODUCE AND DOES
# NOT FIX, RECORDED HERE BECAUSE THE CAMPAIGN FOUND IT AND SILENCE WOULD BE
# WORSE. The rig's other stimulus family is a FLAPPING LOAD, and a square wave
# whose half period is about one control cycle opposes the command on EVERY
# cycle: the command chases the previous half-cycle's meter while the meter has
# already reversed. Across the 840 flapping runs the worst continuous opposition
# at a 300 W threshold is 980 s at two inverters - and 1000 s at ONE, which is
# the whole point. The N=1 arm is the control, and it says this is a property of
# comparing a lagged command against a meter, not a property of the second
# inverter. No window inside the 900 s billing quarter survives it, and no
# threshold up to 1000 W does either.
#
# It is not acted on here for three reasons, in order of weight: it is identical
# at the roster this add-on actually ships, so acting on it would be changing a
# live safety path on evidence that has nothing to do with this card; a
# ~6 kW square wave at 0.1 Hz sustained for a quarter of an hour is not a house
# (the captured healthy day's longest opposed run is 30 s); and the fix is not a
# number - it wants the detector to notice that the disagreement is ALTERNATING,
# which is a different check. It is a card, and this comment is its evidence.
# SAFETY-30. THE TWO NOUNS THE TRIP SENTENCE CAN NAME, WRITTEN ONCE. They are
# constants rather than literals at the call sites because `main.py` arms the
# detectors and `test_watchdog.py` grades what they say, and a string typed in
# two places is a string that drifts in one of them - the same argument
# `store.unit_key()` makes about a key name. `AGAINST_METER` is the wording that
# has always shipped and must not change: it is what a one-inverter install's
# `reason` reads, in the store, in the action log and on the status page.
AGAINST_METER = "a meter reading"
AGAINST_OWN_POWER = "its own measured power"
@dataclass(frozen=True)
class SignWatchdogConfig:
"""Defaults, not constants - config.yaml carries both (SAFETY-02 AC 5)."""
@@ -206,7 +473,7 @@ class SignWatchdogConfig:
hold_s: float = 180.0
def disagrees(commanded_w, grid_w, following: bool,
def disagrees(commanded_w, against_w, following: bool,
cfg: SignWatchdogConfig) -> bool:
"""The predicate, and the ONLY place it is written down.
@@ -215,12 +482,23 @@ def disagrees(commanded_w, grid_w, following: bool,
inline. Two copies of a safety predicate is one copy plus a future
disagreement about what the check means, and the copy that drifts is always
the one in the harness that grades it.
⚠️ `against_w` WAS CALLED `grid_w`, AND THE RENAME IS THE WHOLE OF SAFETY-30
IN ONE PARAMETER. The arithmetic is unchanged - opposed signs, neither side
near zero, and the loop actually driving - but WHAT the command is opposed
TO is now a property of the caller rather than a fact about this function.
The site comparison hands it the meter; each unit's own comparison hands it
that unit's measured power (register 0x0518). One predicate, two callers,
for `loop_is_following()`'s reason: a safety predicate written down twice is
one copy plus a future disagreement about what the check means. The
parameter is positional at every call site in both repositories, so the
rename moves no caller.
"""
return (following
and commanded_w is not None and grid_w is not None
and commanded_w * grid_w < 0
and commanded_w is not None and against_w is not None
and commanded_w * against_w < 0
and abs(commanded_w) > cfg.min_w
and abs(grid_w) > cfg.min_w)
and abs(against_w) > cfg.min_w)
def loop_is_following(resolution, loop_asked) -> bool:
@@ -272,7 +550,17 @@ def loop_is_following(resolution, loop_asked) -> bool:
class SignWatchdog:
"""One instance per actuator, evaluated once per control cycle.
"""One instance per COMPARISON, evaluated once per control cycle.
⚠️ SINCE SAFETY-30 THAT IS NOT THE SAME SENTENCE AS "one per actuator",
which is what this docstring used to say. There is one instance per
inverter - `Inverter.sign_wd`, latched under that unit's own store keys -
AND one for the site, `Controller.site_sign_wd`, latched under flat ones.
The two ask different questions of different evidence and reach different
remedies; `arm()` below is where an instance is told which of them it is.
At a roster of one they would be the same question, so only the per-unit
instance is ever armed there - see the SAFETY-30 section of the module
docstring.
⚠️ NOT SHARED ACROSS CADENCES. `disagree_since` is a wall-clock start time,
so driving one instance from two loops at two rates would have each one
@@ -282,8 +570,14 @@ class SignWatchdog:
"""
def __init__(self, cfg: SignWatchdogConfig | None = None, *,
tripped: bool = False, reason: str = ""):
tripped: bool = False, reason: str = "",
against: str = AGAINST_METER):
self.cfg = cfg or SignWatchdogConfig()
# SAFETY-30. WHAT THE COMMAND IS BEING COMPARED AGAINST, as the operator
# reads it in the trip sentence. The default is the meter, which is what
# every trip this add-on has ever taken was compared against and is what
# keeps a one-inverter install's `reason` string byte-identical.
self.against = str(against)
self.disagree_since: datetime | None = None
# ⚠️ RESTORED FROM THE STORE, NOT DEFAULTED. A latch that lives only in
# memory is not a latch: a container restart clears it, and the add-on
@@ -292,8 +586,31 @@ class SignWatchdog:
self.tripped = bool(tripped)
self.reason = reason if self.tripped else ""
# -- which of SAFETY-30's two questions this instance is asking ----------
def arm(self, cfg: SignWatchdogConfig, against: str) -> None:
"""Set the thresholds and the subject of the comparison. Nothing else.
⚠️ IT IS CONFIGURATION, NOT STATE, AND IT DELIBERATELY DOES NOT TOUCH
`disagree_since`, `tripped` OR `reason`. A detector that cleared its own
window when it was told what it was comparing against would lose the
episode it is in the middle of, every cycle, and would never accumulate
a hold at all - the check would be permanently green and nothing would
say so.
⚠️ AND IT IS RE-STATED EVERY CYCLE RATHER THAN FROZEN AT CONSTRUCTION.
The answer is a property of the ROSTER and of nothing else, and
`Controller.cycle()` already re-reads the roster every cycle for
liveness and for the allocation. Freezing it in `__init__` would also
make it wrong for any caller that appends an inverter afterwards, which
is exactly how a two-inverter fixture is built in this repository - and
a fixture that silently got the one-inverter comparison would grade
nothing while looking green.
"""
self.cfg = cfg
self.against = str(against)
# -- the whole check, and it is a pure function of its arguments ----------
def evaluate(self, commanded_w, grid_w, following: bool,
def evaluate(self, commanded_w, against_w, following: bool,
now: datetime) -> bool:
"""Advance the detector one cycle. Returns True while tripped.
@@ -301,15 +618,23 @@ class SignWatchdog:
after deadband, slew, quantisation and the arbiter. Not
the optimizer's raw wish: the wire carries the emitted
value, so anything else can disagree with the meter for a
reason that is not a fault.
`grid_w` net P1, + = importing. None when the meter is stale or
missing, which CLEARS the timer rather than accumulating
- a frozen figure held against a moving command would
otherwise manufacture a disagreement in about three
minutes, on top of SAFETY-01 having already commanded
zero for the same cause.
reason that is not a fault. For a per-unit instance it is
THAT UNIT'S share of it; for the site instance it is the
roster sum.
`against_w` what the command is graded against, and SAFETY-30 made
this a decision rather than a fact: net P1 for the SITE
comparison (+ = importing), and this unit's own measured
power for the PER-UNIT one (+ = discharging, register
0x0518). Both carry the same sign convention as the
command, which is why one predicate serves both. None
when the reading is stale or missing, which CLEARS the
timer rather than accumulating - a frozen figure held
against a moving command would otherwise manufacture a
disagreement in about three minutes, on top of SAFETY-01
having already commanded zero for the same cause.
`following` did the grid-following loop actually win this cycle? See
gate 1 in the module docstring.
gate 1 in the module docstring, and the SAFETY-30 section
on why the per-unit comparison keeps it.
`now` the caller's clock, so this stays testable and replayable.
"""
if self.tripped:
@@ -317,7 +642,7 @@ class SignWatchdog:
return True
cfg = self.cfg
if not disagrees(commanded_w, grid_w, following, cfg):
if not disagrees(commanded_w, against_w, following, cfg):
self.disagree_since = None
return False
@@ -330,9 +655,17 @@ class SignWatchdog:
return False
self.tripped = True
# ⚠️ `self.against` IS THE ONLY THING SAFETY-30 CHANGED IN THIS STRING,
# and it defaults to the wording that shipped - "a meter reading" - so a
# one-inverter install's `reason` is byte-identical to what an operator
# (and test_watchdog.py) has always read. A per-unit instance names what
# it actually compared instead, because "commanded +1500 W against a
# meter reading -1500 W" would be a false statement about which
# instrument produced the evidence, on the one line somebody woken by
# this alarm reads first.
self.reason = (
f"SIGN_DISAGREEMENT: commanded {commanded_w:+.0f} W against a meter "
f"reading {grid_w:+.0f} W for {held:.0f} s continuously "
f"SIGN_DISAGREEMENT: commanded {commanded_w:+.0f} W against "
f"{self.against} {against_w:+.0f} W for {held:.0f} s continuously "
f"(limits: both over {cfg.min_w:.0f} W, held over {cfg.hold_s:.0f} s)"
)
return True
+204 -1
View File
@@ -1,5 +1,5 @@
name: GoodWe RS485 Controller
version: "0.5.2"
version: "0.6.0"
slug: goodwe_controller
description: >-
Drives a GoodWe ES/BP battery inverter over RS485 by emulating its smart
@@ -39,6 +39,59 @@ options:
batt_invert: false
setpoint_entity: ""
# --- ARCH-01 / CFG-04: the inverter roster ---------------------------------
# ⚠️ EMPTY IS NOT "UNCONFIGURED", IT IS THE SINGLE-INVERTER CONFIGURATION, and
# it is what every install that upgrades into this version lands on. An empty
# list means THE FIVE FLAT KEYS ABOVE DESCRIBE THE ONE INVERTER - same
# entities, same rating, same behaviour, no operator action - which is the
# only migration story this key was allowed to have. `build_roster()` reads
# this and nothing else decides the shape.
#
# Declared, it REPLACES those five keys rather than extending them. Each entry
# names its own actuator, its own rating and its own sensors:
#
# inverters:
# - name: inverter-a
# setpoint_entity: number.goodwe_a_setpoint_w
# soc_entity: sensor.goodwe_a_soc
# batt_entity: sensor.goodwe_a_battery_power
# max_w: 5000
# - name: inverter-b
# setpoint_entity: number.goodwe_b_setpoint_w
# soc_entity: sensor.goodwe_b_soc
# batt_entity: sensor.goodwe_b_battery_power
# max_w: 3000
#
# ⚠️ NOTHING IS INHERITED FROM THE FLAT KEYS BY AN ENTRY THAT OMITS IT, and
# that is the whole of DEV-02 restated as a config rule. `soc`, `batt` and the
# rating became per-instance precisely so that no inverter is ever graded
# against a sibling's numbers; an entry silently inheriting `soc_entity` would
# rebuild that defect in YAML. `name`, `setpoint_entity` and `max_w` are
# therefore REQUIRED of every entry (the schema below enforces it, and
# validate.py rule 9 enforces it again for the callers the Supervisor never
# sees). An omitted `soc_entity`/`batt_entity` means THIS UNIT HAS NO SUCH
# SENSOR - `inputs_ok` already stops the site for that - and never means
# "use the other one's".
#
# ⚠️ AND THE FLAT `setpoint_entity` MUST THEN BE BLANK. Leaving it set while a
# roster is declared is two config sites aimed at actuators, one of which
# nothing writes; if it names an entity an entry also names, SAFETY-28's
# writer census refuses it as two writers on one actuator, and if it names a
# different one the add-on would run a site quietly smaller than the config
# reads. Rule 9 refuses both rather than picking one.
#
# ⚠️ THE SHAPE WAS MEASURED, NOT ASSUMED. A list of objects is not used
# anywhere else in this file, and whether Supervisor's options validator
# accepts one was an open question - `static_profile` carries its structure as
# a JSON string in a `str?` for exactly that doubt. It was settled by running
# Supervisor 2026.08.0's OWN `AppOptions` validator (the version this site
# runs) against both candidates: tools/supervisor_shape_probe.py is the
# script, DECISIONS/CFG-04-inverter-roster.md is what it printed and why the
# list won. The default `[]` is load-bearing in that record: WITHOUT it the
# validator answers `Missing option 'inverters' in root` for every existing
# options blob, and the upgrade leaves an add-on that cannot start.
inverters: []
# --- P1 meter ingestion (specs §5.2 / §14 `meter:`) -------------------------
# `off` keeps the original single meter_entity path above, so an existing
# install is untouched until it opts in. ha_dsmr subscribes to the DSMR
@@ -114,6 +167,62 @@ options:
sign_disagree_w: 300
sign_disagree_s: 180
# --- SAFETY-30 per-inverter sign-disagreement watchdog ---------------------
# ⚠️ A DIFFERENT COMPARISON, NOT A SECOND COPY OF THE ONE ABOVE, AND IT IS
# ARMED ONLY WHEN THIS SITE HAS MORE THAN ONE INVERTER. The pair above grades
# the SITE's total command against P1 - one meter, one grid connection. This
# pair grades EACH inverter's own share against THAT inverter's own measured
# power (holding register 0x0518), and it catches the fault the meter cannot
# answer for once there are two units: a unit doing the opposite of what it
# was told, while its sibling covers for it and P1 reads exactly what a
# healthy site reads.
#
# At ONE inverter these two keys do nothing at all. §6.2's identity makes the
# site's total command that inverter's command, so the pair above is already
# asking this question of the same actuator, and arming a second detector
# would be two latches and two banners for one fault.
#
# Both defaults are measured on admin/goodwe's two-master rig, over 1890
# closed-loop runs in which nothing is faulty, swept across the whole range
# this file accepts for `gain` and `slew_w`. 250 W is `saturation_w / 2`, so
# the smallest divergence this can see is exactly the gap at which the control
# law itself already says the inverter is not following; 85 s is 8.5x the
# worst legitimate opposition those runs produce (10.0 s), 2.8x the firmware's
# own 30 s link veto, and under half the 180 s the site check takes. See
# app/watchdog.py's SIGN_OPTION_DEFAULTS and
# DECISIONS/SAFETY-30-per-unit-sign.md.
#
# ⚠️ unit_sign_disagree_w must stay BELOW max_w, for sign_disagree_w's reason:
# a share is bounded to +-max_w, so a threshold at or above it can never fire.
# validate.py refuses that config.
unit_sign_disagree_w: 250
unit_sign_disagree_s: 85
# --- SAFETY-30 SITE sign-disagreement watchdog -----------------------------
# ⚠️ THE SAME COMPARISON `sign_disagree_*` MAKES, AT THE ROSTER WHERE IT STOPS
# BEING A STATEMENT ABOUT ONE INVERTER. At two or more units the SUM of the
# standing commands is graded against P1, and the trip stops the whole site -
# what it catches is the site being asked for the wrong thing, which every
# per-inverter check is blind to because each unit is faithfully executing its
# share. At ONE inverter these two keys do nothing: `sign_disagree_*` above is
# already asking this of the same actuator.
#
# The threshold is the shipped 300 W, CARRIED, and the reason is that the
# argument behind it does not depend on the roster: near zero the sign is
# noise, the deadband is 15 W, and there is one P1 whatever is behind it.
#
# ⚠️ THE WINDOW IS NOT CARRIED, AND THAT IS A MEASUREMENT. The transient 180 s
# exists to reject is the loop crossing zero after a load reversal, and the
# command has to travel the whole SITE rail at `slew_w` per cycle - a rail
# that is the roster sum while `slew_w` is not. On 1890 two-inverter runs in
# which nothing is faulty, the worst continuous legitimate opposition at 300 W
# is 110 s at one inverter and 215 s at two: carrying 180 s across would have
# shipped a false trip reachable at `gain: 0.05`, `slew_w: 50` and an ordinary
# 2.2 kW load reversal. 325 s is 1.51x that, inside the 900 s billing quarter,
# and still inside every episode of the 2026-08-20 fault day.
site_sign_disagree_w: 300
site_sign_disagree_s: 325
# --- SAFETY-18 frozen-but-fresh meter detector -----------------------------
# Seconds the meter may keep answering with an UNCHANGED measurement while the
# command stands at the rail before the add-on raises an alarm. Both halves
@@ -134,6 +243,25 @@ options:
# still inside the 900 s quarter that bills the capacity tariff.
meter_freeze_s: 300
# --- SAFETY-31: circulating power ------------------------------------------
# ⚠️ CFG-03. THESE TWO LINES ARE THE SOURCE OF TRUTH FOR THESE DEFAULTS, and
# `app/circulation.py`'s `CIRC_OPTION_DEFAULTS` is the ONE in-code copy - the
# Dockerfile does not put this file in the image, so the running add-on cannot
# read it. test_watchdog.py pins the copy by READING these lines, so a drift
# goes red in CI rather than shipping. Add a third option in three places -
# options:, schema:, CIRC_OPTION_DEFAULTS - and in no fourth.
#
# Circulating power is sum(|Bi|) - |sum(Bi)| over MEASURED per-inverter power:
# two inverters pushing against each other, which NETS TO ZERO AT THE METER
# and is therefore invisible to every other guard in this add-on. Both numbers
# below were measured on the TEST-19 two-master rig over 924 closed-loop runs
# in which nothing was faulty; circulation.py carries the curve they were read
# off and the argument for each. They are NOT sensitivity preferences.
#
# Both are ignored at one inverter, where the quantity is identically zero.
circulation_w: 700
circulation_hold_s: 75
# --- 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,
@@ -350,6 +478,32 @@ schema:
batt_invert: bool
setpoint_entity: str
# CFG-04. THE ONE LIST-OF-OBJECTS IN THIS FILE, and see the options block for
# the measurement that says Supervisor 2026.08.0 accepts it: nested types are
# enforced per entry, a missing required key names the key, a scalar where the
# list belongs is refused, and the UI renders it as a repeatable section.
#
# ⚠️ THREE KEYS ARE REQUIRED PER ENTRY AND THAT IS DELIBERATE. An entry with
# no `name` has no Store namespace and would share another unit's SAFETY-02
# latch; one with no `setpoint_entity` is a unit nothing can command; one with
# no `max_w` would have to borrow a rating, which is the sibling-grading
# defect DEV-02 removed. The optional pair is the sensors, whose absence
# honestly means "this unit reports none".
#
# ⚠️ THIS BLOCK IS DECLARED BEFORE `max_w:` ON PURPOSE. `max_w` now appears
# TWICE under `schema:` - once nested here, once flat below - and a reader
# that matches a stripped line takes the nested one FIRST. That is the
# first-match trap this card had to fix in three checks; leaving the nesting
# first keeps the trap baited, so the fix stays graded rather than assumed.
# test_inverter.py part 12 asserts the ordering is still hostile.
inverters:
- name: str
setpoint_entity: str
max_w: int(100,5000)
soc_entity: str?
batt_entity: str?
batt_invert: bool?
meter_source: list(off|ha_dsmr|mqtt_p1|ha_signed|homewizard_local)
# ⚠️ 2 is accepted by this range but is not a real Belgian connection. A
# telegram whose phase count disagrees is rejected at ingest and logged, so a
@@ -389,6 +543,33 @@ schema:
sign_disagree_w: int(50,5000)
sign_disagree_s: int(30,1800)
# SAFETY-30. No "off" value, for SAFETY-02's reason.
#
# ⚠️ THE THRESHOLD'S RANGE IS THE SAME AS THE SITE CHECK'S ON PURPOSE, AND THE
# WINDOW'S FLOOR IS NOT. On the two-inverter rig the per-unit comparison's
# worst continuous legitimate opposition is nearly FLAT in the threshold -
# 25.0 s at 50 W, 15.0 s at 150 W, 10.0 s at 250 W, 5.0 s at 500 W - because a
# unit's own power chases its own command rather than the load. So no value in
# this range puts the guard outside the regime it can be answered for, and the
# floor does not have to be a knee the way `circulation_w`'s does.
unit_sign_disagree_w: int(50,5000)
# The floor of 30 is `inverter.LINK_STALE_S`, the firmware's own veto window:
# below it, a unit not executing its share is a LINK fault the add-on already
# answers by dropping the unit from the split, and firing inside that window
# would be a second, louder alarm about a state that is already being handled.
unit_sign_disagree_s: int(30,1800)
# SAFETY-30's SITE pair. Same ranges as `sign_disagree_*`, because it is the
# same comparison asked of the site total - and no "off" value, for the same
# reason. ⚠️ THERE IS DELIBERATELY NO validate.py RULE PAIRING
# site_sign_disagree_w WITH max_w, unlike the other two thresholds: the bound
# on the SITE command is `Controller.site_max_w`, the ROSTER SUM, and
# `validate_startup_config()` is handed options rather than a roster. A rule
# written against max_w would refuse a perfectly reachable two-inverter
# configuration the day CFG-04 lands. The schema range is the bound here.
site_sign_disagree_w: int(50,5000)
site_sign_disagree_s: int(30,1800)
# No "off" value, for SAFETY-02's reason: disarming a safety alarm is not a
# supported configuration. ⚠️ THE FLOOR OF 60 IS NOT A RECOMMENDATION. At 300 s
# the slowest a HEALTHY meter's 1 Wh register can tick and still look unchanged
@@ -398,6 +579,28 @@ schema:
# app/freeze.py.
meter_freeze_s: int(60,3600)
# SAFETY-31. No "off" value, for SAFETY-02's and meter_freeze_s's reason:
# disarming a safety alarm is not a supported configuration.
#
# ⚠️ THE FLOOR OF 400 IS NOT A RECOMMENDATION, IT IS THE MEASURED EDGE OF THE
# REGIME IN WHICH THIS GUARD CAN BE ANSWERED FOR. On the TEST-19 rig, the
# worst CONTINUOUS opposition produced by a site where nothing is faulty - a
# flapping load reversing every control cycle, swept over the whole range this
# schema accepts for `gain` and `slew_w` - is 5.0 s at a 400 W threshold and
# above, 10.0 s at 300 W, 40.0 s at 250 W and 505.0 s at 100 W. Below the
# knee, legitimate operation holds the sensor over the threshold for MINUTES
# and no window shorter than the 900 s billing quarter could tell that from a
# fault. A configurable value under 400 W would be a false-alarm generator
# that this project's own doctrine (SAFETY-15, SAFETY-19) forbids shipping.
circulation_w: int(400,5000)
# The floor of 30 is `inverter.LINK_STALE_S`: below the firmware's own veto
# window a unit still executing a stale share is a LINK fault the add-on
# already handles by dropping it from the split, and firing inside that window
# would raise a second, louder alarm about a state already being managed. The
# ceiling of 900 is the quarter that bills the capacity tariff - a circulating
# loop must be caught and acted on well inside one.
circulation_hold_s: int(30,900)
# ⚠️ 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 -
File diff suppressed because it is too large Load Diff
+407 -2
View File
@@ -13,10 +13,13 @@ Read MUTATION.md before you report a survivor.
"""
import sys
from math import inf
from app.arbiter import (
P_LOOP, P_MAINT_SHAPE, P_MAINTENANCE, P_PEAK, P_SAFETY,
Claim, resolve,
ACTUATOR_SITE, CLAIM_SCOPE, P_ARBITRAGE, P_LOOP, P_MAINT_SHAPE,
P_MAINTENANCE, P_PEAK, P_SAFETY, SCOPE_SITE, SCOPE_UNIT, UnitBounds,
Claim, actuator_for, allocate, pre_resolve, resolve, scope_violations,
site_resolve,
)
fails = []
@@ -28,6 +31,15 @@ def check(name, cond):
fails.append(name)
def _raises(fn):
"""True if `fn()` raises - a check that something is REFUSED, not defaulted."""
try:
fn()
except Exception:
return True
return False
print("basics")
r = resolve([])
check("no claims at all means 0 W", r.target_w == 0.0 and r.winner == "failsafe")
@@ -99,6 +111,399 @@ check("charging is clamped by the low limit", r.target_w == -1000)
r = resolve([Claim.set("loop", P_LOOP, -200), charge_only])
check("charge-only permits charging", r.target_w == -200)
# =============================================================================
# ARB-03: the actuator specs.md declared, and the three stages
# =============================================================================
# ⚠️ EVERY CHECK ABOVE THIS LINE IS UNEDITED, AND THAT IS ITSELF THE FIRST
# ACCEPTANCE CRITERION. Not one of them names an actuator, so every claim they
# build is a SITE claim - which is exactly the state main.py is in at N=1 - and
# they still answer what they answered before the field existed. If a line above
# had to be changed to accommodate `actuator`, stage 2 would not be the shipped
# arbiter and the refactor would not be pure.
print()
print("ARB-03 1. the field, and what its absence means")
lone = Claim.set("loop", P_LOOP, 900)
check("a claim built without naming an actuator carries one anyway",
lone.actuator == ACTUATOR_SITE)
# ⚠️ THE TYPE ITSELF, NOT ONLY THE TWO HELPERS. Measured: with only the helper
# checked, emptying the DATACLASS default survives this suite untouched, because
# `Claim.set()` and `Claim.limit()` pass their own default down and the field's
# never runs. Anything that builds a `Claim(...)` directly - a future strategy,
# a `dataclasses.replace()` - would have got the unspecified actuator that this
# card exists to remove.
check("...and so does one built through the dataclass directly, which is the "
"constructor the two helpers do not cover",
Claim("loop", P_LOOP).actuator == ACTUATOR_SITE)
check("...and it is an explicit SITE, not None and not an empty string. "
"'unspecified' is what the shipped code had, and 'unspecified' is what "
"made every claim implicitly about the one and only actuator",
isinstance(lone.actuator, str) and lone.actuator != ""
and lone.actuator is not None)
check("...and `source` is still the first positional argument, which is what "
"test_peakguard.py part 10f's AST scan reads off main.py to pin the "
"claim-source set. specs.md declares `actuator` first; the tuple position "
"is not the part of that declaration that carries meaning, and moving "
"`source` off zero would blind the tripwire that guards SAFETY-25",
Claim.limit("device", P_SAFETY, -1, 1).source == "device")
print()
print("ARB-03 2. the split: eight sources, each classified where it is BUILT")
# The classification is graded against what each claim is ABOUT, restated here
# so that the table in arbiter.py and the expectation in a test are not the same
# sentence read twice. test_peakguard.py part 10f pins this set against main.py's
# own AST, so a ninth source cannot arrive without both files noticing.
SITE_SOURCES = {
"loop": "regulates grid_w, the P1 measurement - one meter, one site",
"peak": "the quarter-hour average offtake AT the grid connection",
"arbitrage": "buys and sells at the grid against a day-ahead price",
"safety": "'stopped' is the site's switch, 'inputs missing' is the "
"site's own meter - neither is about a pack",
# SAFETY-31, and it is the entry most easily filed on the wrong side.
"circulation": "sum(|Bi|) - |sum(Bi)| is defined OVER THE ROSTER and is "
"identically zero for any one unit - there is no fact of "
"the matter about which of two opposing inverters is the "
"offender, so there is nothing to file it per-unit on",
# SAFETY-30, and it is the entry most easily confused with `failsafe`
# below, because the same three words describe both.
"sign_site": "the SUM of every standing command against the meter. The "
"offending number is the SITE target, which no single "
"inverter owns - parking one of them would leave the rest "
"pushing the same way with the guard satisfied",
}
UNIT_SOURCES = {
"device": "one inverter's own reported min/max rating",
"supervised": "max_w caps what may be WRITTEN to one setpoint entity",
"failsafe": "per-unit evidence, per-unit remedy: since SAFETY-30 it "
"grades THIS unit's command against THIS unit's OWN "
"measured power (0x0518), so what it learns is about one "
"device. The site-wide half moved to `sign_site`",
"maintenance": "the monthly recalibration is a pack procedure",
}
for _src, _why in sorted(SITE_SOURCES.items()):
print(f" site {_src:<11} {_why}")
for _src, _why in sorted(UNIT_SOURCES.items()):
print(f" unit {_src:<11} {_why}")
check("all TEN claim sources are classified, and only those ten",
set(CLAIM_SCOPE) == set(SITE_SOURCES) | set(UNIT_SOURCES))
check("the six that are about the GRID CONNECTION are site claims",
{s for s, v in CLAIM_SCOPE.items() if v == SCOPE_SITE} == set(SITE_SOURCES))
check("the four that are about a PACK, a DEVICE or one write are per-inverter",
{s for s, v in CLAIM_SCOPE.items() if v == SCOPE_UNIT} == set(UNIT_SOURCES))
check("a source nobody classified cannot be routed at all - actuator_for() "
"raises rather than defaulting to the site, because defaulting to the "
"site is the failure this card removes",
_raises(lambda: actuator_for("reserve", "inverter-a", ("inverter-a",))))
print()
print("ARB-03 3. at N=1 the site IS the unit, so nothing moves")
# §6.2's identity: with one inverter the fabricated grid reading and the battery
# setpoint are the same number, so there is one actuator and it is both.
ONE = ("inverter-a",)
TWO = ("inverter-a", "inverter-b")
check("with one inverter every source routes to the site, per-inverter ones "
"included - that is the identity, not the classification being ignored",
all(actuator_for(s, "inverter-a", ONE) == ACTUATOR_SITE for s in CLAIM_SCOPE))
check("...and with none configured at all, likewise",
all(actuator_for(s, "inverter-a", ()) == ACTUATOR_SITE for s in CLAIM_SCOPE))
check("with TWO the identity breaks and the split becomes real: the four "
"per-inverter sources route to the unit this controller drives, the six "
"site sources stay on the grid connection",
{s: actuator_for(s, "inverter-a", TWO) for s in CLAIM_SCOPE}
== {**{s: "inverter-a" for s in UNIT_SOURCES},
**{s: ACTUATOR_SITE for s in SITE_SOURCES}})
print()
print("ARB-03 4. stage 2 IS the shipped arbiter (AC 3)")
# ⚠️ NOT ASSERTED, REPLAYED. Every claim list this file resolves above is run
# through BOTH entry points and every field the shipped code reads off a
# Resolution is compared. `resolve()` at N=1 is `site_resolve()` on the same
# list, so a single edit inside stage 2 would show up in every check above as
# well as here - and one that only affects the wrapper shows up only here.
REPLAY = [
[],
[Claim.set("loop", P_LOOP, 900)],
[Claim.set("loop", P_LOOP, 900), Claim.set("maintenance", P_MAINTENANCE, 2500)],
[Claim.set("loop", P_LOOP, 4000),
Claim.limit("supervised", P_SAFETY, lo=-2000, hi=2000, reason="max_w")],
[Claim.set("loop", P_LOOP, 4000), Claim.limit("a", P_SAFETY, hi=3000),
Claim.limit("b", P_SAFETY, hi=1500)],
[Claim.set("loop", P_LOOP, 900), charge_only],
[Claim.set("loop", P_LOOP, 900), charge_only, Claim.set("peak", P_PEAK, 2500)],
[Claim.set("peak", P_PEAK, 9000), charge_only,
Claim.limit("device", P_SAFETY, lo=-5000, hi=5000, reason="rating")],
[Claim.set("loop", P_LOOP, 900), Claim.set("safety", P_SAFETY, 0, "inputs missing")],
[Claim.set("loop", P_LOOP, 500), Claim.limit("x", P_SAFETY, lo=1000),
Claim.limit("y", P_SAFETY, hi=200)],
[Claim.set("loop", P_LOOP, -3000),
Claim.limit("supervised", P_SAFETY, lo=-1000, hi=1000)],
[Claim.set("loop", P_LOOP, -200), charge_only],
[Claim.set("arbitrage", P_ARBITRAGE, -2000, "buy"),
Claim.limit("peak", P_PEAK, lo=800.0, reason="quarter peak"),
Claim.limit("supervised", P_SAFETY, lo=-2000, hi=2000, reason="max_w")],
]
def _shape(r):
return (r.target_w, r.winner, r.bound_by, r.contradiction,
list(r.considered), r.explain())
_diff = [i for i, cl in enumerate(REPLAY)
if _shape(resolve(cl)) != _shape(site_resolve(cl))]
print(f" replayed {len(REPLAY)} claim lists through both entry points")
check("NOT ONE of them resolves differently - target, winner, binder, "
"contradiction flag, the considered list and the operator line are equal "
"on every one. At N=1 the three stages are the shipped arbiter with "
"bookkeeping either side of it", _diff == [] and len(REPLAY) >= 12)
check("...and stage 3 hands the whole target to the one actuator there is, "
"which is the N=1 identity rather than an allocation",
resolve([Claim.set("loop", P_LOOP, 900)]).shares == {ACTUATOR_SITE: 900.0})
check("...and says it allocated, because at N<=1 there is nothing to divide",
resolve([Claim.set("loop", P_LOOP, 900)]).allocated)
print()
print("ARB-03 5. THE CONTRADICTION THAT CANNOT BE WRITTEN DOWN (AC 4)")
# SAFETY-25 §0a, constructed. A per-inverter reserve says "this pack must not
# discharge" (`hi = 0`); the peak guard says "the site must deliver at least
# 1500 W" (`lo = 1500`). At N=1 those are two bounds on ONE number and they
# genuinely cross - which is today's behaviour, and today's hazard, and is left
# exactly as it is. Filed on TWO actuators they are bounds on two different
# numbers, and there is no expression in which one is the other's counterpart.
SITE_SIDE = [Claim.set("loop", P_LOOP, -1500.0, "grid"),
Claim.limit("peak", P_PEAK, lo=1500.0, reason="quarter peak")]
CROSSED = SITE_SIDE + [Claim.limit("maintenance", P_MAINT_SHAPE, hi=0.0,
reason="charge-only")]
SPLIT = SITE_SIDE + [Claim.limit("maintenance", P_MAINT_SHAPE, hi=0.0,
reason="charge-only", actuator="inverter-b")]
r_crossed, r_split = resolve(CROSSED), resolve(SPLIT)
print(f" both on one actuator: {r_crossed.explain()}")
print(f" the `hi` on inverter-b: {r_split.explain()} "
f"inverter-b bounds {r_split.unit_bounds['inverter-b'].explain()}")
check("filed on ONE actuator the pair still contradicts and still parks the "
"battery at 0 W in the billed quarter. That is the shipped behaviour and "
"this card does not change it - at N=1 the two really are bounds on one "
"number", r_crossed.contradiction and r_crossed.target_w == 0.0)
check("filed on TWO the site keeps its floor: the unit `hi` is not a term of "
"the site's `lo > hi` test, so there is no contradiction to flag",
not r_split.contradiction and r_split.target_w == 1500.0)
check("...and the constraint is not lost, it is CARRIED - inverter-b's own "
"interval still says 'do not discharge', for the allocator to honour when "
"it divides the 1500 W", r_split.unit_bounds["inverter-b"].hi == 0.0
and r_split.unit_bounds["inverter-b"].hi_src == "maintenance")
check("...and the site target is bit-for-bit what the site claims alone "
"resolve to, so the unit claim contributed NOTHING to it - which is the "
"'cannot be expressed' rather than 'is guarded against'",
_shape(site_resolve(SITE_SIDE))[:4] == _shape(r_split)[:4])
# Swept rather than argued: no per-inverter source, at any bound, on any unit,
# can reach the site's limits.
_SWEEP_N = _SWEEP_BAD = 0
for _src in sorted(UNIT_SOURCES):
for _unit in ("inverter-a", "inverter-b"):
for _lo, _hi in ((0.0, inf), (-inf, 0.0), (2500.0, inf), (-inf, -2500.0),
(900.0, 100.0)):
_r = resolve(SITE_SIDE + [Claim.limit(_src, P_MAINT_SHAPE, lo=_lo,
hi=_hi, actuator=_unit)])
_SWEEP_N += 1
if _r.contradiction or _r.target_w != 1500.0:
_SWEEP_BAD += 1
print(f" swept {_SWEEP_N} (per-inverter source x unit x bound) filings "
f"against a live site floor: {_SWEEP_BAD} disturbed the site target")
check(f"NOT ONE of the {_SWEEP_N} filings contradicts the site floor or moves "
f"the site target - including the last bound of each row, which is a unit "
f"contradicting ITSELF (lo 900 > hi 100). A unit's own impossible pair "
f"parks that unit; it does not park the site",
_SWEEP_BAD == 0 and _SWEEP_N >= 40)
_self_bad = resolve(SITE_SIDE + [Claim.limit("maintenance", P_MAINT_SHAPE,
lo=900.0, hi=100.0,
actuator="inverter-b")])
check("...and that unit says so on its own bounds, so the fault is reported "
"where it was made rather than swallowed",
_self_bad.unit_bounds["inverter-b"].contradiction
and "CONTRADICTION" in _self_bad.unit_bounds["inverter-b"].explain())
print()
print("ARB-03 6. stage 1: one unit's claims, one unit's interval")
mb = pre_resolve([Claim.limit("device", P_SAFETY, -5000, 5000, "rating"),
Claim.limit("supervised", P_SAFETY, -2000, 2000, "max_w"),
Claim.limit("maintenance", P_MAINT_SHAPE, hi=0.0, reason="charge-only")])
print(f" a unit filing rating, max_w and charge-only: {mb.explain()}")
check("the most restrictive of the unit's own limits is the interval",
mb.lo == -2000 and mb.hi == 0.0 and mb.hi_src == "maintenance"
and mb.lo_src == "supervised")
owned = pre_resolve([Claim.set("maintenance", P_MAINTENANCE, -2500, "charge"),
Claim.limit("supervised", P_SAFETY, -2000, 2000, "max_w"),
Claim.limit("maintenance", P_MAINT_SHAPE, hi=0.0, reason="charge-only")])
print(f" a unit whose maintenance owns the setpoint: {owned.explain()}")
check("a unit's own winning SET gates its own limits exactly as clause 2 does "
"at the site - the P_MAINT_SHAPE ceiling is not applied to a "
"P_MAINTENANCE drain that outranks it", owned.hi == 2000.0)
check("...and the SET's value travels BESIDE the interval, not inside it. "
"Folding -2500 into [-2500, -2500] would turn 'clamped to max_w' into "
"'contradicts max_w', which is a different answer and a wrong one",
owned.pinned_w == -2500 and owned.pinned_by == "maintenance"
and owned.gate == P_MAINTENANCE and not owned.contradiction)
print()
print("ARB-03 7 / ALLOC-01: the seam, and what now occupies it")
# ⚠️ THIS PART WAS "the seam is a seam, and NOT an allocator" AND IT GRADED THE
# DECLINE. ALLOC-01 filled the seam, so the decline at N>=2 is gone - and the
# checks that graded it are RE-AIMED rather than deleted, because the two halves
# they were really about are both still true and both still worth a line: the
# N<=1 pass-through is byte-identical, and the seam still does not BROADCAST.
check("with no units the whole target goes to the site actuator",
allocate(1500.0, {}) == ({ACTUATOR_SITE: 1500.0}, True))
check("with one unit the share IS the site target - §6.2's N=1 identity, "
"pass-through. ⚠️ A FLOAT, UNROUNDED AND UNCLAMPED: this is the "
"compatibility promise every N=1 replay in this repository depends on, "
"and the general path below does neither of those things",
allocate(1500.0, {"inverter-a": UnitBounds()})
== ({"inverter-a": 1500.0}, True))
check("...and it is byte-identical on a fractional target too, which is where a "
"'tidy this into the general path' refactor would show up: the general "
"path rounds to the 1 W register, the pass-through must not",
allocate(1500.4, {"inverter-a": UnitBounds()})
== ({"inverter-a": 1500.4}, True))
_shares, _ok = allocate(1500.0, {"inverter-a": UnitBounds(),
"inverter-b": UnitBounds()})
print(f" two units, ALLOC-01: shares={_shares} allocated={_ok}")
check("⚠️ AND THE ONE THING THE SEAM MUST NEVER DO, WHICH IS THE WHOLE OF "
"ARCH-01: it does not BROADCAST. Hand the site target to each inverter "
"and each supplies it IN FULL - the gain at the meter becomes N times the "
"per-unit gain, which admin/goodwe's two-master rig measures as a 4000 W "
"peak-to-peak limit cycle at gain 1.0 with not one guard firing. This "
"line went red on ARB-03's decline and it goes red on a broadcast, which "
"is the point: it grades the OUTPUT, not the mechanism",
1500.0 not in _shares.values())
check("...it allocates instead, and the shares SUM to the site target exactly. "
"That is the safety property: sum(s_i) = S is what makes the gain at the "
"meter a convex combination of the per-unit gains for ANY split, so the "
"weights are a comfort choice and a bad split cannot destabilise the site",
_ok is True and sum(_shares.values()) == 1500
and sorted(_shares) == ["inverter-a", "inverter-b"])
check("...and an odd target still sums exactly, which is the half a per-unit "
"round() gets wrong: 1501/2 is 750.5 twice, and two roundings of that are "
"either 1500 or 1502. Largest remainder gives 751 and 750",
sum(allocate(1501.0, {"inverter-a": UnitBounds(),
"inverter-b": UnitBounds()})[0].values()) == 1501)
check("⚠️ AND THE DECLINE IS NOT GONE, IT IS RE-AIMED. It is still correct when "
"no safe split exists at all, and PR #40's reviewer proved that branch was "
"unreachable and untested once already - removing its trigger without "
"giving it a new one would rebuild that hole. Here: every inverter's "
"master stale, so there is no envelope set to allocate into",
allocate(1500.0, {"inverter-a": UnitBounds(),
"inverter-b": UnitBounds()}, live=()) == ({}, False))
# ⚠️ AND `resolve()` HAS TO HONOUR THE ROSTER IT IS GIVEN, WHICH IS NOT THE SAME
# THING AS HAVING A `units` PARAMETER. Left None the roster is DERIVED from the
# claims, and that derivation is right only for a caller that files a claim for
# every unit every cycle. Ignore the argument and derive it always - `if units
# is None:` -> `if True:` - and a unit that filed nothing this cycle simply
# CEASES TO EXIST: the site of two looks like a site of one, the seam passes the
# whole grid target through to the single inverter that spoke, and ARCH-01's
# fault is built with the evidence for it removed. That mutation left this whole
# suite green until this check was written (PR #40 review), so it is graded on
# the one observation that distinguishes the two - a SILENT unit.
_silent = resolve([Claim.set("loop", P_LOOP, 900.0),
Claim.limit("device", P_SAFETY, -2000, 2000, "rating",
actuator="inverter-a")],
units=TWO)
print(f" roster of two, only inverter-a files: bounds="
f"{sorted(_silent.unit_bounds)} allocated={_silent.allocated} "
f"shares={_silent.shares}")
check("resolve() HONOURS the roster it is handed rather than inferring one from "
"who happened to speak. inverter-b filed nothing this cycle and is still "
"a unit: it gets its own interval, and the site is still a site of TWO, "
"so the target is SPLIT across two inverters",
sorted(_silent.unit_bounds) == ["inverter-a", "inverter-b"]
and _silent.shares == {"inverter-a": 450, "inverter-b": 450})
check("...and that is the whole cost of ignoring the argument, stated as the "
"number it would produce: derive the roster from the claims instead and "
"the site is a site of ONE, so the seam passes ALL 900 W through to "
"inverter-a - the silent inverter's absence read as a smaller site, and "
"inverter-a told to do the whole site's work on its own. ⚠️ ALLOC-01 "
"makes this mutation WORSE, not better: before, both answers refused, so "
"only the roster listing distinguished them; now the wrong one produces a "
"plausible number that is twice what inverter-a should be given",
resolve([Claim.set("loop", P_LOOP, 900.0),
Claim.limit("device", P_SAFETY, -2000, 2000, "rating",
actuator="inverter-a")]).shares
== {"inverter-a": 900.0})
check("...and left None the roster IS derived from the claims, which is the "
"documented default every N=1 replay above depends on - so the parameter "
"changes the answer only where the two disagree",
resolve([Claim.set("loop", P_LOOP, 900.0),
Claim.limit("device", P_SAFETY, -2000, 2000, "rating",
actuator="inverter-a")], units=None).allocated is True)
print()
print("ARB-03 8. verified by breaking it: a claim routed to the wrong stage (AC 6)")
# The `peak` floor, misfiled on a unit. It is the site's floor - if it lands on
# one inverter's interval the SITE keeps no floor at all, and the loop is free to
# go on charging through the quarter that sets the month's bill.
mis_peak = SITE_SIDE[:1] + [Claim.limit("peak", P_PEAK, lo=1500.0,
reason="quarter peak",
actuator="inverter-b")]
r_mis = resolve(mis_peak)
print(f" peak floor misfiled on inverter-b: {r_mis.explain()} "
f"scope_errors={r_mis.scope_errors}")
check("the mis-routing is CAUGHT: scope_violations names the source and the "
"actuator it does not belong on", len(r_mis.scope_errors) == 1
and "peak" in r_mis.scope_errors[0])
check("...and the reason it must be caught, measured rather than argued: with "
"the floor on a unit the SITE has no floor, so the loop charges 1500 W "
"into the quarter the guard was trying to shave",
r_mis.target_w == -1500.0 and resolve(SITE_SIDE).target_w == 1500.0)
check("a UNIT source filed on the site at a site that HAS named units is "
"caught too - that is the direction that produces `lo > hi`",
scope_violations(SITE_SIDE + [
Claim.limit("maintenance", P_MAINT_SHAPE, hi=0.0),
Claim.limit("device", P_SAFETY, -1, 1, actuator="inverter-b")]) != [])
check("...and at N=1, where every source legitimately routes to the site, the "
"same list is clean. The check grades ROUTING, not tidiness",
scope_violations(SITE_SIDE + [
Claim.limit("maintenance", P_MAINT_SHAPE, hi=0.0)]) == [])
check("an unclassified ninth source is a violation wherever it is filed",
scope_violations([Claim.limit("reserve", P_LOOP, hi=0.0)]) != [])
check("and the eight, routed by actuator_for() at a two-inverter site, are "
"clean - which is what says the router and the checker agree",
scope_violations(
[Claim.limit(s, P_SAFETY, -1, 1,
actuator=actuator_for(s, "inverter-a", TWO))
for s in CLAIM_SCOPE]) == [])
# --- ALLOC-01: AND NOW SOMETHING HAPPENS ABOUT IT ---------------------------
# ⚠️ ARB-03 LEFT THIS DELIBERATELY INERT - `scope_violations()` logged and did
# not change the resolution, and nothing graded the consequence. ALLOC-01 had to
# decide, and decided the allocator CONSUMES it as a REFUSAL rather than as an
# input. The reasoning is at `allocator.plan()`'s REFUSAL 1 and the short form
# is: the mis-routed claim has already been partitioned by the time stage 3
# runs, so its effect is baked into S or into somebody's interval; "consuming"
# it as an allocation input would mean RE-ROUTING it, which needs a guess about
# which inverter it belonged to that nothing here can make. What is left is that
# S itself may be wrong, and dividing a number that may be wrong is worse than
# not dividing it.
print(f" and stage 3's answer to it: {r_mis.allocation.explain()}")
check("⚠️ the mis-routing is no longer only a log line: stage 3 REFUSES to "
"allocate on a claim list it has been told is mis-routed, so main.py "
"fails toward inaction and shouts instead of dividing a number that may "
"be wrong. That is the same answer clause 3 already gives a contradiction",
r_mis.allocated is False and r_mis.shares == {}
and "mis-routed" in r_mis.allocation.refused)
check("...and it is NOT consumed as an ENVELOPE, which is the tempting reading "
"and the wrong one: a unit-scoped claim that landed on the site names no "
"unit, so promoting it means either guessing one or applying one "
"inverter's rating to a sibling that does not have it. Nothing here is "
"promoted - the refusal carries no shares at all",
r_mis.allocation.plans == () and r_mis.allocation.dropped == ())
check("...and a correctly routed cycle is unaffected, which is what says this "
"grades ROUTING and not the presence of units: the same site claims with "
"the floor where it belongs allocate normally",
resolve(SITE_SIDE, units=TWO).allocated is True)
print()
if fails:
print(f"{len(fails)} FAILED: {', '.join(fails)}")
+430 -9
View File
@@ -4,8 +4,8 @@
No framework, asserts only, same house style as test_freeze.py.
Six parts, and parts 3 and 4 are the ones that carry SAFETY-03's own
acceptance criteria; part 6 is TEST-11's:
Seven parts, and parts 3 and 4 are the ones that carry SAFETY-03's own
acceptance criteria; part 6 is TEST-11's and part 7 is SAFETY-28's:
1. THE CLAMP ARITHMETIC, on the shipped `clamp_to_rating()` - boundaries,
symmetry, the device second stage, and the non-finite cases. Table driven.
@@ -31,6 +31,13 @@ acceptance criteria; part 6 is TEST-11's:
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().
7. SAFETY-28. THE WRITE PATH IS GATED ON THE ALLOCATION RECORD - a value the
single allocator did not place on THIS tick does not reach the wire, a
record from a previous tick cannot authorise one, and 0 W is authorised
unconditionally so the failsafe can never deadlock behind the gate. This is
the check that replaced a config-shape proxy: `ACTUATOR_WRITE_KEYS` graded
how many option KEYS exist, which stays 1 while a per-inverter config adds
a second real writer.
------------------------------------------------------------------------------
WHY PART 4 ALSO ASSERTS ON `Decision`'s BOOLEANS AND NOT ON `reason`
@@ -65,6 +72,7 @@ Read MUTATION.md before you report a survivor.
"""
import asyncio
import io
import math
import sys
from datetime import datetime, timedelta, timezone
@@ -73,7 +81,10 @@ from app.clamp import (
CLEAR_CYCLES, REASON_CODE, REASSERT_S, ClampWatchdog, clamp_to_rating,
is_commandable,
)
from app.allocator import Allocation, UnitPlan, plan
from app.arbiter import P_LOOP, Claim, UnitBounds, allocate, resolve
from app.control import Tuning, compute
from app.inverter import Inverter
from app.main import Controller
fails = []
@@ -531,16 +542,48 @@ print()
print("5. no path reaches the wire around the clamp")
def arm(c, value):
"""Give `c` a real allocation record authorising `value` on the CURRENT tick.
⚠️ SAFETY-28 MADE THIS NECESSARY, AND THE FACT THAT IT IS NECESSARY IS THE
TICKET. `write_setpoint()` now refuses any value the single allocator did
not place on this tick, so the probes below - which call it directly, the
way the heartbeat and the operator's buttons do - have to say where their
number came from. Before this they did not, and that was precisely the hole:
a second writer's number reached the wire on nothing but the fact that
somebody called the method.
⚠️ AND IT IS BUILT THROUGH THE SHIPPED `resolve()`, NOT BY HAND. A helper
that assembled an `Allocation` itself would be a second allocator living in
the test file, and every check below would then be grading the fixture's
idea of a record rather than the one main.py produces. The tick is bumped
the same way `cycle()` bumps it, for the same reason.
"""
c.alloc_tick += 1
res = resolve([Claim.set("loop", P_LOOP, value, "test stimulus")],
units=c.units, live=c.units, tick=c.alloc_tick)
c.allocation = res.allocation
return res.allocation
async def _direct():
hass = _Hass(0.0)
c = Controller({"setpoint_entity": "number.sp", "max_w": 2000,
"meter_source": "off"},
hass, _Store(), _Pub(), stop=asyncio.Event())
c.dev_min, c.dev_max = -LIVE_MAX_W, LIVE_MAX_W
# The shape the heartbeat, shutdown() and handle_action() all use.
await c.write_setpoint(9999.0, force=True)
await c.write_setpoint(-9999.0, force=True)
# The shape the heartbeat, shutdown() and handle_action() all use - each one
# authorised by this tick's allocation, which is what those callers have
# too: the heartbeat re-affirms `self.target`, and the buttons write 0 W,
# which needs no allocator at all (see part 7).
for wanted in (9999.0, -9999.0):
arm(c, wanted)
await c.write_setpoint(wanted, force=True)
# A nan is loss of input, not an unauthorised write: rule 1 turns it into
# 0 W ABOVE the gate, and 0 W is always authorised. No arming, on purpose -
# if the gate ever moved above the coercion this line would go red.
await c.write_setpoint(float("nan"), force=True)
arm(c, 1500.0)
await c.write_setpoint(1500.0, force=True)
return hass, c
@@ -558,6 +601,56 @@ 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))
# --- 5b. ALLOC-01: AND THE ALLOCATOR DID NOT ADD ONE ------------------------
# ⚠️ "NO PATH REACHES THE WIRE AROUND THE CLAMP" IS A CLAIM ABOUT THE WHOLE
# ADD-ON, so it has to be re-made every time a module learns to produce a number
# that looks like a setpoint. ALLOC-01 added `app/allocator.py`, whose output is
# a dict of per-inverter watts - numbers that are exactly the shape of a thing
# somebody would write - and the temptation it creates is real: a second writer
# for a second inverter is DEV-02's card, and the wrong way to build it is a
# `set_number` call next to the allocation.
#
# Two checks, and neither is about the allocator's arithmetic:
# * it CANNOT write, and that is established from its imports rather than
# from its behaviour, because a behavioural check only sees the paths a
# fixture happens to take;
# * at the shipped roster the number that reaches the wire is still the
# arbiter's `target_w`, unclamped by the allocator, so SAFETY-03's clamp is
# still the binding one and not a second opinion after a first clamp.
import app.allocator as _alloc_mod # noqa: E402
_alloc_src = io.open(_alloc_mod.__file__, encoding="utf-8").read()
_alloc_imports = sorted(
n.split(".")[0]
for line in _alloc_src.splitlines() if line.startswith(("import ", "from "))
for n in [line.split()[1]])
print(f" app/allocator.py imports: {_alloc_imports}")
check("the allocator imports NOTHING that can reach the wire - no `hass`, no "
"`aiohttp`, not even `main`. It is a pure function of intervals and a "
"number, so 'it cannot write' is a property of the file rather than of "
"the paths a fixture happened to take",
_alloc_imports == ["dataclasses", "math"])
check("...and it never mentions the setpoint entity, `set_number`, or the "
"clamp - the three names any bypass would have to spell",
not any(n in _alloc_src for n in ("set_number", "setpoint_entity",
"clamp_to_rating")))
check("...and it must not: it has no measurement either. The allocator reading "
"P1 would be a SECOND integrator on the site measurement, which is the "
"same two-writers failure one level up",
not any(n in _alloc_src for n in ("p1", "P1Ingest", "grid_w")))
check("at the shipped roster of ONE the allocator is a pass-through, so the "
"number handed to write_setpoint() is the arbiter's own target and "
"SAFETY-03's clamp is still the FIRST and only clamp it meets. An "
"allocator that pre-clamped here would leave this file grading a value "
"that was already in range, and the clamp untested on the live path",
allocate(9999.0, {"inverter-a": UnitBounds()}) == ({"inverter-a": 9999.0},
True))
check("...and that unclamped 9999 W is exactly what part 5 above just proved "
"the write path stops at the rating. The two halves meet here: the "
"allocator does not clamp, the wire does",
hass_d.writes[0] == 2000.0)
# ==============================================================================
print()
print("6. TEST-11: the guard's evidence is THIS cycle's write, not the last one")
@@ -690,13 +783,21 @@ class _RefactoredController(Controller):
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.
⚠️ THE SIGNATURE GAINED `unit=` IN DEV-02 AND THIS FIXTURE FOLLOWED IT, which
is the honest update and not a weakening: `write_setpoint()` now addresses ONE
inverter (or, with `unit=None`, commands the whole site to 0 W), because a
controller with a roster cannot have one write path that means "the
inverter". A delegate that dropped the argument would silently re-broadcast
at N>=2, so it is passed through here exactly as a real refactor would have
to pass it through.
"""
async def _emit_setpoint(self, value, *, force=False):
await Controller.write_setpoint(self, value, force=force)
async def _emit_setpoint(self, value, *, force=False, unit=None):
await Controller.write_setpoint(self, value, force=force, unit=unit)
async def write_setpoint(self, value, *, force=False):
await self._emit_setpoint(value, force=force)
async def write_setpoint(self, value, *, force=False, unit=None):
await self._emit_setpoint(value, force=force, unit=unit)
async def _clamp_guard(self):
await Controller.check_output_clamp(self)
@@ -747,6 +848,11 @@ async def _write_path(moved=False):
# 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
# SAFETY-28: the write path only carries numbers the allocator placed, so
# this stimulus is authorised the same way cycle()'s is. It has to be: the
# clamp is what this part grades, and a gate refusal would substitute 0 W
# and there would be no clamp to see.
arm(c, c.target)
if moved:
await c.check_output_clamp()
await c.write_setpoint(c.target)
@@ -792,6 +898,321 @@ 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()
print("7. SAFETY-28: the write path is gated on the allocation record")
# WHY THIS PART IS IN THIS FILE. Part 5 already claims "no path reaches the wire
# around the clamp", and the clamp is the last thing between a bug and the
# hardware. SAFETY-28 adds a second thing on the same path and asks a different
# question of it: not "is this number in range" but "WHO CHOSE THIS NUMBER".
#
# THE DEFECT IT REPLACES. specs §1.5 makes two writers on one actuator a
# non-goal, and until this ticket that was enforced by
# `len(validate.ACTUATOR_WRITE_KEYS) == 1` - one option key, so a second writer
# is not expressible. True, and a statement about the OPTIONS SCHEMA rather than
# about the writes: add CFG-04's per-inverter config and there are two real
# writers with that length still 1. test_validate.py part 2 grades the config
# half; this part grades the write half, which is the one that does not care
# what the options look like.
A_UNIT, B_HYPO = "inverter-a", "inverter-b"
def fresh(**over):
"""A Controller with a stub HA, no cycle run, and therefore NO record."""
hass = _Hass(0.0)
c = Controller(dict({"setpoint_entity": "number.sp", "max_w": 2000,
"meter_source": "off"}, **over),
hass, _Store(), _Pub(), stop=asyncio.Event())
c.dev_min, c.dev_max = -LIVE_MAX_W, LIVE_MAX_W
return hass, c
# --------------------------------------------------------------------------- #
# 7a. AC 1 - an unauthorised value is REFUSED AT THE WRITE PATH
# --------------------------------------------------------------------------- #
# The second writer, modelled as what it would actually look like in code: some
# other strategy with arithmetic of its own calling the one method that reaches
# the wire. It has a perfectly reasonable number - in range, finite, nothing the
# clamp would object to - and the only thing wrong with it is that nothing
# allocated it.
async def _second_writer():
hass, c = fresh()
arm(c, 1500.0) # the allocator placed 1500 W this tick
await c.write_setpoint(1500.0, force=True) # the loop's own write
await c.write_setpoint(1200.0, force=True) # ...and the second writer's
return hass, c
hass_2w, ctl_2w = asyncio.run(_second_writer())
print(f" allocator placed +1500 W; a second writer asked for +1200 W; "
f"the device saw {hass_2w.writes}")
check("AC 1: a value the allocation record does not contain never reaches the "
"device. 1200 W is in range and finite - the clamp has no opinion about "
"it - so the ONLY thing that stopped it is that no allocator placed it",
1200.0 not in hass_2w.writes)
check("...and it is REFUSED, not merely logged: 0 W goes on the wire in its "
"place. Returning instead would leave the inverter latched on the last "
"command with the ESP32 heartbeat still being fed - holding an "
"unauthorised setpoint quietly, which is the outcome this gate exists "
"to prevent",
hass_2w.writes == [1500.0, 0.0])
check("...and the action log says so in words an operator can act on",
any("WRITE REFUSED" in e for e in ctl_2w.events))
check("...while the authorised write of the SAME shape went through "
"untouched, so the gate is not simply refusing everything",
hass_2w.writes[0] == 1500.0)
# --------------------------------------------------------------------------- #
# 7b. AC 2 - a record from a previous tick cannot authorise a write in this one
# --------------------------------------------------------------------------- #
# ⚠️ THIS IS THE CACHED-ENVELOPE FAULT WEARING A DIFFERENT HAT. allocator.py's
# rule is that a unit's interval is read per tick and never cached, because a
# pack at its floor or a stale link moves it between one cycle and the next.
# A record is that envelope written down - so code that keeps one and replays it
# is caching the envelope through the record, and the allocator's own purity
# cannot stop it. The tick stamp is what stops it.
async def _replay():
hass, c = fresh()
stale = arm(c, 1500.0) # tick N
await c.write_setpoint(1500.0, force=True)
arm(c, 800.0) # tick N+1: the envelopes have moved on
c.allocation = stale # ...and somebody puts the old one back
await c.write_setpoint(1500.0, force=True)
return hass, c, stale
hass_rp, ctl_rp, stale_rec = asyncio.run(_replay())
print(f" a tick-{stale_rec.tick} record replayed on tick "
f"{ctl_rp.alloc_tick}: the device saw {hass_rp.writes}")
check("AC 2: replaying the previous tick's record does NOT authorise its "
"value again - the write is refused and 0 W goes out instead",
hass_rp.writes == [1500.0, 0.0])
check("...and the refusal names both ticks, so the reason is legible rather "
"than 'computer says no'",
"tick" in (ctl_rp.write_refusal(1500.0) or "")
and str(stale_rec.tick) in (ctl_rp.write_refusal(1500.0) or "")
and str(ctl_rp.alloc_tick) in (ctl_rp.write_refusal(1500.0) or ""))
check("...and an UNSTAMPED record - one built by a caller that passed no tick "
"at all - is refused too, because 'I cannot say when I was made' must "
"fail closed and not read as tick zero",
ctl_rp.allocation is not None
and (lambda c: (setattr(c, "allocation",
plan(1500.0, {A_UNIT: UnitBounds()}))
or c.write_refusal(1500.0) is not None))(ctl_rp))
# ⚠️ AND THE TICK HAS TO ADVANCE ON THE LIVE PATH, WHICH IS A DIFFERENT CLAIM
# FROM ANY OF THE ABOVE. Everything so far drives `arm()`, which bumps the
# counter itself - so all of it would stay green with `self.alloc_tick += 1`
# deleted from cycle(), and the replay protection would be gone on the only path
# that matters. This drives REAL cycles and asks the same question of them.
async def _live_staleness():
hass = _Hass(6000.0)
c = Controller({"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, "step_w": 10, "stale_input_s": 15},
hass, _Store(), _Pub(), stop=asyncio.Event())
c.auto = True
c.dev_min, c.dev_max = -LIVE_MAX_W, LIVE_MAX_W
await c.read_inputs()
await c.cycle()
first, first_v = c.allocation, c.target
await c.read_inputs()
await c.cycle()
# ...and now the HOLD: one missed poll, which must NOT age the record, or a
# single dropped meter reading would drop the site to 0 W.
held_before = c.alloc_tick
c.grid = None
c.inputs_bad_since = datetime.now(timezone.utc)
await c.cycle()
hass.writes.clear()
await c.write_setpoint(c.target, force=True) # the heartbeat's own call
return c, first, first_v, held_before, hass
ctl_ls, rec1, val1, held_before, hass_ls = asyncio.run(_live_staleness())
print(f" two real cycles: tick {rec1.tick} -> {ctl_ls.allocation.tick}; "
f"a held cycle left it at {ctl_ls.alloc_tick}")
check("PRECONDITION: two real cycles produced two records with two different "
"ticks and a value worth replaying",
rec1.tick != ctl_ls.allocation.tick and val1 != 0.0)
check("the tick advances on the LIVE path, so cycle 1's record does not "
"authorise a write on cycle 2. Everything above this line drives the "
"test's own `arm()` and would stay green with the increment deleted from "
"cycle() - this is the check that would not",
(lambda c: (setattr(c, "allocation", rec1)
or c.write_refusal(val1) is not None))(ctl_ls))
check("⚠️ AND A CYCLE THAT PRODUCED NO RESOLUTION DOES NOT AGE IT. The "
"'inputs missing, not yet stale' hold returns before the allocator runs, "
"precisely so one dropped meter reading does not zero the inverter, and "
"the heartbeat re-affirms self.target through this same gate while it "
"does. A tick incremented per LOOP ITERATION rather than per RESOLUTION "
"would refuse that heartbeat and turn the hold into the outage it exists "
"to prevent",
ctl_ls.alloc_tick == held_before and hass_ls.writes == [ctl_ls.target]
and ctl_ls.target != 0.0)
# --------------------------------------------------------------------------- #
# 7c. THE FAILSAFE CANNOT DEADLOCK BEHIND THE GATE
# --------------------------------------------------------------------------- #
# ⚠️ THE HAZARD THIS PART EXISTS FOR. `write_setpoint()` is also how layer 2
# commands 0 W: cycle()'s two refusal branches substitute a 0 W failsafe and
# write it like any other cycle, and shutdown() and the operator's stop button
# do the same. Every one of those runs while the allocator has REFUSED - `ok` is
# False and there are no shares - so a gate that asked the allocator's
# permission to command zero would block the safety write behind the very
# component whose failure the safety write answers. A gate that can do that is
# worse than the hole it closes.
#
# The resolution: 0 W is authorised unconditionally, and it is authorised on the
# VALUE rather than on a `failsafe=True` flag the caller asserts. The argument is
# at Controller.write_refusal(): the hazard §1.5 names is N-times loop gain from
# broadcasting one target to N inverters, and at S = 0 the broadcast and the
# correct allocation COINCIDE - a_i = 1 for every unit gives every unit 0 W,
# which is exactly its share. There is no over-command to make at zero.
_hostile = []
_h, _c = fresh()
_hostile.append(("no record at all", _c))
_h, _c = fresh()
_c.alloc_tick = 1
_c.allocation = plan(1500.0, {A_UNIT: UnitBounds()}, scope_errors=("mis-routed",),
tick=1)
_hostile.append(("the allocator REFUSED this tick", _c))
_h, _c = fresh()
_c.allocation = arm(_c, 1500.0)
_c.alloc_tick += 7 # ...and then seven ticks went by
_hostile.append(("only a stale record", _c))
for _why, _c in _hostile:
check(f"0 W is authorised with {_why}", _c.write_refusal(0.0) is None)
check(f"...and a NON-zero write is still refused with {_why}, so the zero "
f"exit is a floor and not an amnesty",
_c.write_refusal(1500.0) is not None)
async def _failsafe_wire():
"""The refusal path END TO END, through the real cycle().
⚠️ THE ROSTER HERE IS A HYPOTHESIS AND NOTHING IS MEASURED FROM IT.
INVERTER B DOES NOT EXIST. It is named only so `live_units()` can return
nothing and drive the allocator into REFUSE_EMPTY, which is the state
main.py's first refusal branch is written for and the one this check needs:
the allocator itself has failed, and layer 2 must still be able to command
zero.
"""
hass = _Hass(0.0)
class _Blind(Controller):
def live_units(self):
return ()
c = _Blind({"setpoint_entity": "number.sp", "meter_source": "off",
"max_w": LIVE_MAX_W, "soc_entity": "sensor.soc",
"batt_entity": "sensor.batt", "meter_entity": "sensor.grid"},
hass, _Store(), _Pub(), stop=asyncio.Event())
# ⚠️ DEV-02: THE ROSTER IS GROWN BY ADDING AN `Inverter`, NOT BY ASSIGNING
# `units`. `Controller.units` is now DERIVED from `Controller.inverters` and
# has no setter, because a settable roster is a site that claims two
# actuators while holding one writer - a half-driven site with nothing to
# say so. The object carries the writer, which is what makes this fixture a
# roster of two rather than a tuple of two names.
c.dev_min, c.dev_max = -LIVE_MAX_W, LIVE_MAX_W # while the roster is one
_b = Inverter(B_HYPO, setpoint_entity="number.sp_b",
soc_entity="sensor.soc", batt_entity="sensor.batt",
max_w=LIVE_MAX_W, store=c.store)
_b.dev_min, _b.dev_max = -LIVE_MAX_W, LIVE_MAX_W
_b.soc, _b.batt = 50.0, 0.0
c.inverters.append(_b)
c.auto = True
for _ in range(3):
await c.read_inputs()
await c.cycle()
return hass, c
hass_fs, ctl_fs = asyncio.run(_failsafe_wire())
print(f" allocator refused every tick "
f"({ctl_fs.allocation.refused!r}); the device saw {hass_fs.writes}")
check("the allocator having failed, the 0 W failsafe still REACHES THE WIRE - "
"this is the deadlock the gate must not have, driven through the real "
"cycle() and its real refusal branch rather than asserted",
not ctl_fs.allocation.ok and hass_fs.writes == [0.0, 0.0]
and ctl_fs.target == 0.0)
check("...and it was the ALLOCATOR's refusal that produced it, not the gate's "
"- if the gate were the thing zeroing this cycle the action log would "
"say WRITE REFUSED and the distinction between the two failures would "
"be lost to whoever has to debug it",
any("ARBITER: REFUSED" in e for e in ctl_fs.events)
and not any("WRITE REFUSED" in e for e in ctl_fs.events))
# --------------------------------------------------------------------------- #
# 7d. `unmet_w` IS NOT `ok`, AND THE GATE MUST NOT FUSE THEM
# --------------------------------------------------------------------------- #
# allocator.py says it plainly: an allocation that could not place every watt is
# still SAFE TO WRITE and strictly better than commanding zero. Fusing the two
# would let ONE SATURATED INVERTER PARK THE WHOLE SITE - the site target goes
# unmet by 3800 W, every share is legal, and a gate reading `unmet_w` would
# answer that by commanding 0 W and meeting even less of it.
_tight = plan(4000.0, {A_UNIT: UnitBounds(lo=-100.0, hi=100.0),
B_HYPO: UnitBounds(lo=-100.0, hi=100.0)}, tick=1)
_h, _c = fresh()
_c.alloc_tick, _c.allocation = 1, _tight
print(f" saturated site: {_tight.explain()}")
check("PRECONDITION: this record is ok AND has watts it could not place",
_tight.ok and _tight.unmet_w == 3800 and _tight.shares[A_UNIT] == 100)
check("the gate authorises this unit's share anyway. `unmet_w` is not read - "
"it is the site target that went unmet, not a broken allocation",
_c.write_refusal(100.0) is None)
check("...and it still refuses a value that is not the share, so 'do not read "
"unmet_w' has not been implemented as 'read nothing'",
_c.write_refusal(4000.0) is not None)
# --------------------------------------------------------------------------- #
# 7e. A RECORD THAT CONTRADICTS ITSELF AUTHORISES NOTHING
# --------------------------------------------------------------------------- #
# `UnitPlan.explain()` renders a share outside its own interval as
# "ENVELOPE VIOLATED, DO NOT WRITE". This is the DO NOT WRITE. The shape is the
# half-open clamp defect ALLOC-01 fixed: a plan stating the floor and a share
# below it in the same breath, and agreeing with itself.
#
# ⚠️ UNREACHABLE FROM THE ALLOCATOR AS IT STANDS, AND GRADED ANYWAY. At the
# shipped roster of one the pass-through's interval is (-inf, +inf) and every
# number is inside it. PR #40's reviewer proved what an unreachable ungraded
# branch is worth by replacing one with `if False:` and watching the whole suite
# stay green, so this one is exercised on a constructed record rather than
# trusted.
_liar = Allocation(target_w=500.0, sum_w=500, shares={A_UNIT: 500},
plans=(UnitPlan(A_UNIT, 500, 2000.0, math.inf, 1.0,
"weighted share"),), tick=1)
_h, _c = fresh()
_c.alloc_tick, _c.allocation = 1, _liar
print(f" {_liar.plans[0].explain()}")
check("PRECONDITION: the record is `ok`, and its share IS what the gate would "
"otherwise match on - so nothing but the envelope question stops it",
_liar.ok and _liar.shares[A_UNIT] == 500)
check("a share outside its own plan's interval is refused, and the refusal "
"quotes the plan's own DO NOT WRITE line",
"DO NOT WRITE" in (_c.write_refusal(500.0) or ""))
# --------------------------------------------------------------------------- #
# 7f. AC 5 - AT N=1 NOTHING CHANGES
# --------------------------------------------------------------------------- #
# The strongest form of this is not a new assertion, it is the 17 other files in
# this suite passing unedited on real cycles. What is added here is the
# statement that the live path is not being quietly zeroed: over part 3's
# sixty-cycle replay - the 10.3 runaway, an inverter that never follows - the
# gate refused nothing at all.
check("AC 5: across part 3's 60 real cycles the gate refused ZERO writes, so "
"the shipped one-inverter path reaches the wire exactly as it did "
"before. A gate that silently substituted 0 W here would leave every "
"clamp check above green and the install dead",
not [e for e in ctl_r.events if "WRITE REFUSED" in e])
check("...and the numbers those cycles put on the wire are the arbiter's own "
"target, unrounded and unaltered by the record it now has to appear in",
hass_r.writes and all(abs(w) <= LIVE_MAX_W for w in hass_r.writes))
print()
if fails:
print(f"{len(fails)} FAILED: {', '.join(fails)}")
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+709 -26
View File
@@ -114,12 +114,20 @@ from math import inf, isinf
from pathlib import Path
from app import peakguard
# ⚠️ THE DROP AND REFUSAL REASONS ARE IMPORTED, NOT TRANSCRIBED. A check that
# matched the English would stay green against an allocator that renamed the
# case out from under it, which is this repository's own named failure mode.
from app.allocator import (
DROP_STALE as ALLOC_DROP_STALE, REFUSE_EMPTY as ALLOC_REFUSE_EMPTY,
)
from app.arbiter import (
P_LOOP, P_MAINT_SHAPE, P_MAINTENANCE, P_PEAK, P_SAFETY, Claim, resolve,
ACTUATOR_SITE, CLAIM_SCOPE, P_LOOP, P_MAINT_SHAPE, P_MAINTENANCE, P_PEAK,
P_SAFETY, SCOPE_SITE, SCOPE_UNIT, Claim, resolve, scope_violations,
)
from app.control import Tuning, compute, peak_at_risk
from app.freeze import FreezeWatchdogConfig, looks_frozen, rail_w
from app import main as app_main
from app.inverter import Inverter
from app.main import Controller
from app.p1 import (
PLAUSIBLE_MAX_W, P1Ingest, QUARTER_S, QuarterAverager, make_sample,
@@ -170,20 +178,65 @@ def fresh_store(name: str) -> PeakStore:
return PeakStore(str(TMP / f"{name}.db"))
def read_option(key: str):
"""The shipped default for `key`, out of config.yaml.
# ⚠️⚠️ THESE THREE READERS WERE CHANGED BY CFG-04, AND THE OLD ONES WERE THE
# PERMISSIVE KIND. Read this before touching them.
#
# WHAT THEY USED TO DO. `read_option()` walked the whole file and took the FIRST
# line whose STRIPPED text started with `<key>:`; `_schema_bound()` did the same
# from `schema:` onwards. The docstring justified first-match by naming the one
# collision that existed - `peak_cap_w:` appears once under `options:` and once
# under `schema:` - and it was right about that one.
#
# WHY THAT STOPPED BEING SAFE. CFG-04's `inverters:` is a LIST OF OBJECTS, and
# its entries carry a `max_w:` of their own, indented six spaces under
# `schema:`. `line.strip()` throws the indentation away, so `read_schema_max
# ("max_w")` began answering with the PER-INVERTER bound instead of the site
# one - silently, and in this file's case correctly, because the two bounds
# happen to be the same `int(100,5000)` today. A reader that returns inverter
# #1's number and keeps passing is the failure mode this repository is named
# after: green, and not watching. config.yaml declares `inverters:` BEFORE
# `max_w:` deliberately so that the trap stays baited rather than sorted out by
# an ordering nobody would maintain.
#
# WHAT THEY DO NOW. A top-level option and a top-level schema key are at EXACTLY
# two spaces; anything nested is at four or more. So the anchor is the
# indentation, the file's two halves disambiguate `peak_cap_w` (the options half
# for a default, the schema half for a bound) and first-match is not relied on
# at all. And where a key really is ambiguous - the same key twice at top level
# in the same half - these RAISE instead of picking one, because a reader that
# guesses is how this got here.
#
# test_inverter.py part 12 runs all of them against a synthetic TWO-INVERTER
# config.yaml whose nested numbers differ from its flat ones, which is the only
# way to tell a reader that is anchored from one that is lucky.
def _cfg_halves():
body = (HERE / "config.yaml").read_text(encoding="utf-8")
marker = body.index("\nschema:")
return body[:marker], body[marker:]
⚠️ `peak_cap_w:` appears TWICE - once under `options:`, once under `schema:`.
test_tariff.py's part 9 documents the trap; this takes the FIRST match, which
is the options block, i.e. the number an install actually lands on.
"""
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 _top_level(half: str, key: str) -> list:
"""Every ` key: ...` line at EXACTLY two spaces. Raises if there are two."""
hits = [ln for ln in half.splitlines()
if ln.startswith(f" {key}:") and not ln[2:3].isspace()]
if len(hits) > 1:
raise AssertionError(
f"config.yaml declares {key!r} {len(hits)} times at the top level "
f"of one block: {hits!r}. This reader will not pick one for you - "
"an option with two defaults is a question for whoever wrote the "
"second, not a tie for a check to break.")
return hits
def read_option(key: str):
"""The shipped default for `key`, out of config.yaml's `options:` block."""
hits = _top_level(_cfg_halves()[0], key)
if not hits:
return None
try:
return float(hits[0].split(":", 1)[1].strip())
except ValueError:
return None
def read_schema_max(key: str):
@@ -202,11 +255,9 @@ def read_schema_min(key: str):
def _schema_bound(key: str, which: int):
body = (HERE / "config.yaml").read_text(encoding="utf-8")
marker = body.index("\nschema:")
for line in body[marker:].splitlines():
for line in _top_level(_cfg_halves()[1], key):
st = line.strip()
if st.startswith(f"{key}:") and "(" in st and ")" in st:
if "(" in st and ")" in st:
return float(st[st.index("(") + 1:st.rindex(")")].split(",")[which])
return None
@@ -914,6 +965,7 @@ class _Pub:
class _Hass:
def __init__(self):
self.writes = []
self.per_entity = []
self.notifications = []
# SAFETY-25. The whole payload, not only the id. AC 3 is about what the
# operator READS, so a fixture that records only that a notification
@@ -929,6 +981,11 @@ class _Hass:
async def set_number(self, entity, value):
self.writes.append(value)
# DEV-02. WHICH inverter each write went to, which is the only way to
# tell "both units were commanded their own share" from "one unit was
# commanded twice". `writes` keeps its old shape - a list of floats -
# because a dozen checks above read it that way.
self.per_entity.append((entity, value))
return True
async def call(self, domain, service, data):
@@ -1282,8 +1339,14 @@ _soc_src = ast.unparse(next(k.value for k in _call.keywords if k.arg == "soc"))
print(f" main.py's decide(batt_w=...) is `{_batt_src}`, decide(soc=...) is "
f"`{_soc_src}`")
check("...and the call site says so in the source: the argument is the measured "
"battery attribute, not the standing command and not the resolved target",
_batt_src == "self.batt")
"battery attribute, not the standing command and not the resolved target. "
"⚠️ DEV-02 MOVED WHICH ATTRIBUTE AND NOT WHICH KIND OF THING IT IS: "
"`self.batt` was one inverter's power used as a site measurement, and "
"`site_batt_w` is the SUM over the roster - still measured, still not "
"`standing` and not `self.target`. The reduction itself is graded in "
"test_inverter.py; what is pinned here is that a MEASUREMENT is what "
"sizes the floor",
_batt_src == "self.site_batt_w")
# ⚠️ SAFETY-24, AND ON THE SAME SINGLE CALL SITE. This grader takes the FIRST
# `.decide(` in main.py and reads a NAME rather than a value, so a second call
# site - or a decoy - would defeat it; this card deliberately adds neither, and
@@ -1291,8 +1354,14 @@ check("...and the call site says so in the source: the argument is the measured
check("...and `soc` is handed over as the MEASURED reading, bare. Not "
"`self.soc or 100`, not a `float(..., 100)`, not the maintenance floor: "
"a full battery is exactly the value that disarms SAFETY-24's floor, and "
"NOTES.md 4.4b records this project shipping that exact defaulting once",
_soc_src == "self.soc")
"NOTES.md 4.4b records this project shipping that exact defaulting once. "
"⚠️ DEV-02 MADE IT `pack_floor_soc` - THE EMPTIEST PACK - and the "
"defaulting hazard is unchanged and still the point: that property is a "
"bare `min()` over measured readings that answers None if ANY unit did "
"not read, because `decide()` treats None as floor-limited, which costs a "
"shave rather than a pack. An `or 100` anywhere on that path is the same "
"defect with two inverters",
_soc_src == "self.pack_floor_soc")
check(f"...and main.py has exactly ONE `peakguard.decide(` call site (it has "
f"{len(_peak_calls)}), so the call graded above is unambiguously the "
f"shipped one. Other modules may call their own decide() - OPT-04's "
@@ -1519,6 +1588,14 @@ check("...and its arbiter reason names the SoC floor rather than reusing "
# forbidden to cap. Swept rather than argued.
SWEEP_NEG = SWEEP_BOTH = SWEEP_N = 0
SWEEP_HI = True
# ⚠️ ARB-03 ADDS ONE DIMENSION TO THIS PROOF RATHER THAN RE-RUNNING IT UNCHANGED.
# `Claim` gained an `actuator`, and the asymmetry that makes this guard safe is
# now TWO facts, not one: `hi` is +inf on every claim it files, AND every claim
# it files is on the SITE actuator. A `lo` that landed on one inverter's interval
# would still have `hi = +inf` and would still never cap a discharge - and would
# leave the SITE, the thing the capacity tariff actually bills, with no floor at
# all. So the same combinations are swept for both.
SWEEP_SITE = True
for load in (0.0, CEIL - 500.0, CEIL, CEIL + 300.0, CEIL + 3000.0,
LIVE_MAX_W * 3):
for elapsed in (30.0, 450.0, 870.0):
@@ -1538,6 +1615,8 @@ for load in (0.0, CEIL - 500.0, CEIL, CEIL + 300.0, CEIL + 3000.0,
_c = peakguard.claim(_d)
if _c is not None and not (isinf(_c.hi) and _c.hi > 0):
SWEEP_HI = False
if _c is not None and _c.actuator != ACTUATOR_SITE:
SWEEP_SITE = False
print(f" swept {SWEEP_N} (load x elapsed x battery x SoC x floor) "
f"combinations, SoC included: {SWEEP_NEG} negative floors, "
f"{SWEEP_BOTH} decisions both floor-limited and saturated")
@@ -1548,6 +1627,12 @@ check(f"NOT ONE of the {SWEEP_N} combinations produces a negative floor. That "
SWEEP_NEG == 0 and SWEEP_N > 600)
check("...and `hi` stays +inf on every claim any of them files",
SWEEP_HI)
check("...and every one of them is filed on the SITE actuator, which is the "
"other half of the same asymmetry now that a claim has an actuator: the "
"billed quantity is the quarter's offtake AT THE GRID CONNECTION, so a "
"floor that bound one inverter's share would leave the site - the thing "
"the capacity tariff meters - with no floor at all",
SWEEP_SITE)
check("...and no combination is both floor-limited and saturated, so the two "
"notifications are exclusive on measured inputs and not merely by reading "
"the code", SWEEP_BOTH == 0)
@@ -2316,8 +2401,28 @@ check("...and so does the persistent notification, which outlives the page and "
# "deferred" is exactly the state in which a ninth source gets built by
# accident. Its revisit trigger is ALLOC-01, under which the reserve becomes a
# PER-INVERTER interval at the allocator rather than a ninth claim here.
# ⚠️ SAFETY-31 ADDED THE NINTH, DELIBERATELY, AND THIS IS THE PARAGRAPH THAT
# SENTENCE ASKS FOR. `circulation` is a SET at P_SAFETY on the SITE actuator,
# filed only while `circ_wd.tripped`. It is not the deferred loop-side reserve
# this tripwire was built to catch: it is not conditioned on a state of charge,
# it does not shape the loop, and it appears in NO cycle of the sweeps below -
# the dynamic halves of this part still observe exactly {device, supervised,
# loop} at every SoC from 0 to 100 %, because nothing in those fixtures
# circulates. What it does is stop the site when two inverters are measured
# pushing against each other. See DECISIONS/SAFETY-31-circulating-power.md.
# ⚠️ SAFETY-30 ADDED THE TENTH, AND IT NEEDS ITS OWN PARAGRAPH FOR THE REASON
# `circulation` needed one. `sign_site` is a SET at P_SAFETY on the SITE
# actuator, filed only while `site_sign_wd.tripped` AND the roster holds more
# than one inverter. It is not a second copy of `failsafe`: that one grades ONE
# unit's command against THAT unit's own measured power and parks that unit,
# while this grades the SUM of the commands against the meter and stops the
# site. It appears in NO cycle of the sweeps below - the dynamic halves still
# observe exactly {device, supervised, loop} at every SoC, because the shipped
# roster is one inverter and this claim cannot be filed there at all. See
# DECISIONS/SAFETY-30-per-unit-sign.md.
CLAIM_SOURCES = {"device", "supervised", "failsafe", "safety", "peak",
"arbitrage", "maintenance", "loop"}
"arbitrage", "maintenance", "loop", "circulation",
"sign_site"}
# The two appends that file a claim BUILT ELSEWHERE in the method. Named here so
# that a THIRD such indirection reads as an unrecognised append rather than as a
# silent gap in the scan.
@@ -2358,7 +2463,7 @@ check("every `claims.append(...)` in main.py's cycle is one this scan can READ "
"- a claim filed through a shape it cannot parse has to fail here rather "
"than be counted as nothing, which is how a scan like this goes quietly "
"vacuous", len(_appends) >= 10 and None not in _filed)
check("...and the sources that cycle can file are EXACTLY these eight. THIS is "
check("...and the sources that cycle can file are EXACTLY these nine. THIS is "
"what makes part 10 a tripwire: replay_loop() hand-builds the claim list, "
"so it cannot see a claim main.py adds - and a loop-side SoC reserve is a "
"NINTH source. Filing one takes this line red on the line it is written",
@@ -2376,9 +2481,17 @@ def cycle_claims(run):
seen = []
real = app_main.resolve
def _spy(claims):
def _spy(claims, **kw):
# ⚠️ `**kw` PASSES THE ROSTER THROUGH UNREAD, AND THAT IS THE WHOLE
# ADAPTATION ARB-03 MADE HERE. main.py now calls
# `resolve(claims, units=self.units)`; a spy with a fixed signature would
# raise a TypeError on every real cycle, which is loud, but a spy that
# DROPPED the roster would be silently grading a different arbitration
# from the one main.py performs. What is observed - `claims`, the list
# itself - is unchanged, so the two halves below still see exactly what
# they saw before, and a ninth source still goes red.
seen.append(list(claims))
return real(claims)
return real(claims, **kw)
app_main.resolve = _spy
try:
@@ -2467,6 +2580,576 @@ check("...and replay_loop() folding main.py's TWO P_SAFETY rating limits into "
and near(LOOP_MAX_W, read_option("max_w")))
# --- 10g. ARB-03: AND THE ACTUATOR EACH OF THEM IS FILED ON -----------------
# ⚠️ THE SAME PIN, ONE DIMENSION WIDER, AND FOR THE SAME REASON. 10f pins WHICH
# sources main.py can file. ARB-03 gave every claim an `actuator`, and a claim
# routed to the wrong stage is a defect 10f cannot see: the source set is
# unchanged when the peak floor is misfiled onto one inverter, and the site is
# then left with no floor at all in the quarter that sets the month's bill.
#
# It is also what keeps SAFETY-25 §0c honest from the other side. That table
# says the deferred loop reserve becomes a PER-INVERTER `hi` at stage A while
# the peak floor stays a SITE `lo` at stage B, and calls the crossing
# structurally impossible. The structure is `CLAIM_SCOPE`, so `CLAIM_SCOPE` is
# pinned to the AST-scanned set rather than trusted to agree with it.
check("every source main.py can file is CLASSIFIED site or per-inverter, and "
"nothing else is. A TENTH source now goes red twice - once here for "
"having no classification, once above for being a tenth - and it takes an "
"argument about what the claim is ABOUT to make either line green",
set(CLAIM_SCOPE) == CLAIM_SOURCES)
print(" site: " + ", ".join(sorted(s for s, v in CLAIM_SCOPE.items()
if v == SCOPE_SITE))
+ " | per-inverter: "
+ ", ".join(sorted(s for s, v in CLAIM_SCOPE.items() if v == SCOPE_UNIT)))
check("...and the split is the one ARB-03 argued, with SAFETY-31's and "
"SAFETY-30's additions: the six about the GRID CONNECTION are site "
"claims and the four about a pack, a device or one write are "
"per-inverter. `circulation` is a site claim because its quantity is "
"defined over the roster and is identically zero for any one unit; "
"`sign_site` is one because the number that tripped it is the SITE "
"target, which no single inverter owns - while `failsafe` beside it is "
"per-inverter because since SAFETY-30 it grades one unit's command "
"against that unit's OWN measured power",
{s for s, v in CLAIM_SCOPE.items() if v == SCOPE_SITE}
== {"loop", "peak", "arbitrage", "safety", "circulation", "sign_site"}
and {s for s, v in CLAIM_SCOPE.items() if v == SCOPE_UNIT}
== {"device", "supervised", "failsafe", "maintenance"})
# The shipped roster is ONE inverter, so §6.2's identity holds and every claim a
# real cycle files is a site claim. Observed on the claims main.py's own resolve
# was handed, not assumed from the routing table.
_real_acts = {(c.source, c.actuator) for c in _cl}
print(f" the real FLOOR-LIMITED cycle files: "
+ ", ".join(f"{s}@{a}" for s, a in sorted(_real_acts)))
check("at the SHIPPED one-inverter roster every claim a real cycle files is on "
"the SITE actuator, per-inverter sources included. That is §6.2's "
"identity - one inverter means the fabricated grid reading and the "
"battery setpoint are the same number, so there is one actuator and it is "
"both - and it is why ARB-03 is a pure refactor here",
all(a == ACTUATOR_SITE for _, a in _real_acts))
check("...and the arbiter agrees the routing is legal, on the list main.py "
"actually handed it", scope_violations(_cl) == [])
# And the day the roster grows, the SAME cycle must partition. Graded through
# main.py's own `actuator_of()` on a real Controller - the method every
# `claims.append` above routes through - rather than through a copy of it.
#
# ⚠️ DEV-02: THE ROSTER IS GROWN BY ADDING A REAL `Inverter`, NOT BY SETTING
# `c.units`. It used to be a tuple somebody could assign beside a roster of one,
# i.e. a site claiming two actuators with one writer - which is a half-driven
# site with nothing to say so - and `Controller.units` is now DERIVED from
# `Controller.inverters` and has no setter. Building the object is also what
# makes these checks mean more than they did: the second unit has its own
# setpoint entity, its own rating and its own device range, so the claims below
# are filed from ITS numbers rather than from a copy of A's.
#
# ⚠️ INVERTER B DOES NOT EXIST YET. Its rating here is a HYPOTHESIS: nothing in
# this file is a measured parameter for a second device (SPIKE-04 measures one).
# What is graded is the ARCHITECTURE - which actuator each claim lands on, and
# whose number each per-unit bound is built from.
#
# ⚠️ AND IT IS 3000 W RATHER THAN A's 5000 W, WHICH IS NOT COSMETIC. THE RULE,
# STATED AT THE LINE THAT NEEDED IT: ANY CHECK ASSERTING "X DIFFERS FROM Y" MUST
# BE RUN ONCE WITH X AND Y ACTUALLY MADE DIFFERENT. This helper used to default
# B's rating and device range to A's `LIVE_MAX_W`, and the AC 4 check below
# compared inverter B's `supervised` bound against `_b2.max_w` - which was
# LITERALLY THE SAME NUMBER as A's. It read as evidence and observed nothing:
# filing both per-unit claims from `self.inverters[0]`'s numbers instead of
# `inv`'s left all 19 files green. That is the third check this session whose
# DATA could not reach the failure it named (ARB-03's call-site scan saw 3 of 8
# sites; ALLOC-01's replay generator saw 0 escapes where a widened one saw
# 39,991), so the number is different HERE, once, for every fixture in the file.
B_RATING_HYPOTHESIS = LIVE_MAX_W - 2000.0
def second_inverter(ctl, *, name="inverter-b", setpoint="number.sp_b",
max_w=None, dev=None):
"""Append a real second `Inverter` to `ctl`, and return a restore()."""
rating = B_RATING_HYPOTHESIS if max_w is None else max_w
inv = Inverter(name, setpoint_entity=setpoint, soc_entity="sensor.soc_b",
batt_entity="sensor.batt_b", max_w=rating, store=ctl.store)
inv.dev_min, inv.dev_max = dev or (-rating, rating)
# The readings a real cycle needs from it. `inputs_ok` requires EVERY unit
# to have answered, which is the point - a pack nothing can grade stops the
# site rather than being quietly dropped from the split.
inv.soc, inv.batt = ctl.inverters[0].soc, 0.0
original = list(ctl.inverters)
ctl.inverters.append(inv)
def restore():
ctl.inverters[:] = original
return inv, restore
_b, _restore_b = second_inverter(c_src)
_routed = {s: c_src.actuator_of(s) for s in CLAIM_SOURCES}
_restore_b()
print(" with a second inverter on the roster, main.py routes: "
+ ", ".join(f"{s}->{a}" for s, a in sorted(_routed.items())))
check("⚠️ AND THIS IS THE BREAKING HALF. Give the same Controller a second "
"inverter and its OWN routing method splits the ten: `device`, "
"`supervised`, `failsafe` and `maintenance` bind the unit this controller "
"drives, `loop`, `peak`, `arbitrage`, `safety`, SAFETY-31's `circulation` "
"and SAFETY-30's `sign_site` stay on the grid connection. Swap any one of "
"them - route `peak` to the unit and the site keeps no floor; route "
"`maintenance` to the site and it can cross that floor into `lo > hi`; "
"route `circulation` to one unit and a site-wide loop parks the inverter "
"that may well be the one still listening; route `sign_site` to one unit "
"and a SITE total pointing the wrong way parks one inverter while the "
"rest of the roster goes on pushing the same way - and this line goes red",
_routed == {"device": "inverter-a", "supervised": "inverter-a",
"failsafe": "inverter-a", "maintenance": "inverter-a",
"loop": ACTUATOR_SITE, "peak": ACTUATOR_SITE,
"arbitrage": ACTUATOR_SITE, "safety": ACTUATOR_SITE,
"circulation": ACTUATOR_SITE, "sign_site": ACTUATOR_SITE})
check("...and the roster it was restored to is the shipped one, so nothing "
"below inherits a two-inverter Controller",
c_src.units == (app_main.UNIT_A,) and len(c_src.inverters) == 1)
# ⚠️ AND THE ROUTING TABLE BEING RIGHT IS NOT THE SAME AS THE CALL SITES USING
# IT RIGHT. `actuator_of("maintenance")` written at the `device` append routes a
# rating limit to whatever `maintenance` routes to, and at the shipped
# one-inverter roster BOTH answers are the site, so nothing above can see it.
# ⚠️ AND THE DYNAMIC CYCLE BELOW SEES ONLY THREE OF THE NINE DIRECT APPENDS.
# That was THIS PART committing this repository's own named failure - a check
# observing something other than what it claimed - inside the check written to
# prevent it. The first cut of 10g called the two-inverter cycle "the line a
# mis-typed `actuator_of(...)` at a call site goes red on", full stop. IT IS
# NOT. That cycle is auto, P1-healthy, no maintenance procedure, no tripped sign
# watchdog, the guard idle and arbitrage off, so it reaches `device`,
# `supervised` and `loop` AND NOTHING ELSE. PR #40's reviewer mutated the other
# five appends one at a time and every suite in this repository stayed GREEN,
# this part included. At the maintenance-shaping append,
# `actuator_of("maintenance")` -> `actuator_of("peak")` then produced, at a
# roster of two, a site loop of -1500 W against the guard's site `lo` of 1500 W
# and the now-misrouted charge-only `hi = 0`: `lo > hi`, arbiter clause 3, 0 W
# IN THE BILLED QUARTER - SAFETY-25 §0a's fatal case, built by a one-word typo
# under a green suite. The same mutation at the `failsafe` append survived too.
#
# So THE CALL SITES ARE PINNED STATICALLY, over 10f's own AST scan of
# `Controller.cycle()` and for 10f's reason: a static pin sees every append on
# the line it is written, in every configuration, whether or not any fixture
# here reaches the state that files it. All eight direct appends expose their
# actuator as a LITERAL - `actuator=self.actuator_of('<source>')` - so the
# literal is simply required to EQUAL the source the claim is filed under. That
# is what makes "a mis-typed `actuator_of(...)` goes red" a true sentence about
# all ten rather than about the three a fixture happens to reach.
def append_actuator(node):
"""The actuator expression a DIRECT append routes its claim through.
⚠️ RETURNED AS SOURCE TEXT, NOT EVALUATED, and that is the whole point.
`self.actuator_of('device')` and `self.actuator_of('maintenance')` are the
SAME VALUE at the shipped roster and two different routings; only the text
written at the call site tells them apart, which is exactly why every
dynamic check in this file is blind to the swap at N=1.
"""
kw = [k for k in node.keywords if k.arg == "actuator"]
if len(kw) != 1:
return None
return ast.unparse(kw[0].value)
# The appends that BUILD their claim in place - the nine whose routing is
# chosen by hand, and the only ones where a typo is possible - against the two
# that append a claim built elsewhere in the method and carry no `actuator=`
# here at all.
_direct = [n.args[0] for n in _appends if isinstance(n.args[0], ast.Call)]
_indirect = [n.args[0].id for n in _appends if isinstance(n.args[0], ast.Name)]
_routing = sorted(((c.args[0].value, append_actuator(c), c.lineno)
for c in _direct), key=lambda r: r[2])
# ⚠️ DEV-02 GAVE `actuator_of()` A SECOND ARGUMENT - the roster entry the claim
# is ABOUT - so a per-inverter append inside the `for inv in self.inverters:`
# loop reads `self.actuator_of('device', inv)`. The pin is unchanged in what it
# grades: the FIRST argument, the string literal, must still be the source the
# claim is filed under. What the second argument may be is deliberately NOT
# constrained here - it is a roster entry, and which one is a question the
# dynamic two-inverter cycle below answers on real claims - but its PRESENCE is,
# because a per-inverter claim built in that loop and routed with no `inv` files
# inverter B's rating on inverter A. That is graded at the line: a source
# classified SCOPE_UNIT must pass one.
def _routing_literal(a):
"""The first argument of `self.actuator_of(...)`, or None if it is not one."""
if not a.startswith("self.actuator_of("):
return None
return a[len("self.actuator_of("):-1].split(",")[0].strip()
_misrouted = [r for r in _routing if _routing_literal(r[1]) != repr(r[0])]
_unit_sources_unrouted = [
r for r in _routing
if CLAIM_SCOPE.get(r[0]) == SCOPE_UNIT and "," not in r[1]]
print(f" {len(_direct)} direct appends, each read at its own line: "
+ ", ".join(f"main.py:{ln} {s} -> {a}" for s, a, ln in _routing))
check("all TEN of `Controller.cycle()`'s DIRECT appends route through "
"`self.actuator_of(<string literal>)`, so this scan can read the routing "
"of EVERY one of them. An append that computed its actuator, or omitted "
"the argument, or hand-wrote a string, fails HERE rather than being "
"silently skipped - which is how a scan like this goes quietly vacuous, "
"and 10f is in this file because that already happened once",
len(_direct) == 10
and all(a is not None and a.startswith("self.actuator_of('")
for _s, a, _ln in _routing))
check("⚠️ AND AT EVERY ONE OF THE TEN THE LITERAL IT ROUTES THROUGH IS THE "
"SOURCE THE CLAIM IS FILED UNDER. THIS is the line a mis-typed "
"`actuator_of(...)` at a call site goes red on - all nine of them, on "
"the line the typo is written, at every roster, INCLUDING the six "
"appends no fixture in this repository reaches. "
"`actuator_of(\"peak\")` at the maintenance append is a different string "
"here even though it is the same VALUE at the shipped roster of one",
_misrouted == [])
check("⚠️ AND EVERY PER-INVERTER APPEND NAMES THE INVERTER IT IS ABOUT. "
"`actuator_of()` takes the roster entry as its second argument and "
"defaults to the FIRST one when it is left out - which is right for the "
"site-scoped sources and is the whole defect for a per-inverter one: a "
"`device` limit built inside the roster loop and routed without `inv` "
"files inverter B's rating on inverter A, where it binds the wrong "
"share. Five of the ten appends are SCOPE_UNIT - `device`, "
"`supervised`, `failsafe` and maintenance's two - and all five pass one. "
"SAFETY-30's `sign_site` is deliberately NOT one of them: it is filed on "
"the site, beside `circulation`, because the number that tripped it is "
"the site target",
_unit_sources_unrouted == []
and len([r for r in _routing
if CLAIM_SCOPE.get(r[0]) == SCOPE_UNIT]) == 5)
check("...and the only appends this pin does NOT reach are the two that file a "
"claim BUILT ELSEWHERE - `peak_claim` and `arb_claim` - which have no "
"`actuator=` at the call site to mis-type. Their routing is pinned where "
"it is CHOSEN instead: peakguard.claim() by the SWEEP_SITE sweep above, "
"over every load x elapsed x battery x SoC x floor combination, and "
"arbitrage.claim() by test_arbitrage.py",
sorted(_indirect) == sorted(CLAIM_BUILDERS)
and len(_direct) + len(_indirect) == len(_appends))
check("...and between them the eleven appends account for exactly the nine "
"sources 10f pins, so the routing pin and the source set are one scan "
"and neither can drift from the other",
{s for s, _a, _ln in _routing} | set(CLAIM_BUILDERS.values())
== CLAIM_SOURCES)
# THE DYNAMIC HALF, kept, and now stated for what it actually observes: a real
# cycle proving the routing reaches the arbiter THROUGH main.py rather than only
# through this file's reading of main.py. It grades three of the eight appends.
# The static pin above is what covers the other five.
_b2, _restore_b2 = second_inverter(c_src)
_n2_writes_before = len(c_src.hass.per_entity)
try:
_, _cl2 = cycle_claims(lambda: run_cycle(c_src))
_n2_target, _n2_reason = c_src.target, c_src.reason
_n2_events = list(c_src.events)
_n2_writes = c_src.hass.per_entity[_n2_writes_before:]
_n2_shares = {i.name: i.target for i in c_src.inverters}
_n2_last = {i.name: i.last_write for i in c_src.inverters}
_n2_alloc = c_src.allocation
finally:
_restore_b2()
print(" a REAL two-inverter cycle files: "
+ ", ".join(f"{c.source}@{c.actuator}" for c in _cl2))
check("a real cycle at a roster of TWO partitions its own claims correctly - "
"every claim main.py filed is on an actuator its source's scope permits, "
"observed on the list main.py's own `resolve` was handed. ⚠️ AND THIS "
"SEES THREE OF THE EIGHT APPENDS, NOT THE CLASS: this state files "
"`device`, `supervised` and `loop`, so it is the static pin above and not "
"this line that covers `failsafe`, `safety` and the two `maintenance` "
"appends", len(_cl2) >= 3 and scope_violations(_cl2) == [])
check("⚠️ AND THE RATING LIMITS ARE FILED ONCE PER INVERTER, ON ITS OWN "
"ACTUATOR - which is DEV-02 in one line. Before this card there was ONE "
"`device` pair, read from ONE `setpoint_entity`, filed once: a second "
"inverter's rating was never read and never bound anything, so its share "
"was clamped against the first one's numbers. Now the loop over the "
"roster files a pair per unit and the loop claim stays on the grid "
"connection",
sorted((c.source, c.actuator) for c in _cl2)
== [("device", "inverter-a"), ("device", "inverter-b"),
("loop", ACTUATOR_SITE), ("supervised", "inverter-a"),
("supervised", "inverter-b")])
check("...and naming those three is not an accident of this fixture but the "
"reason the static pin exists - SEVEN of the ten sources need a state "
"no check in this file reaches. SAFETY-31's `circulation` is one of the "
"seven: it is filed only while the site is MEASURED to be circulating, "
"which no fixture here is. SAFETY-30's `sign_site` is another, and it "
"needs TWO states at once - a roster of two AND the site's total command "
"standing opposed to the meter for its whole window",
{c.source for c in _cl2}
== CLAIM_SOURCES - {"failsafe", "safety", "maintenance", "peak",
"arbitrage", "circulation", "sign_site"})
# ⚠️ AND NOW THE HALF THAT WAS EVIDENCE-SHAPED AND OBSERVED NOTHING. The three
# checks above grade WHICH ACTUATOR each claim lands on. They say nothing about
# WHOSE NUMBERS the bound is built from - and those are two different defects
# with two different fixes. Filing the per-unit `device` and `supervised` claims
# from `self.inverters[0]`'s numbers while leaving `actuator=self.actuator_of(
# ..., inv)` alone routes every claim correctly and bounds inverter B by
# inverter A's rating: at A=5000/B=3000 the planned envelope for inverter-b
# becomes (-5000, 5000) instead of (-3000, 3000), which is a 2000 W
# over-command the arbiter believes is supervised.
#
# ⚠️ THE RULE THIS LINE EXISTS TO OBEY: ANY CHECK ASSERTING "X DIFFERS FROM Y"
# MUST BE RUN ONCE WITH X AND Y ACTUALLY MADE DIFFERENT. The version this
# replaces compared inverter B's bound against `_b2.max_w` while
# `second_inverter()` defaulted `max_w` to A's `LIVE_MAX_W` - so it compared
# 5000 against 5000, and the mutation above left all 19 files GREEN. The
# PRECONDITION below is what stops that happening again: it fails if the two
# ratings are ever made equal, so the check cannot go quietly vacuous.
_sup2 = {c.actuator: (c.lo, c.hi) for c in _cl2 if c.source == "supervised"}
_dev2 = {c.actuator: (c.lo, c.hi) for c in _cl2 if c.source == "device"}
print(f" supervised bounds by actuator: {_sup2}; device bounds: {_dev2}")
check("PRECONDITION, AND IT IS THE WHOLE POINT: A AND B HAVE DIFFERENT "
"RATINGS. A check that 'B's bound is B's own number' cannot observe "
"anything while B's number IS A's number, and this file shipped that "
"check for a whole review round",
_b2.max_w != c_src.inverters[0].max_w
and (_b2.dev_min, _b2.dev_max)
!= (c_src.inverters[0].dev_min, c_src.inverters[0].dev_max))
check("⚠️ AND EACH UNIT'S `supervised` BOUND IS ITS OWN `max_w`, NOT A COPY OF "
"THE FIRST UNIT'S. That is the sentence AC 4 is, and it is now stated "
"against LITERAL, DIFFERENT numbers rather than against an expression "
"that could be reading the same object twice: B is bounded at "
f"+/-{B_RATING_HYPOTHESIS:.0f} W and A at +/-{LIVE_MAX_W:.0f} W",
_sup2 == {"inverter-a": (-LIVE_MAX_W, LIVE_MAX_W),
"inverter-b": (-B_RATING_HYPOTHESIS, B_RATING_HYPOTHESIS)})
check("...and so is each unit's `device` bound, which is the other number the "
"same loop files and the one that was NEVER READ before this card - one "
"`dev_min`/`dev_max` pair came off one `setpoint_entity`, so a second "
"inverter's reported range bound nothing at all",
_dev2 == {"inverter-a": (-LIVE_MAX_W, LIVE_MAX_W),
"inverter-b": (-B_RATING_HYPOTHESIS, B_RATING_HYPOTHESIS)})
check("...and the bounds the ARBITER RESOLVED for inverter B - not just the "
"claims filed at it - are B's own, because a claim filed correctly and "
"then resolved against the wrong envelope would be the same defect one "
"layer down",
_n2_alloc is not None
and next((p for p in _n2_alloc.plans if p.unit == "inverter-b"), None)
is not None
and (lambda p: p.lo == -B_RATING_HYPOTHESIS
and p.hi == B_RATING_HYPOTHESIS)(
next(p for p in _n2_alloc.plans if p.unit == "inverter-b")))
# --- 10h. ALLOC-01: WHAT MAIN.PY DOES WITH AN ALLOCATION IT CANNOT DELIVER ---
# ⚠️ THIS PART WAS WRITTEN AGAINST `allocated=False` AND HAS BEEN RE-AIMED, NOT
# DELETED. ARB-03's `allocate()` declined at every roster of two or more,
# because it had no allocator and the obvious placeholder - hand the site target
# to each inverter - IS the ARCH-01 fault. ALLOC-01 filled the seam, so that
# trigger is gone. The branch is NOT, and this part is why it had better not be:
# PR #40's reviewer replaced main.py's `if not resolution.allocated:` with
# `if False:` and the whole 17-file suite stayed GREEN, so an unreachable-but-
# right instinct was one refactor away from being deleted as dead code.
# Removing the trigger without giving the branch a new one would rebuild that
# hole exactly.
#
# THERE ARE NOW TWO REFUSALS AND THEY ARE DIFFERENT REFUSALS, so all three
# states below are driven as REAL CYCLES through `Controller.cycle()`:
#
# 10h-1 the allocator SUCCEEDS and this controller cannot deliver the split.
# 10h-2 one inverter's master is stale: the survivor carries the whole site
# target, WHICH IS DELIVERABLE, and the drop is announced (AC 6).
# 10h-3 every master is stale: no envelope set, so the allocator itself
# refuses and `allocated=False` is reached for real.
#
# ⚠️ AND 10h-1 IS THE HALF DEV-02 CHANGED, SO IT HAS BEEN RE-AIMED AGAIN AND
# THE PREVIOUS AIM IS RECORDED HERE RATHER THAN DELETED. ALLOC-01 had to ADD
# this guard: there was one `setpoint_entity` in this add-on, so a controller
# handed a valid 450/450 split and a roster of two would have written
# `self.target` - 900, the SITE number - to the single inverter it could reach
# while a second sat uncommanded. Not the broadcast fault, but the same shape of
# over-command.
#
# DEV-02 gives it a writer per inverter, so that trigger is gone and the
# deliverable case is now the ORDINARY one: both units are commanded THEIR OWN
# SHARE, which is what 10h-1 grades below. The refusal survives with a trigger
# it can still reach - a roster entry with NO setpoint entity of its own - and
# 10h-1b drives it.
print(f" at N=2 the allocator produced {_n2_alloc.explain()}")
print(f" and main.py resolved to {_n2_target:+.0f} W, reason "
f"{_n2_reason!r}, wrote {_n2_writes}")
print(" and logged: "
+ next((e for e in _n2_events if "ARBITER" in e), "(nothing)"))
check("⚠️ THE ALLOCATOR NOW SUCCEEDS AT A ROSTER OF TWO, and the shares SUM to "
"the site target exactly rather than repeating it. That sum is the whole "
"safety property: it makes the gain at the meter a convex combination of "
"the per-unit gains, where a broadcast makes it N times the per-unit "
"gain - 4000 W peak-to-peak forever at gain 1.0 on admin/goodwe's "
"two-master rig, with not one guard firing",
_n2_alloc.ok and sorted(_n2_alloc.shares) == ["inverter-a", "inverter-b"]
and sum(_n2_alloc.shares.values()) == _n2_alloc.sum_w
and _n2_alloc.unmet_w == 0)
check("...and it did NOT broadcast: neither share is the site target, and "
"THAT is the line a placeholder `{u: target for u in units}` goes red on",
all(v != _n2_alloc.sum_w for v in _n2_alloc.shares.values())
or _n2_alloc.sum_w == 0)
check("⚠️ AND MAIN.PY NOW DELIVERS THE SPLIT. THIS IS DEV-02'S DELIVERABLE, "
"and it is the line that used to read 'refusing to command a partial "
"site'. Each inverter is written ITS OWN SHARE, to ITS OWN setpoint "
"entity, in one cycle - two entities, two numbers, and the two numbers "
"are the allocator's, not the site target repeated",
sorted(_n2_writes)
== sorted([("number.sp", float(_n2_alloc.shares["inverter-a"])),
("number.sp_b", float(_n2_alloc.shares["inverter-b"]))]))
check("...and neither entity was handed the SITE target, which is the "
"broadcast fault stated as a check on the wire rather than on the "
"allocator. Each unit supplying the site number IN FULL is 4000 W "
"peak-to-peak forever at gain 1.0 on admin/goodwe's two-master rig, with "
"not one guard firing",
_n2_target == 0.0 or all(v != _n2_target for _e, v in _n2_writes))
check("...and the resolution is NOT the 0 W failsafe any more: the site target "
"is a real number and it reached the hardware. That is the whole "
"difference this card makes to this part",
_n2_target != 0.0 and "failsafe" not in _n2_reason)
check("...and each inverter's own `last_write` records what IT was told, so "
"the heartbeat re-emits a SHARE rather than the site number and "
"SAFETY-02 grades each unit against the command IT is standing on",
_n2_last == {u: float(v) for u, v in _n2_alloc.shares.items()})
check("...and the action log no longer carries the 'no writer' refusal, "
"because there is a writer. This is the line that goes red if that "
"branch is left standing with its old trigger",
not any("no writer" in e for e in _n2_events))
# --- 10h-1b. THE RE-AIMED REFUSAL: A ROSTER ENTRY WITH NO WRITER ------------
# ⚠️ THE INSTINCT SURVIVES ITS TRIGGER, WHICH IS WHAT ALLOC-01 ASKED FOR WHEN IT
# SAID RE-AIM RATHER THAN DELETE - and PR #40's reviewer is why: replacing
# main.py's sibling branch with `if False:` left the whole suite green, so an
# unreachable-but-right guard was one refactor from being deleted as dead code.
# A configured inverter with no `setpoint_entity` of its own is still a unit
# this controller cannot put a number on, and commanding the ones it CAN reach
# would over-command them by exactly the missing unit's share.
_nw, _restore_nw = second_inverter(c_src, name="inverter-c", setpoint="")
_nw_writes_before = len(c_src.hass.per_entity)
try:
_, _cl_nw = cycle_claims(lambda: run_cycle(c_src))
_nw_target, _nw_reason = c_src.target, c_src.reason
_nw_events = list(c_src.events)
_nw_writes = c_src.hass.per_entity[_nw_writes_before:]
finally:
_restore_nw()
print(f" a roster entry with no setpoint entity: main.py resolved to "
f"{_nw_target:+.0f} W, reason {_nw_reason!r}, wrote {_nw_writes}")
print(" and logged: "
+ next((e for e in _nw_events if "ARBITER" in e), "(nothing)"))
check("⚠️ A UNIT WITH NO WRITER TAKES THE SITE TO THE 0 W FAILSAFE. It is a "
"CONFIGURATION that cannot be delivered - not a link that went away, "
"which is the dropped case below and is announced and survived - and a "
"site running at part strength on a roster somebody wrote down wrong "
"reads as healthy on every dashboard",
_nw_target == 0.0 and "failsafe" in _nw_reason)
check("...and it says WHY, naming the inverter it has no setpoint entity for",
any("no setpoint entity for inverter-c" in e for e in _nw_events))
check("...and then it WRITES that 0 W to the unit it CAN reach, on the same "
"line as every other cycle. A substitution, not an abstention: the "
"inverter holds its last command forever, so failing toward inaction "
"means commanding zero, not falling silent",
_nw_writes == [("number.sp", 0.0)])
check("...and the 0 W is NOT what the site target happened to be - the same "
"claims at a roster whose units all have writers resolve to a real "
"number, which is what says the branch does work rather than agreeing "
"with the resolution by luck",
resolve(_cl_nw, units=("inverter-a",)).allocated is True
and resolve(_cl_nw, units=("inverter-a",)).target_w != 0.0)
# --- 10h-2. A DEAD LINK, AND THE SURVIVOR NOT ABSORBING IT SILENTLY ---------
# ⚠️ STIMULATED THROUGH main.py's OWN SEAM, NOT THROUGH A PATCHED ARBITER.
# `Controller.live_units()` is the production method the allocator's `live`
# argument comes from.
#
# ⚠️ AND SINCE DEV-02 IT IS DRIVEN BY THE REAL STIMULUS RATHER THAN OVERRIDDEN.
# This used to replace the method with a lambda, because at a roster of one
# "its master is stale" had no expression separate from "this controller is
# blind". `Inverter.is_live()` gives it one: a link whose every write has been
# REJECTED for a whole `LINK_STALE_S` window is not commandable, which is layer
# 1's own veto period - the point at which the firmware takes that inverter to
# zero anyway. So inverter B is put into exactly that state and the shipped
# method is asked, which is what makes this a check on `live_units()` instead of
# a check on a lambda this file wrote.
_bs, _restore_bs = second_inverter(c_src)
_bs.rejected_since = datetime.now(timezone.utc) - timedelta(
seconds=app_main.LINK_STALE_S + 5)
_bs.last_write_ok = False
_stale_writes_before = len(c_src.hass.per_entity)
try:
check("PRECONDITION: the SHIPPED `live_units()` - not a lambda - drops the "
"inverter whose writes have been rejected for a whole layer-1 window, "
"and keeps the healthy one",
c_src.live_units() == ("inverter-a",))
_, _cl_stale = cycle_claims(lambda: run_cycle(c_src))
_stale_target = c_src.target
_stale_alloc = c_src.allocation
_stale_events = list(c_src.events)
_stale_writes = c_src.hass.per_entity[_stale_writes_before:]
finally:
_restore_bs()
print(f" inverter-b's master stale: {_stale_alloc.explain()}")
print(" and logged: "
+ next((e for e in _stale_events if "ALLOCATOR" in e), "(nothing)"))
check("a unit whose master is stale is REMOVED FROM THE ENVELOPE SET rather "
"than allocated into. An allocator that kept commanding a link it cannot "
"reach is writing into a void and calling the site target met",
_stale_alloc.dropped == (("inverter-b", ALLOC_DROP_STALE),)
and "inverter-b" not in _stale_alloc.shares)
check("...and the SURVIVOR CARRIES THE WHOLE SITE TARGET, which is right - "
"there is one integrator on P1 and its output still has to be delivered - "
"and it is now DELIVERABLE, so main.py writes it instead of failsafing. "
"The two guards are distinguished by this line: a dead sibling is not the "
"same event as a sibling with no writer",
_stale_alloc.shares == {"inverter-a": _stale_alloc.sum_w}
and _stale_target == float(_stale_alloc.sum_w)
and ("number.sp", _stale_target) in _stale_writes)
check("⚠️ AND THE DROPPED UNIT IS COMMANDED 0 W, NOT LEFT STANDING. The "
"inverter holds its last command FOREVER - it has no meter timeout of its "
"own - so 'not in the split' has to mean zero on the wire. Leaving it "
"silent would leave a dead-link inverter pushing its last share while the "
"survivor carried the whole site target on top of it",
("number.sp_b", 0.0) in _stale_writes)
check("⚠️ AND IT DOES NOT ABSORB IT SILENTLY, which is the whole of AC 6 and of "
"SAFETY-30. The action log names the inverter, the reason it left, and "
"the consequence - that what remains now carries its share. A site "
"running at half its inverters and reporting nothing reads as a healthy "
"site to the operator and to every dashboard",
any("inverter-b" in e and "stale link" in e and "carry" in e
for e in _stale_events))
# --- 10h-3. EVERY MASTER STALE: THE ALLOCATOR'S OWN REFUSAL, REACHED --------
# Same stimulus, both units. ⚠️ AND IT REACHES A ROSTER OF ONE TOO: this is the
# state `live_units()`'s own docstring warns about - the sole inverter dropping
# takes the SITE to 0 W - so it is driven here rather than left as a sentence.
_bd, _restore_bd = second_inverter(c_src)
_gone = datetime.now(timezone.utc) - timedelta(
seconds=app_main.LINK_STALE_S + 5)
_bd.rejected_since, _bd.last_write_ok = _gone, False
c_src.inverters[0].rejected_since = _gone
c_src.inverters[0].last_write_ok = False
_dead_writes_before = len(c_src.hass.per_entity)
try:
_, _cl_dead = cycle_claims(lambda: run_cycle(c_src))
_dead_target, _dead_reason = c_src.target, c_src.reason
_dead_alloc = c_src.allocation
_dead_events = list(c_src.events)
_dead_writes = [v for _e, v in c_src.hass.per_entity[_dead_writes_before:]]
finally:
_restore_bd()
c_src.inverters[0].rejected_since = None
c_src.inverters[0].last_write_ok = True
print(f" every master stale: {_dead_alloc.explain()}")
print(" and logged: "
+ next((e for e in _dead_events if "ARBITER" in e), "(nothing)"))
check("⚠️ AND HERE `allocated=False` IS REACHED FOR REAL, ON A REAL CYCLE. "
"With no inverter in the envelope set there is nobody to allocate to, "
"and inventing a share for a link nobody can reach is the failure this "
"branch exists for. The refusal path ARB-03 left behind is therefore "
"still live code with a live trigger, which is what the ticket asked for "
"when it said re-aim rather than delete",
_dead_alloc.ok is False and _dead_alloc.shares == {}
and ALLOC_REFUSE_EMPTY in _dead_alloc.refused)
check("...and main.py substitutes the 0 W failsafe on it, writes that 0 W, and "
"puts the allocator's OWN sentence in the action log rather than a "
"paraphrase - so the operator reads which of the refusals fired",
_dead_target == 0.0 and "failsafe" in _dead_reason
and set(_dead_writes) == {0.0} and len(_dead_writes) == 2
and any("ARBITER: REFUSED" in e and ALLOC_REFUSE_EMPTY in e
for e in _dead_events))
check("...and the roster it was restored to is the shipped one, with a healthy "
"link, so nothing below inherits a two-inverter Controller or a dead one",
c_src.units == (app_main.UNIT_A,)
and c_src.live_units() == (app_main.UNIT_A,))
# ==============================================================================
print()
print("11. mutation: what defeats these guards, and which check bites")
+23 -11
View File
@@ -791,17 +791,29 @@ check("the committed replay fixtures are present - a regression fixture CI "
"cannot see is not a regression fixture", len(REPLAY) >= 2)
# ⚠️ `peak_cap_w:` appears TWICE in config.yaml - once under `options:` with the
# default, once under `schema:` with `int(500,15000)`. Taking the last match
# would blow up on the schema line, and taking any match that parses would be
# luck; the FIRST is the options block, which is the number an install lands on.
SHIPPED_CAP_W = None
for line in (HERE / "config.yaml").read_text(encoding="utf-8").splitlines():
if line.strip().startswith("peak_cap_w:"):
try:
SHIPPED_CAP_W = float(line.split(":", 1)[1].strip())
except ValueError:
continue
break
# default, once under `schema:` with `int(500,15000)`. This used to take the
# FIRST match on a STRIPPED line and call that the options block; CFG-04 made
# stripped-line-first-match unsafe in this file's neighbours (a `max_w:` nested
# six spaces under `inverters:` in the schema block began outranking the
# top-level one), so it is anchored the same way they now are: the options half
# of the file, at exactly two spaces of indentation. `peak_cap_w` is not a
# per-inverter key today and this reader was never wrong - it is the IDIOM that
# was, and leaving one copy of it here would be leaving the next per-inverter
# key a place to land. test_inverter.py part 12 runs this function against a
# two-inverter config.
def shipped_option(key):
"""The `options:` default for `key`, anchored at two spaces. None if absent."""
body = (HERE / "config.yaml").read_text(encoding="utf-8")
for line in body[:body.index("\nschema:")].splitlines():
if line.startswith(f" {key}:") and not line[2:3].isspace():
try:
return float(line.split(":", 1)[1].strip())
except ValueError:
return None
return None
SHIPPED_CAP_W = shipped_option("peak_cap_w")
check("config.yaml's shipped peak_cap_w was read out of the file rather than "
"typed here", SHIPPED_CAP_W is not None)
+199 -5
View File
@@ -19,8 +19,8 @@ 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,
ACTUATOR_WRITE_KEYS, FIRMWARE_INGEST_VETO_S, ConfigRefused,
actuator_writers, refuse, validate_startup_config,
)
fails = []
@@ -135,9 +135,128 @@ for blank in ("", " ", None):
check("...and the message says why it is dangerous rather than untidy",
why(validate_startup_config(base(setpoint_entity=""), None, None),
"heartbeat"))
# specs §1.5: two writers on one actuator is not expressible in this schema.
check("there is exactly one way to reach the actuator",
ACTUATOR_WRITE_KEYS == ("setpoint_entity",))
# --------------------------------------------------------------------------- #
# specs §1.5: TWO WRITERS ON ONE ACTUATOR, AND WHAT ACTUALLY GRADES IT
# --------------------------------------------------------------------------- #
# ⚠️ WHAT USED TO BE HERE, AND WHY IT WAS NOT ENOUGH. This was one line:
#
# check("there is exactly one way to reach the actuator",
# ACTUATOR_WRITE_KEYS == ("setpoint_entity",))
#
# and validate.py's comment said the §1.5 non-goal was ENFORCED by construction -
# exactly one such key, so a second writer is not expressible in the options
# schema at all. Both were true. Both graded THE SHAPE OF THE OPTIONS SCHEMA
# rather than the writes, and the difference is not academic: the config below
# has TWO WRITERS ON ONE ACTUATOR and leaves that tuple's length at 1. The check
# stays green while the property it protects is gone, which is this repository's
# named failure mode - a check that observes something other than what it claims
# to observe.
#
# So the first thing this section does is DEMONSTRATE the old check passing on
# the hazardous config, rather than assert in prose that it would have.
_PER_INVERTER_HAZARD = base(inverters=[
{"id": "inverter-a", "setpoint_entity": "number.goodwe_setpoint"},
# ⚠️ INVERTER B DOES NOT EXIST. Nothing is measured from it here; it is a
# config fixture, and the only thing that matters about it is that its
# `setpoint_entity` NAMES THE SAME ENTITY as the scalar key above - which is
# the shape of the mistake, and the shape CFG-04 makes reachable.
{"id": "inverter-b", "setpoint_entity": "number.goodwe_setpoint"}])
check("⚠️ THE DEFECT, DEMONSTRATED: on a per-inverter config with two writers "
"aimed at ONE entity, the old proxy is still green - it counts option "
"KEYS, and there is still exactly one key called setpoint_entity. This "
"is the check that could not see the thing it was named after",
len(ACTUATOR_WRITE_KEYS) == 1)
_census = actuator_writers(_PER_INVERTER_HAZARD)
print(f" the same config, censused by writer: "
f"{ {k: len(v) for k, v in _census.items()} }")
check("...and the replacement SEES it, because it counts writers per ACTUATOR "
"rather than keys: three declarations, one entity",
list(_census) == ["number.goodwe_setpoint"]
and len(_census["number.goodwe_setpoint"]) == 3)
_hazard_problems = validate_startup_config(_PER_INVERTER_HAZARD, -5000, 5000)
check("AC 3: and the config is REFUSED, where today it starts",
why(_hazard_problems, "one actuator"))
check("...and the refusal names the actuator and every writer aimed at it, so "
"an operator can see WHICH declarations to remove rather than being told "
"only that something is wrong",
why(_hazard_problems, "number.goodwe_setpoint")
and why(_hazard_problems, "inverters[0].setpoint_entity")
and why(_hazard_problems, "inverters[1].setpoint_entity"))
# ⚠️ AND THE GATE MUST NOT REFUSE THE CONFIG CFG-04 IS ACTUALLY FOR. A validator
# that fires on the legitimate case gets switched off by the first person it
# inconveniences, and then none of this is enforced. Two inverters with two
# entities are two writers on TWO actuators, which is not the non-goal - it is
# the whole point of the per-inverter roster.
#
# ⚠️ THE ENTRIES BELOW GAINED `name` AND `max_w` WHEN CFG-04 LANDED, AND THE
# HAZARD FIXTURE ABOVE DELIBERATELY DID NOT. SAFETY-28 wrote both against a
# shape that did not exist yet and guessed `id`; CFG-04 chose `name`, and made
# `name`/`setpoint_entity`/`max_w` required of every entry (rule 9). The hazard
# fixture is left in the OLD guessed shape on purpose - the claim it makes is
# that `actuator_writers()` finds writers STRUCTURALLY, under a container and a
# key spelling this file was never told, and rewriting it into today's shape
# would quietly turn it into a check that the census knows about `inverters`.
# This one is the opposite claim - that a real, valid, two-inverter config is
# ACCEPTED - so it has to be a config the shipped validator actually accepts.
_PER_INVERTER_OK = {k: v for k, v in base().items() if k != "setpoint_entity"}
_PER_INVERTER_OK["inverters"] = [
{"name": "inverter-a", "setpoint_entity": "number.goodwe_setpoint",
"max_w": 2000},
# ⚠️ INVERTER B DOES NOT EXIST. 2000 W here is the SHIPPED default repeated,
# not a rating measured off a second device - SPIKE-04 measures that when
# there is one to measure. Nothing in this file depends on the number.
{"name": "inverter-b", "setpoint_entity": "number.goodwe_setpoint_b",
"max_w": 2000}]
check("two inverters with their own entities are ACCEPTED - one writer each, "
"no shared actuator, and that is CFG-04's whole purpose",
validate_startup_config(_PER_INVERTER_OK, -5000, 5000) == [])
check("...and today's single-inverter config is untouched: one writer, one "
"actuator, and the census finds it wherever it is declared",
validate_startup_config(base(), -5000, 5000) == []
and actuator_writers(base()) ==
{"number.goodwe_setpoint": ["setpoint_entity"]})
# The census is found STRUCTURALLY, not by looking for a container called
# `inverters` - CFG-04 has not chosen that name yet, and a census that guessed
# wrong would go green while two writers existed, which is the same defect one
# step along.
check("a writer nested under a container this file has never heard of is "
"still counted, because the walk is over the options TREE and not over a "
"list of blessed key names",
len(actuator_writers({"setpoint_entity": "number.x",
"whatever_cfg04_calls_it": {
"unit_b": {"setpoint_entity": "NUMBER.X"}}})
["number.x"]) == 2)
check("...and entity ids are folded to lower case, so a second writer cannot "
"be smuggled past the census on Number.X versus number.x",
why(validate_startup_config(base(inverters=[{"setpoint_entity":
"NUMBER.GOODWE_SETPOINT"}]),
-5000, 5000), "one actuator"))
# ⚠️ THIS CHECK CHANGED SHAPE IN CFG-04, AND THE REASON IS A DECISION RATHER
# THAN AN ADJUSTMENT. It used to assert that a blank per-inverter entity left
# the whole config ACCEPTED - "blank is how an operator leaves a slot
# unconfigured". CFG-04 decided that is not true of a ROSTER ENTRY: an entry
# with no `setpoint_entity` is a unit that `allocator.plan()` still gives a
# share of the site target to and that nothing can command, on a status page
# reporting a site at full strength. Rule 9 refuses it by name. The claim about
# the CENSUS is untouched and is now asserted directly on the census, where it
# always belonged - a blank contributes no writer, so it cannot manufacture a
# two-writer refusal out of two unconfigured slots.
check("a BLANK per-inverter entity is not a writer - the same rule the scalar "
"key gets, since write_setpoint() returns immediately on a blank entity",
actuator_writers(base(inverters=[{"setpoint_entity": " "},
{"setpoint_entity": ""}]))
== {"number.goodwe_setpoint": ["setpoint_entity"]})
check("...but the ENTRY is refused all the same, by rule 9 and not by the "
"census: a roster slot nothing can write still takes a share of the site "
"target every cycle and delivers none of it",
why(validate_startup_config(base(inverters=[{"name": "inverter-b",
"max_w": 2000,
"setpoint_entity": " "}]),
-5000, 5000), "has no setpoint_entity"))
# --------------------------------------------------------------------------- #
print("3. a meter that can never read")
@@ -234,6 +353,64 @@ check("...and it is refused with maintenance_enabled off, as shipped",
base(max_w=2000, maintenance_charge_w=2500,
maintenance_enabled=False), -5000, 5000), "THE CEILING WINS"))
# ⚠️ MAINT-05: AND AT TWO PACKS IT IS THE WEAKEST CAP, NOT THE FIRST ENTRY'S.
# The comment this replaces in validate.py said, in as many words, that it took
# the FIRST unit's cap because there was exactly one `Maintenance` and it could
# only ever recalibrate `inverters[0]` - and that "when `maint_unit` stops being
# `inverters[0]`, this line moves with it". It has. Every pack is now
# recalibrated on its own schedule, so the shaping claim can be filed on any of
# them and the cap that contradicts it first is the smallest.
#
# ⚠️ THE FIXTURE'S TWO CAPS ARE DELIBERATELY DIFFERENT AND THE RATE SITS
# BETWEEN THEM. Two equal caps could not tell "grades the first" from "grades
# the smallest", and a rate above both would be refused by either rule - so
# 3000 W against caps of 5000 W and 2000 W is the one arrangement where the old
# answer and the new one disagree. ⚠️ 2000 W for the second pack is a
# HYPOTHESIS: inverter B does not physically exist and nothing here is measured
# from one.
def _roster(a_max, b_max, **over):
o = base(**over)
for k in ("setpoint_entity", "soc_entity", "batt_entity", "max_w"):
o.pop(k, None)
o["inverters"] = [
dict(name="inverter-a", setpoint_entity="number.sp_a",
soc_entity="sensor.soc_a", batt_entity="sensor.batt_a",
max_w=a_max),
dict(name="inverter-b", setpoint_entity="number.sp_b",
soc_entity="sensor.soc_b", batt_entity="sensor.batt_b",
max_w=b_max)]
return o
_two = _roster(5000, 2000, maintenance_charge_w=3000, maintenance_discharge_w=1000,
sign_disagree_w=300, unit_sign_disagree_w=300)
_p_two = [p for p in validate_startup_config(_two, -5000, 5000)
if "maintenance_charge_w" in p]
print(f" 5000 W and 2000 W packs, charge 3000 W -> {_p_two}")
check("⚠️ A CHARGE RATE THE SMALLEST PACK CANNOT TAKE IS REFUSED, even though "
"the FIRST pack could. Before MAINT-05 the second pack was never "
"recalibrated, so its cap could not contradict anything; it is now, and "
"its cheap-window charge would ask for hi=-3000 against lo=-2000 - the "
"`lo > hi` contradiction, 0 W, on the pack nobody was watching",
len(_p_two) == 1 and why(_p_two, "max_w (inverter-b) is 2000 W"))
check("...and the message names the pack the number came off, not the first "
"entry - an operator told to lower a number on the wrong device is being "
"sent to the wrong device by the message that exists to stop that",
not why(_p_two, "max_w (inverter-a)"))
check("...while the same rate against two packs that can both take it starts, "
"so this is a comparison and not a blanket refusal of rosters",
[p for p in validate_startup_config(
_roster(5000, 4000, maintenance_charge_w=3000,
maintenance_discharge_w=1000, sign_disagree_w=300,
unit_sign_disagree_w=300), -5000, 5000)
if "maintenance_charge_w" in p] == [])
check("...and at a ROSTER OF ONE `min()` over one cap is that cap: the same "
"message, the same boundary, the same refusal the flat config always got",
why(validate_startup_config(base(max_w=2000, maintenance_charge_w=2500),
-5000, 5000), "THE CEILING WINS")
and validate_startup_config(base(max_w=2000, maintenance_charge_w=2000),
-5000, 5000) == [])
# ⚠️ THE SIBLING, CHECKED RATHER THAN ASSUMED. The shaping is NOT symmetric:
# drain files Claim.set at P_MAINTENANCE and owns the actuator, so the ceiling
# CLAMPS it (+2000 W) instead of contradicting it, and the arbiter's explain()
@@ -404,9 +581,26 @@ check("...and the message explains it would read as a trip, not a mistake",
# check below.
check("the smallest sane max_w still starts",
validate_startup_config(base(max_w=1, sign_disagree_w=0.5,
unit_sign_disagree_w=0.5,
maintenance_charge_w=1), -5000, 5000) == [])
check("...but that same 1 W ceiling with the DEFAULT sign threshold is refused",
why(validate_startup_config(base(max_w=1), -5000, 5000), "never fire"))
# ⚠️ SAFETY-30 ADDED A SECOND WAY TO DISARM A SIGN WATCHDOG BY CONFIGURATION,
# and the fixture above now has to name BOTH thresholds - which is the check
# doing its job rather than a bookkeeping edit. `unit_sign_disagree_w` bounds a
# unit's own SHARE, which the same `supervised` claim holds at +-max_w, so at or
# above the ceiling it is unsatisfiable by construction exactly as
# `sign_disagree_w` is. Refused even at the shipped roster of one, where this
# watchdog is not armed: a config that cannot work is refused when it is
# written, not on the day somebody adds a second inverter.
check("...and the per-inverter threshold has the same rule, named separately "
"so an operator is told WHICH watchdog they disarmed",
why(validate_startup_config(base(max_w=1, sign_disagree_w=0.5,
maintenance_charge_w=1), -5000, 5000),
"unit_sign_disagree_w"))
check("...and one watt under that ceiling is reachable, so accepted",
validate_startup_config(base(max_w=2000, unit_sign_disagree_w=1999),
-5000, 5000) == [])
# --------------------------------------------------------------------------- #
print("what must NOT be refused - a validator that fires on trivia gets deleted")
File diff suppressed because it is too large Load Diff
+292
View File
@@ -0,0 +1,292 @@
#!/usr/bin/env python3
"""ALLOC-01's acceptance evidence, on admin/goodwe's OWN two-master rig.
python3 tools/alloc_sim.py --table # broadcast vs allocator, side by side
python3 tools/alloc_sim.py --splits # AC 2: split-invariance at the meter
python3 tools/alloc_sim.py --sweep # AC 3: gain to 1.0 at every split
python3 tools/alloc_sim.py --all
# DEV-02: the split-invariance finding ALLOC-01's review handed on, and the
# sensing change that closed it. The two rows are the evidence.
python3 tools/alloc_sim.py --splits --gain 0.4 --feedback unit # 250 W apart
python3 tools/alloc_sim.py --splits --gain 0.4 --feedback site # identical
WHY THIS IS A SCRIPT AND NOT A `test_*.py`
==========================================
It needs admin/goodwe checked out beside this repository, and the add-on's CI
job has no credentials for that repository - it is private and the job's token
is minted for this one. A `test_*.py` here is globbed and RUN by
.gitea/workflows/checks.yml, so a file that needs the sibling repo would either
fail the gate or - worse, and this is what test_freeze.py does today - pass
SILENTLY having checked nothing. So the rig evidence lives here, is quoted in
the pull request, and test_alloc.py grades the same properties in CI against a
plant it models itself and says it models.
WHAT IS REAL IN HERE
====================
Everything except the allocator's inputs. `sitesim.run_site()` is used
UNMODIFIED: the add-on's own `compute()` closes the loop, the firmware's own
encoder puts each command on each unit's wire, `plantsim.Plant` is the battery
model, and `watchdog.SignWatchdog` is the shipped detector. The ONLY thing this
file changes is `sitesim.allocate`, which it wraps so that a new mode name
routes to `app.arbiter.allocate()` - the shipped allocator, imported, never
transcribed - and delegates every other mode to the original. That wrapper is
the whole diff between the RED run and the GREEN run, which is what makes the
comparison worth anything.
⚠️ NOTHING IN admin/goodwe IS MODIFIED. `sim/` triggers a workflow that takes
the physical rig's lock; this file reads that repository and writes nothing to
it.
⚠️ INVERTER B'S PARAMETERS ARE PLACEHOLDERS. `plantsim.INVERTER_B` carries
`measured=False` - it is A's numbers copied, because inverter B does not exist
yet (SPIKE-04 measures it). Every verdict below that involves B is a verdict
about the ARCHITECTURE, not about that inverter, and the runs say so.
"""
import argparse
import math
import os
import pathlib
import sys
HERE = pathlib.Path(__file__).resolve().parent
ADDON = HERE.parent.parent # the goodwe-addon checkout root
def find_sim():
"""admin/goodwe's `sim/` directory, or None - and the caller says which.
$GOODWE_SIM first, the same override test_freeze.py takes, then the sibling
checkouts that actually occur. A missing sibling is not a failure of the
allocator and must never be reported as one.
"""
cands = []
if os.environ.get("GOODWE_SIM"):
cands.append(pathlib.Path(os.environ["GOODWE_SIM"]))
for up in (ADDON.parent, ADDON.parent.parent):
cands += [up / "goodwe" / "sim", up / "goodwe-session" / "goodwe" / "sim"]
for c in cands:
if (c / "sitesim.py").exists():
return c
return None
def load(sim):
"""Import the rig, pointed at THIS checkout, and graft our allocator in."""
sys.path[:0] = [str(sim)]
# inject.py resolves the add-on repo, and refuses to guess between two
# checkouts. Naming it removes the guess: the tree under test is the tree
# this file ships in, whatever else is lying around the disk.
os.environ.setdefault("GOODWE_ADDON_REPO", str(ADDON))
import inject, sitesim # noqa: E402
arbiter = sitesim.load_addon("app.arbiter", "alloc_sim")
allocator = sitesim.load_addon("app.allocator", "alloc_sim")
original = sitesim.allocate
def patched(target_w, n, mode):
if not mode.startswith("alloc01"):
return original(target_w, n, mode)
# "alloc01" or "alloc01:90/10" - the weights, which AC 2 says must not
# change the aggregate trace at the meter.
names = [f"inverter-{c}" for c in "ab"[:n]]
parts = mode.split(":", 1)
if len(parts) == 2:
ws = [float(x) for x in parts[1].split("/")]
else:
ws = [1.0] * n
bounds = {u: arbiter.UnitBounds(lo=-r, hi=r)
for u, r in zip(names, patched.ratings)}
shares, ok = arbiter.allocate(
target_w, bounds, weights=dict(zip(names, ws)))
if not ok:
# A refusal on this rig would be a bug in the experiment, not a
# finding: nothing here is stale, mis-routed or pinned. Fail loud.
raise SystemExit(f"alloc_sim: the allocator REFUSED at {target_w} W "
"- no scenario below should reach a refusal")
return [float(shares[u]) for u in names]
# The envelope handed to the allocator each tick: the rating each MODELLED
# inverter actually carries, read off plantsim rather than typed here, so a
# change to INVERTER_A - or a --b-rating override - moves the envelope with
# it instead of leaving this file quietly wrong. ⚠️ INVERTER_B's IS A
# PLACEHOLDER; nothing here has measured it.
from plantsim import INVERTER_A, INVERTER_B
patched.ratings = [INVERTER_A["rating_w"], INVERTER_B["rating_w"]]
sitesim.allocate = patched
return inject, sitesim, arbiter, allocator
def run(sitesim, control, watchdog, mode, gain, **kw):
return sitesim.run_site(control, watchdog, n=2, gain=gain, mode=mode,
label=f"N=2 gain {gain} {mode}", **kw)
def run_site_feedback(sitesim, control, mode, gain, load_w=2000.0, cycles=40,
cycle_s=None, dt=0.05):
"""`sitesim.run_site()` WITH EXACTLY ONE LINE CHANGED, and it is named here.
⚠️ THIS IS A COPY AND IT IS A COPY ON PURPOSE. `run_site` lives in
admin/goodwe, which this file reads and never writes, and it feeds
`compute()` ONE inverter's power as `actual_w` because that is what the
add-on gave it: a single `batt_entity`, so an operator who wired up a second
inverter had a loop that saw unit A only. A rig that fed the sum would have
been KINDER than the deployment.
So this differs from `run_site` in one expression - `site.battery`, the
site's total inverter power, instead of `inverters[0].plant.actual` - and in
nothing else.
⚠️ AND SINCE DEV-02 THAT ONE EXPRESSION IS THE SHIPPED ONE, WHICH TURNS THIS
FUNCTION FROM A COUNTERFACTUAL INTO THE MODEL. `Controller.site_batt_w` is
the SUM of the per-instance battery readings and is what main.py hands
`compute()`; `--feedback site` is therefore the add-on as it now stands, and
`--feedback unit` is the PRE-DEV-02 sensing, kept because the comparison is
the evidence. Measured here, 2 kW load, 40 cycles: fed one unit's power the
aggregate trace at the meter is split-dependent by 510 W at gain 0.2, 250 W
at 0.4 and 50 W at 0.6; fed the site total every split is bit-identical at
every gain. `run_site` still models the old sensing and must not be
"corrected" to the new one - the row it produces is what the fix is measured
against.
"""
from plantsim import INVERTER_A, INVERTER_B, Inverter, Site
cycle_s = sitesim.CYCLE_S if cycle_s is None else cycle_s
specs = [("A", INVERTER_A), ("B", INVERTER_B)]
inverters = [Inverter.from_spec(n, dict(sp, **sitesim.INSTANT))
for n, sp in specs]
site = Site(inverters, load=load_w)
loop = sitesim.Loop(control, gain)
samples = []
for c in range(cycles):
grid = site.grid
d = loop.cycle(grid, site.battery) # <- THE ONE CHANGED LINE
for inv, share in zip(inverters,
sitesim.allocate(d.target_w, len(inverters), mode)):
inv.command(share)
site.settle(cycle_s, dt=dt)
samples.append(dict(cycle=c, grid_before=grid, target=d.target_w,
grid=site.grid, batt=site.battery, reason=d.reason,
sat=d.sat_count, frozen=d.frozen, clamped=d.clamped,
i_clamped=d.i_clamped,
shares=[inv.plant.cmd for inv in inverters]))
return sitesim.Run(f"site-feedback gain {gain} {mode}", samples, inverters,
mode, gain, None)
SPLITS = ["alloc01:50/50", "alloc01:90/10", "alloc01:10/90",
"alloc01:99/1", "alloc01:1/0"]
def table(sitesim, control, watchdog, cycles, load_w):
print("=== AC 3 / the ARCH-01 experiment: broadcast vs allocation ===")
print(f"{'run':28} {'tail p2p':>10} {'worst export':>13} commands")
rows = []
for gain in (0.6, 1.0):
for mode in ["broadcast", "even_split"] + SPLITS:
r = run(sitesim, control, watchdog, mode, gain,
load_w=load_w, cycles=cycles)
rows.append((gain, mode, r))
print(f"gain {gain} {mode:20} {r.p2p():10.0f} "
f"{r.worst_export(1):13.0f} "
f"{[int(x) for x in r.targets(4)]}")
return rows
def splits(sitesim, control, watchdog, cycles, load_w, gain=1.0,
feedback="unit"):
"""AC 2. A 90/10 and a 50/50 split, and the AGGREGATE trace at the meter."""
print(f"=== AC 2 / split-invariance at gain {gain}, loop feedback "
f"= {feedback} ===")
base = None
ok = True
for mode in SPLITS:
r = (run(sitesim, control, watchdog, mode, gain,
load_w=load_w, cycles=cycles) if feedback == "unit"
else run_site_feedback(sitesim, control, mode, gain,
load_w=load_w, cycles=cycles))
trace = [round(g, 6) for g in r.grids()]
cmds = [round(t, 6) for t in r.targets()]
if base is None:
base, base_mode = trace, mode
print(f" {mode:16} reference: grid {[int(g) for g in trace[:6]]} ...")
else:
same = trace == base
ok &= same
print(f" {mode:16} {'IDENTICAL' if same else 'DIFFERS'} to "
f"{base_mode} worst |delta| "
f"{max(abs(a - b) for a, b in zip(trace, base)):.6f} W")
# And the shares are NOT the same - otherwise the invariance is vacuous.
s = r.samples[-1]["shares"]
print(f" last shares {[int(x) for x in s]}, "
f"sum {sum(s):.0f} vs site command {cmds[-1]:.0f}")
print(f" -> split-invariance {'HOLDS' if ok else 'FAILS'}")
return ok
def sweep(sitesim, control, watchdog, cycles, load_w):
"""AC 3. Gain swept to config.yaml's documented maximum, at every split."""
print("=== AC 3 / gain sweep to 1.0 at every split ===")
gains = [0.05, 0.2, 0.4, 0.6, 0.8, 0.9, 1.0]
print(f"{'mode':20}" + "".join(f"{g:>9}" for g in gains))
worst = {}
for mode in ["broadcast"] + SPLITS:
line = f"{mode:20}"
for g in gains:
r = run(sitesim, control, watchdog, mode, g,
load_w=load_w, cycles=cycles)
p = r.p2p()
worst[mode] = max(worst.get(mode, 0.0), p)
line += f"{p:9.0f}"
print(line + f" worst {worst[mode]:.0f} W p2p")
print(" (tail peak-to-peak grid swing, W. A limit cycle is a tail that "
"does not go to zero.)")
return worst
def main():
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("--table", action="store_true")
ap.add_argument("--splits", action="store_true")
ap.add_argument("--sweep", action="store_true")
ap.add_argument("--all", action="store_true")
ap.add_argument("--cycles", type=int, default=40)
ap.add_argument("--load", type=float, default=2000.0)
ap.add_argument("--gain", type=float, default=1.0)
ap.add_argument("--feedback", choices=("unit", "site"),
default="site",
help="what the loop is fed as actual_w: the site total "
"(the shipped add-on since DEV-02, the default here) "
"or one inverter's power (the PRE-DEV-02 sensing, "
"kept because the comparison is the evidence)")
a = ap.parse_args()
if not (a.table or a.splits or a.sweep):
a.all = True
sim = find_sim()
if sim is None:
print("alloc_sim: admin/goodwe is not checked out beside this "
"repository, so the two-master rig is unavailable. NOTHING has "
"been measured. Set $GOODWE_SIM to its sim/ directory.")
return 2
print(f"rig: {sim}")
inject, sitesim, arbiter, allocator = load(sim)
control = sitesim.load_addon("app.control", "alloc_sim")
watchdog = sitesim.load_addon("app.watchdog", "alloc_sim")
print(f"add-on under test: {os.environ['GOODWE_ADDON_REPO']}")
print("⚠️ inverter B's rating/ramp/lag are PLACEHOLDERS (plantsim."
"INVERTER_B, measured=False) - SPIKE-04 measures them\n")
if a.table or a.all:
table(sitesim, control, watchdog, a.cycles, a.load)
print()
if a.splits or a.all:
splits(sitesim, control, watchdog, a.cycles, a.load, a.gain,
a.feedback)
print()
if a.sweep or a.all:
sweep(sitesim, control, watchdog, a.cycles, a.load)
return 0
if __name__ == "__main__":
sys.exit(main())
@@ -0,0 +1,210 @@
"""CFG-04: does Supervisor accept a list-of-objects option? MEASURED, not assumed.
⚠️ WHY THIS SCRIPT EXISTS AND WHY IT IS COMMITTED. config.yaml had no
list-of-objects option anywhere before CFG-04, and `static_profile` carries a
structured value as a JSON STRING in a `str?` precisely because nobody knew
whether the Supervisor's options validator supported a nested one. That is a
question about a specific version of a specific piece of somebody else's
software, and the honest way to answer it is to run that software.
WHAT IT RUNS. Supervisor's OWN `AppOptions` validator and its OWN
`SCHEMA_APP_CONFIG`, out of the release image, against THIS repository's
config.yaml. Nothing here is a re-implementation of the validation rules; if
Supervisor changes them, this script changes its answer.
HOW TO RUN IT (the version is the one `ha info` reports on the target install -
2026.08.0 is what 192.168.2.158 ran when CFG-04 landed):
docker run --rm \
-v "$PWD:/w:ro" -v "$PWD/tools:/probe:ro" -v /tmp/out:/out \
--entrypoint python3 \
ghcr.io/home-assistant/amd64-hassio-supervisor:2026.08.0 \
/probe/supervisor_shape_probe.py
⚠️ IT TOUCHES NOTHING. It reads config.yaml and runs a validator in a throwaway
container. It does not talk to the live Supervisor, does not POST options and
does not install anything - the schema conflict in docs/deploy-rollback.md §4 is
exactly what you do NOT want to discover on a running site.
WHAT IT ANSWERED, 2026-09-04, on 2026.08.0 - the full output is in
DECISIONS/CFG-04-inverter-roster.md:
A. The manifest, list-of-objects schema and all, is ACCEPTED.
B. The shipped `options:` block validates as it stands, and the SAME block
with ONLY `inverters` removed is refused BY NAME - `Missing option
'inverters' in root`. That is the one measurement the `inverters: []`
default rests on, and it is an ISOLATED counterfactual: exactly one key
varies between the two runs, so the refusal cannot be about anything else.
B2. A reconstructed pre-0.6.0 options blob, merged with those defaults,
validates. Its RAW form is refused - but for whichever required key the
reconstruction happens to lack FIRST, which is an artefact of the
reconstruction and NOT evidence about `inverters`. B is that evidence.
C. A two-inverter blob validates, per-entry types enforced.
D. An entry missing `name`, `setpoint_entity` or `max_w` is refused BY NAME,
and a JSON string where the list belongs is refused outright.
"""
import sys, json, copy
sys.path.insert(0, "/usr/src/supervisor")
import voluptuous as vol
from voluptuous.humanize import humanize_error
from deepmerge import Merger
from supervisor.apps.validate import SCHEMA_APP_CONFIG
from supervisor.apps.options import AppOptions
from pathlib import Path
from supervisor.utils.yaml import read_yaml_file
MERGER = Merger(type_strategies=[(dict, ["merge"])],
fallback_strategies=["override"], type_conflict_strategies=["override"])
raw = read_yaml_file(Path("/w/config.yaml"))
print("== A. the whole config.yaml through SCHEMA_APP_CONFIG ==")
try:
cfg = SCHEMA_APP_CONFIG(raw)
print(" PASS Supervisor accepts the add-on manifest, version", cfg["version"])
except vol.Invalid as e:
print(" FAIL ", humanize_error(raw, e)); sys.exit(1)
schema, defaults = cfg["schema"], cfg["options"]
print(" schema declares", len(schema), "keys; inverters ->", json.dumps(schema["inverters"]))
# .get, not [], deliberately: if someone deletes the `inverters: []` default
# this line must not crash the probe before section B gets to REFUSE it.
print(" options ship inverters ->", json.dumps(defaults.get("inverters")))
def validate(options):
v = vol.Schema(vol.All(dict, AppOptions(None, schema, cfg["name"], "local_goodwe_controller")))
try:
return True, v(copy.deepcopy(options))
except vol.Invalid as e:
return False, str(e)
FAILED = []
def show(t, ok, d=""):
print(f" {'PASS' if ok else 'FAIL'} {t}")
if d: print(" " + str(d)[:300])
if not ok: FAILED.append(t)
# The live install's persisted options, reconstructed from HANDOVER.md §1 and
# docs/deploy-rollback.md §0/§B.5. No `inverters` key: it did not exist.
LIVE = {
"meter_entity": "sensor.p1_meter_active_power", "meter_invert": False,
"soc_entity": "sensor.goodwe_battery_soc", "batt_entity": "sensor.goodwe_battery_power",
"batt_invert": False,
"setpoint_entity": "number.kelder_goodwe_master_stage1_goodwe_setpoint_w",
"meter_source": "homewizard_local", "meter_phases": 1, "meter_max_age_s": 30,
"meter_poll_s": 5, "p1_host": "192.168.2.250",
"max_w": 5000, "gain": 0.6, "slew_w": 1000, "deadband_w": 15, "target_grid_w": -10,
"step_w": 10, "saturation_w": 500, "saturation_cycles": 3, "integrator_max_w": 0,
"heartbeat_s": 10, "stale_input_s": 15, "cycle_floor_s": 15, "auto_start": False,
"maintenance_enabled": False, "estop_fitted": True, "log_level": "info",
}
print("\n== B. THE LOAD-BEARING ONE: an options blob with no `inverters` key ==")
# ⚠️ THIS IS AN ISOLATED COUNTERFACTUAL AND IT HAS TO STAY ISOLATED. The claim
# the `inverters: []` default rests on is about ONE key, so exactly ONE key
# varies between these two runs: the full shipped `options:` block, and the same
# block with `inverters` removed and nothing else touched. Feeding the validator
# some other, INCOMPLETE blob would also produce a refusal - but about whichever
# required key that blob lacks first, which is a different measurement wearing
# this one's label. §B2 below is that other blob, and it is labelled as such.
ok, out = validate(dict(defaults))
show("the shipped `options:` block validates AS IT STANDS - so anything refused "
"on the next line is refused for the one key that was removed", ok,
"" if ok else out)
_no_inv = {k: v for k, v in defaults.items() if k != "inverters"}
ok_ni, out_ni = validate(_no_inv)
# ⚠️ THE ASSERTION IS ON THE KEY NAME, NOT ON `not ok`, AND THAT IS THE POINT.
# A refusal is only evidence for THIS key if it NAMES this key. Asserted as a
# bare `not ok`, this line would go on printing PASS after someone deleted
# `inverters: []` from config.yaml - blind to the exact regression it is the
# committed evidence for. Asserted on the string, it goes red: with the default
# gone the line above fails too, because then nothing distinguishes the two runs.
_names_it = (not ok_ni) and "Missing option 'inverters' in root" in str(out_ni)
show("...and the SAME block with ONLY `inverters` removed is REFUSED, BY NAME - "
"which is every options blob written before 0.6.0, since the key did not "
"exist when they were written", _names_it, out_ni)
print("\n== B2. AC3: a reconstructed pre-0.6.0 blob upgrades into this version ==")
# ⚠️ WHAT THIS SECTION IS AND IS NOT. LIVE is an INCOMPLETE reconstruction - it
# carries the keys HANDOVER.md and deploy-rollback.md record and no others, so
# it is missing many required keys that have nothing to do with this card. Its
# raw refusal is therefore about whichever of THOSE the validator reaches first
# (it has printed `meter_freeze_s` and `p1_phase_export_entities` on different
# runs), NOT about `inverters`. It is kept because the MERGED half is a real
# demonstration that `deepmerge(options:, stored)` is what App.options is; the
# raw half is printed only so the merge has something to be contrasted with.
# The `inverters` measurement is §B, where one key and only one key varies.
ok, out = validate(LIVE)
show("the reconstructed raw blob is REFUSED - for an unrelated missing key, "
"because the reconstruction is incomplete; see the refusal printed below "
"and §B for the `inverters` measurement", not ok, out)
merged = MERGER.merge(copy.deepcopy(defaults), copy.deepcopy(LIVE))
ok, out = validate(merged)
show("the same blob MERGED with these defaults - what App.options actually is", ok,
f"inverters={out.get('inverters')!r} setpoint_entity={out.get('setpoint_entity')!r} "
f"max_w={out.get('max_w')!r}" if ok else out)
print("\n== C. AC2: a two-inverter blob an operator would POST ==")
TWO = dict(LIVE, setpoint_entity="", inverters=[
{"name": "inverter-a", "setpoint_entity": "number.goodwe_a_setpoint_w",
"soc_entity": "sensor.goodwe_a_soc", "batt_entity": "sensor.goodwe_a_battery_power",
"max_w": 5000},
{"name": "inverter-b", "setpoint_entity": "number.goodwe_b_setpoint_w",
"soc_entity": "sensor.goodwe_b_soc", "batt_entity": "sensor.goodwe_b_battery_power",
"max_w": 3000}])
ok, out = validate(MERGER.merge(copy.deepcopy(defaults), copy.deepcopy(TWO)))
show("two inverters", ok, json.dumps(out.get("inverters")) if ok else out)
# The validated blob, for anyone who wants to POST it. Optional: the probe's
# whole job is the verdicts above, and a missing /out must not fail it.
try:
json.dump(out if ok else {}, open("/out/two_inverter_options.json", "w"), indent=1)
except OSError:
pass
print("\n== D. what the schema itself refuses, per entry ==")
for title, entry in (
("no name", {"setpoint_entity": "number.b", "max_w": 3000}),
("no setpoint_entity", {"name": "inverter-b", "max_w": 3000}),
("no max_w", {"name": "inverter-b", "setpoint_entity": "number.b"}),
("max_w over the range", {"name": "inverter-b", "setpoint_entity": "number.b", "max_w": 9999})):
ok, out = validate(dict(TWO, inverters=[entry]))
show(f"an entry with {title} is refused", not ok, out)
ok, out = validate(dict(TWO, inverters="[]"))
show("a JSON STRING where the list belongs is refused", not ok, out)
print("\n== E. the ROLLBACK direction, and the operator's UI ==")
# The old (flat) schema, i.e. what an operator would be running after a
# downgrade, meeting options that carry an `inverters` list.
_flat_schema = {k: v for k, v in schema.items() if k != "inverters"}
_v = vol.Schema(vol.All(dict, AppOptions(None, _flat_schema, cfg["name"],
"local_goodwe_controller")))
try:
_rolled = _v(MERGER.merge(copy.deepcopy(defaults), copy.deepcopy(TWO)))
show("a schema WITHOUT `inverters` drops the key with a warning rather "
"than refusing - so a downgrade is not the §B trap in reverse",
"inverters" not in _rolled, sorted(_rolled)[:6])
except vol.Invalid as e:
show("a schema WITHOUT `inverters` drops the key", False, str(e))
from supervisor.apps.options import UiOptions # noqa: E402
try:
_ui = [e for e in UiOptions(None)(schema) if e.get("name") == "inverters"]
show("Supervisor's UI renderer turns it into a repeatable section rather "
"than choking - an operator can add the second inverter in the "
"Configuration tab, which the JSON-string alternative could not offer",
bool(_ui) and _ui[0].get("multiple") is True, json.dumps(_ui))
except Exception as e: # noqa: BLE001
show("Supervisor's UI renderer survives the shape", False, f"{type(e).__name__}: {e}")
# ⚠️ THE EXIT CODE IS PART OF THE INSTRUMENT. Without it the probe prints FAIL
# and still succeeds, and a transcript is only evidence if a wrong answer is
# distinguishable from a right one by something other than reading it.
print()
if FAILED:
print(f"== {len(FAILED)} CASE(S) FAILED ==")
for t in FAILED:
print(" - " + t)
sys.exit(1)
print("== all cases passed ==")