Files
goodwe-addon/goodwe_controller/MUTATION.md
T
glenn schrooyenandClaude Opus 5 acbdf41248
checks / unit (pull_request) Successful in 3m55s
TEST-13: grade record_block()'s policy argument, and the two import spellings SAFETY-20's check could not see
Two survivors from TARIFF-01's review, closed in test_tariff.py only. app/ is
untouched and no shipped behaviour changes. Two further items on the card were
already closed in shipped code and are struck rather than re-implemented.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-01 08:40:09 +02:00

13 KiB

Mutation runs in this repository — and the one way they lie

Nearly every safety claim in this add-on was established the same way: change the shipped module, run the suites, watch one go red, put the module back, watch it go green. There is no coverage tool here and there is not meant to be — the check that matters is whether a check notices when the behaviour it names is removed.

That method has exactly one silent failure mode, and TEST-15 exists because we walked into it.

The defect

FCST-03's developer reverted self.provisional to here.provisional, re-ran, and reported the mutation as a survivor. It was not. CPython decides a cached .pyc is still valid from two numbers:

  • the source file's size in bytes, and
  • the source file's mtime truncated to whole seconds.

self and here are the same length, and the revert happened in the same second as the edit. Neither number moved, so the interpreter loaded the bytecode it already had. Confirmed at the time by disassembly: the source read here, the running code loaded self. The suite had graded code that was not there — no error, no warning, exit status 0.

The same collision, in the other direction, can leave a red standing on correct source after a revert that never took.

Which way it lies, and why that scopes everything

A mutation that never took effect leaves the suite green, and a green run of a mutated tree is reported as a survivor. So stale bytecode manufactures survivors; it cannot manufacture a red. The false-red case exists but announces itself, because a developer chases a failure they cannot explain.

Two consequences, and both are used below:

  • a recorded "all red, no survivors" result is not at risk from this defect;
  • a recorded survivor — and a recorded zero, such as a coverage-audit count of 0 — is exactly what this defect produces.

test_control.py's coverage-audit table says the same thing in its own terms: the error is one-directional, so every figure there is a lower bound at worst.

The rule

Purge __pycache__ before every mutation run. Not afterwards, not usually, not when the edit looks big enough.

cd goodwe_controller
tools/mutation_run.sh                     # every test_*.py in this directory
tools/mutation_run.sh . test_tariff.py    # or just the ones you are watching
tools/mutation_run.sh "$GOODWE_ADDON_REPO/goodwe_controller"   # from elsewhere

The harness purges, prints a sha256/byte-count fingerprint of every app/*.py it is about to grade, runs each suite under python3 -B, and fails if a cache appeared during the run. Diff two fingerprints and the file you mutated is the line that changed — which is also how a mutation report proves which source produced it.

What does not fix this

writes bytecode reads a stale .pyc
python3 -B no yes
PYTHONDONTWRITEBYTECODE=1 no yes
purging __pycache__ (unchanged) no — nothing to read

Both flags are write-side only. A mutation run always has a cache already, because the previous run wrote it, so a harness that only adds -B closes nothing. This is measured, not read off documentation: test_bytecode.py part 2 arranges the collision and shows both flags still running the old code.

-B is still worth passing — it stops this run leaving a cache for the next edit to inherit, which is the one nobody is thinking about three mutations into a batch. Purge for this run, -B for the next one.

And not a sleep

One-second mtime resolution is the mechanism, not the enemy. Waiting out the clock would slow every run down, and would still only cover the edit somebody remembered to slow down. Stop trusting mtime instead.

Reporting a mutation

State the things a reviewer cannot reconstruct afterwards:

  1. the byte delta of the mutated file (+5 B, +0 B). +0 B is the risky one — say so;
  2. that the mutated line was on disk when the run started (the harness fingerprint, or a grep of the line);
  3. which suite went red, and on which named check — "the suite is red" and "the check that watches this is red" are different claims;
  4. for a survivor, that the run was purged. An unpurged survivor is not a result.

The other thing a mutation sweep cannot see: masking (TEST-16)

Stale bytecode is not the only way a survivor lies. Two guards can mask each other, and a sweep that mutates one line at a time is structurally blind to it.

TEST-16 is the worked example. static_tariff.arbitrage() refuses a one-firm-hour series at len(firm) < 2, and refuses a flat series at spread == 0.0. A single firm hour also has a spread of zero. So:

  • weaken the firm-pair rung alone → the flat rung refuses the stimulus anyway;
  • weaken the flat rung alone → the tiny-spread stimulus is still refused, just for the wrong reason;
  • and the suite, grading kind == "refused", reports nothing either way.

Both rungs could then be weakened together and still nothing would report — which is precisely the state in which the next edit to either one opens a real hole. It survived four rounds of review on TARIFF-03 and FCST-03.

Two rules come out of it, and both are cheap:

  1. Grade the reason, not just the verdict. "Refused" and "refused for the right reason" are different claims, and a masked rung is the case where the first is true and the second is false. A refusal sentence is what the operator reads; it is also the only observable that moves when one rung quietly absorbs another's work.
  2. When two rungs can answer the same stimulus, mutate them together. One extra run per suspected pair. If a sweep finds two survivors in the same function, that pair is the first thing to try — TEST-16's two survivors were adjacent lines in one function and neither was individually live.

Where each surface stands

  • Local and dev-harness runs — the exposed one. This is where FCST-03 hit it. goodwe_controller/__pycache__ and app/__pycache__ are gitignored and are sitting in most working trees right now. Use the harness.
  • CI — structurally immune, and it was before this card. .gitea/workflows/ checks.yml bind mounts the checkout -v "$WS:/w:ro", so the interpreter cannot write a __pycache__ into the tree under test at all; measured for TEST-15, and it fails silently — no error, exit status 0. Each job also rm -rfs its workspace and clones afresh, so nothing crosses between jobs on the shared runner. PYTHONDONTWRITEBYTECODE=1 is now set there too, as belt and braces: the :ro is one character wide and the next person debugging a write will be tempted by it.
  • The shipped add-on — not affected, and this is closed. goodwe_controller/Dockerfile has carried PYTHONDONTWRITEBYTECODE=1 since it was written. There is no deploy-side finding here; do not re-open it.
  • The infra repo's sim/ harnesses — exposed, and NOT fixed by this card. sim/replay_sign.py and friends import the add-on out of $GOODWE_ADDON_REPO and write __pycache__ into both trees (goodwe/sim/__pycache__ exists today). SAFETY-02's headline validation is a replay, not a suite, so a mutation graded through it carries the same exposure. tools/mutation_run.sh takes the tree to purge as its first argument precisely so that repo can call it, but the change belongs in that repo and some of those harnesses want the rig. Anyone mutating a module graded by a replay must purge both trees by hand until then.

Survey — mutation claims of 2026-08-25 … 2026-09-01

Scoped by the property, not by re-running everything. A claim is at risk only if a mutation could have preserved the file's byte count and been reverted inside the same second, and the claim is of the kind stale bytecode can fabricate (see "which way it lies"). Sources: git log release/1.0 and the commit and PR bodies.

claim verdict why
FCST-03 M9 self.provisional→here.provisional (dd40c56, 71cd784) re-verified this is the original false survivor. Re-run with the cache cleared, M9 is caught. The shipped source was correct throughout.
FCST-03 X1, X6 degenerate stimuli (71cd784) not at risk run after the purge discipline landed in that branch.
SAFETY-24 11 author + 9 reviewer mutations (e709554, 4601682) not at risk the commit records them run under python -B with a purged __pycache__ and real byte deltas. Its one survivor is an equivalent mutant, argued structurally rather than by a green run.
SAFETY-26 tolerance sweep over arbitrage.py and static_tariff.py, 2 survivors (2b8b8cb) not at risk purge, printed +5 B delta, mutated line asserted present, tree re-read before each run. One survivor is explicitly recorded at +0 B — the risky delta — and was produced under the purge. Both survivors are now closed by TEST-16 (test_static_tariff.py section 9), which also found that the two of them masked each other — each was individually non-live only because the other rung caught its stimulus, an arrangement single-mutation testing cannot see. Its own ledger is 7 mutations, 4 of them at +0 B, all red.
OPT-04 mutations reported on PR #22 (bdd7f18) not at risk test_arbitrage.py's header records the exact command: purge, then python3 -B.
TEST-17 checks() dropping when (504e8da) not at risk a red claim, and dropping an argument changes the file length. Neither half of the collision is available.
SAFETY-07 wiring mutations B1/B2/B3 and test_peakguard.py parts 7 and 10 (2d570d8, e7c95bf) not at risk those mutations are executed in-process, monkeypatched onto the imported module. No source file is edited, so no .pyc is consulted.
every "all red, no survivors" claim in the window — TARIFF-02 (24/0), TARIFF-03 (11), MAINT-04 (10), SAFETY-18 (6+4), SAFETY-03 (6), TEL-04 (10), TEL-05 (6) not at risk direction. Stale bytecode turns a red into a green survivor, never the reverse. A red is evidence that something changed under the check.
TEST-06's deleted assertion, "no new notification while parked at 0 W" (c34b5a2) not at risk / superseded it was recorded as undecidable and then falsified — test_freeze.py records the one-line mutation that takes the file red 9 times. The stronger later claim is a red one.
TARIFF-01 reviewer survivor: record_block() ignoring its policy argument (0dbd485) re-verified — still a survivor re-run here through tools/mutation_run.sh against the 15 suites that were on the record, all green with billed_w(block, policy) mutated to billed_w(block, POLICY_NET). The recorded diagnosis holds: every block reaching the store is single-phase, where NET, SUM and MAX collapse. Now CLOSED by TEST-13 (test_tariff.py section 7), which round-trips section 7's own unbalanced (3000, 500, -200) W block THROUGH the store under each policy - three distinct banked figures, so a hardcoded policy takes at least two of them red. Third instance of "a stimulus evaluated where the quantity it grades is degenerate", after WITNESS-02's span normalisation and TARIFF-01's own DST window.
SAFETY-25 8 mutations against test_peakguard.py part 10, then 9 more after review, all red not at risk each run against a tree copied fresh with __pycache__ excluded and mounted :ro, so no .pyc existed to go stale - the same structural immunity recorded for CI above. Byte deltas recorded on the PR; none is +0 B. All are reds, which is the direction this defect cannot fabricate. ⚠️ The second round exists because the first round's mutations were all aimed at DISARMING the guard, and the claim part 10 actually made was about the guard being FIXED - the reviewer built the fix and the suite stayed green. Bytecode was never the issue there; an unaimed battery was.
SAFETY-03 reviewer survivor: abs() dropped from clamp_to_rating's limit (6aabb83) re-verified — still a survivor re-run the same way, all 15 green. Also as recorded: unreachable under the int(100, 5000) schema.
TARIFF-01's other three survivors, SAFETY-03's describe() survivor, TARIFF-02's M3/M5/M7, SAFETY-18's three still unverified recorded before the purge discipline, with no byte delta on the record, so a +0 B same-second revert cannot be excluded. All are survivors, which is the direction this defect fabricates. TARIFF-02's and SAFETY-18's were closed by later commits whose claims are reds, so what is unverified is the diagnosis, not the current state of the code.

Nothing here says a past result is wrong. The two survivors re-run above both stood. What changed is that they are now on the record as measured rather than assumed, and the rest are labelled honestly. The still-unverified rows are cheap to close — one harness run each — and the right moment is when somebody next touches that module, not in a re-run campaign nobody will read.