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
This commit is contained in:
2026-09-04 04:29:45 +02:00
co-authored by Claude Opus 5
parent b30797e1f9
commit 6b85acb0f1
13 changed files with 1856 additions and 119 deletions
+60 -17
View File
@@ -178,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):
@@ -210,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