SAFETY-39: slew_w is a ratio to the rail, and gain is the constant that is still wrong #56

Merged
admin merged 2 commits from SAFETY-39 into release/1.0 2026-09-06 10:41:05 +02:00
21 changed files with 1702 additions and 46 deletions
+33
View File
@@ -31,6 +31,39 @@ guessing a boundary; saying so is more useful than a guess.
## Unreleased
⚠️ **`slew_w` IS A RATIO TO THE RAIL NOW, AND ITS DEFAULT CHANGED FROM 1000 TO 0
([[SAFETY-39]]).** `0` does not mean "off" and does not mean "unset" - it means
**follow `max_w`**, exactly as `integrator_max_w: 0` already does, and resolves
to `max_w / 9`: 222 W at the shipped 2000 W cap, 556 W at the live install's
5000, 1067 W at a ~9600 W two-inverter site. The 9 is
`PLANT_SETTLE_S / LOOP_TICK_S` - an 18 s measured step response against a 2 s
meter tick - so the loop takes the plant's own settling time to cross its whole
output range at any rail.
**An install that has never set `slew_w` will therefore command smaller steps
than it did on 0.7.0, and will converge more slowly after a large disturbance.**
That is the point rather than a side effect: `slew_w: 1000` was derived against
a **1500 W** clamp in 2026-08 and the live install has run it against 5000 since,
which crosses the whole range in 10 s against an 18 s plant. Measured on the
owner's system 2026-09-05: a 3.4 kW export drove the setpoint 380 -> 5000 W in
five ticks, the battery to -5154 W past a 5000 VA rating, and the grid from
3.4 kW of **export** to 2.8 kW of **import**.
An explicit `slew_w` is still accepted and is never silently reduced. What is
new is that a value **faster than the rail allows** is now **REFUSED AT STARTUP**
(`validate.py` rule 10), graded against the ROSTER SUM - so `slew_w: 1000` with
`max_w: 5000` will not start. Set it to `0`, or to any value at or below
`max_w / 9`. Slower is always accepted, including the interim 400 the reference
install has run since 2026-09-05.
⚠️ **This does NOT fix the over-absorption, and the record says so at length.**
Re-deriving the slew removes the >= 900 W setpoint step; the loop still absorbs
~1 kW more than the site needs on a large export step, because that is a `gain`
term and `gain: 0.6` was measured and deliberately left alone. See
`DECISIONS/SAFETY-39-slew-against-the-rail.md` §6, and do not read this entry as
more than it says.
**`test_peakguard.py` answered two of its own checks with the wall clock
(CI-06).** The file sits on the required `checks / unit (pull_request)` context
and had a measured ~20 % flake rate. It cost a wrong merge diagnosis (parents
@@ -0,0 +1,438 @@
# SAFETY-39 — `slew_w` is a ratio to the rail, and `gain` is the constant that is still wrong
**Status:** decided and implemented on branch `SAFETY-39`.
**Card:** SAFETY-39 — *"`slew_w` was derived at a 1500 W clamp and runs at 5000,
so the loop outruns the plant"*.
**Nothing here reached the inverter.** The live install still runs the interim
`slew_w: 400` applied by hand on 2026-09-05 12:00, which this branch's new rule
accepts unchanged.
---
## 0. The three things a reader should take away
1. **The overshoot is reproduced in simulation, and one half of it is not
reproducible at all.** The setpoint stepping to the rail and the meter
crossing from export into import are both reproduced, on two independent
plant models. The **−5154 W battery figure is not reproducible in either**,
because both clamp the plant at its rating. An acceptance criterion written
on it would pass on the broken configuration too, so none is. §2.
2. **The deliverable is the relationship, not the number.** `slew_w: 0` now
means *follow the rail* and resolves to `SLEW_RAIL_FRAC * max_w`;
`validate.py` rule 10 refuses an explicit value faster than that against the
**site** rail. Verified by breaking it. §4, §5.
3. ⚠️ **`slew_w` does not own the over-absorption. `gain` does, and `gain` was
not changed.** Re-deriving the slew removes the ≥ 900 W step — the symptom
that escalated 2 → 1 → 13 → 43 per 30 min on the morning of the excursion —
and removes nothing else. Anyone reading this card as "the overshoot is
fixed" is reading more than was delivered. §6.
---
## 1. The defect, stated in the terms the code uses
`slew_w: 1000` was derived on 2026-08-22 against a **clamp of 1500 W**
(goodwe/`NOTES.md`, *"Simulated 2 kW load step (gain 0.6, clamp 1500)"*). Its
stated justification:
> `slew: 1000` is the default because it puts most of the correction in the first
> cycle **while still capping how far the loop can jump ahead of the inverter**.
At 1500 W that sentence is true, and the reason is the rail rather than the
number: 1000 W/cycle reaches the rail in two cycles, so the excursion is bounded
by 1500 W whatever the loop does.
The live install then went to `max_w: 5000` and the constant did not move.
`DRIVER-07` ("raise actuator power cap to full inverter rating") is still in To
Do; the cap was raised ahead of it and `slew_w` was never revisited. **Nothing
in the code is broken.** The rail moved and the derivation did not.
| | derived at | shipped default | live install |
|---|---|---|---|
| `max_w` | **1500** | 2000 | **5000** |
| `slew_w` | 1000 | 1000 | **1000** |
Measured on the owner's system, 2026-09-05 11:43–11:46:
```
11:43:55 grid -3385 W a real 3.4 kW export
11:43:56 SP 380 → 1380 → 2380 → 3380 → 4380 → 5000 +1000 per 2 s tick
11:44:47 batt -5154 W ABOVE the 5000 VA rating
11:45:55 grid +2831 W flipped to 2.8 kW IMPORT
SP 5000 → 2930 → 3840 → 3750 hunting
```
Large (≥ 900 W) setpoint steps per ~30 min that morning: `2 → 1 → 13 → 43`.
---
## 2. ⭐ Reproduced first — and what could not be
`tools/slew_sim.py --repro`, against admin/goodwe's `plantsim.Plant`, the real
`compute()`, and the firmware's own encoder on the wire. Gain 0.6, `max_w` 5000,
`slew_w` 1000, 2 s tick, one 3385 W export step at t = 10 s:
```
t grid in setpoint battery grid out reason
10 -3739 -280 290 -3675 slew-limited
12 -3675 -1280 57 -3442 slew-limited
14 -3442 -2280 -316 -3069 slew-limited
...
34 -1012 -5000 -2823 -562 i-clamped ← the rail
38 -167 -5000 -3541 156 saturated-freeze ← EXPORT → IMPORT
44 562 -4310 -4018 633 saturated-freeze
50 544 -3210 -3804 419 tracking
```
Reproduced: the setpoint stepping a full 1000 W per tick to the rail, the loop
absorbing ~640 W more than the site needed, and the meter crossing from **3.7 kW
of export to +633 W of import** — the loop manufacturing the error it then
chases. Over a family of 51 export steps (1.0–4.2 kW × 3 phases), **48 of 51**
runs contain a ≥ 900 W setpoint step.
### ⚠️ What is NOT reproducible, and why no criterion is written on it
`plantsim.Plant.limit()` clamps the plant at `p_max`. The modelled battery
**cannot exceed its rating by one watt, at any tuning, on any step, ever.**
Neither can `test_control.py`'s independent model. So:
* the **−5154 W excursion is not reproducible in simulation at all**, and this
is a property of the models rather than of the tuning;
* the card's AC *"battery power no longer exceeds `max_w` on a step of the size
observed"* is **unfalsifiable in simulation** — it passes identically on the
configuration that produced the excursion. It is the one acceptance criterion
this card had to **rewrite rather than meet**, per the board's own rule that a
third review round means the AC is wrong.
What replaced it, and what is graded in CI: **the ≥ 900 W step is gone from
every member of the family**, and **the meter excursion and the over-absorption
are measured and reported rather than claimed to be fixed.**
### The two models agree
`test_control.py`'s in-repo first-order lag and admin/goodwe's ramp-plus-lag
`plantsim.Plant` are independent, and they agree on every sign and rank:
| | in-repo model | `plantsim.Plant` |
|---|---|---|
| ≥ 900 W steps at `slew_w` 1000 | 48/51 | 48/51 |
| ≥ 900 W steps at the derived value | 0/51 | 0/51 |
| over-absorption, slew 1000 → 250 | 1005 → 1330 W | 958 → 1081 W |
| over-absorption, gain 0.6 → 0.2 | 1109 → 393 W | 987 → 435 W |
---
## 3. The derivation
The constraint, in words, and it is the 2026-08-22 sentence made checkable:
> **The loop must not traverse its full output range faster than the plant takes
> to settle.**
Three measured quantities, and each is named where it came from:
| | value | where it was measured |
|---|---|---|
| plant settling time | **18 s** | goodwe/`NOTES.md` §5.10, 2026-08-22 — a 1.78 kW kettle step driven from HA off a plug that meters its own draw. ~18 s up to the deadband, ~23 s down. **18 is taken because it is the shorter and therefore the looser bound**; this is a refusal boundary, and rules 5 and 6 refuse the impossible case only, never "close to the rail". |
| control tick | **2 s** | the live install, measured 2026-09-05 — the setpoint stepped +1000 W every 2 s. `run_control()` runs a cycle on a changed meter value or on `cycle_floor_s`, whichever comes first, so the tick is the *meter's* rate. |
| output range | `max_w` | `main.py` builds `Tuning(max_w=self.site_max_w)`, the **roster sum**. |
```
SLEW_RAIL_FRAC = LOOP_TICK_S / PLANT_SETTLE_S = 2 s / 18 s = 0.1111 (9 ticks)
slew_w ≤ SLEW_RAIL_FRAC × max_w
```
| rail | derived `slew_w` | ticks to cross | seconds to cross |
|---|---|---|---|
| 1500 (where the original was derived) | 167 W | 9 | 18 s |
| 2000 (shipped default) | 222 W | 9 | 18 s |
| **5000 (the live install)** | **556 W** | 9 | 18 s |
| 9600 (with inverter B — **datasheet, not measured**) | 1067 W | 9 | 18 s |
And the configuration that was measured failing: `slew_w` 1000 at `max_w` 5000
crosses the rail in **5.0 ticks = 10 s**, against a plant that takes 18 s.
### ⚠️ The tick is the weak term and it is not wrong in the safe direction
A **slower** meter makes this bound conservative — it refuses configurations that
would have been fine, which is visible immediately and costs one edit. A meter
**faster** than 2 s makes it loose by exactly that ratio and nothing in this
add-on would say so. `run_control()`'s `await asyncio.sleep(1)` bounds the tick
below at 1 s, so the worst case is a factor of two — but if a faster meter is
ever fitted, `LOOP_TICK_S` has to be **re-derived, not merely re-read**. Compare
`validate.FIRMWARE_INGEST_VETO_S`, which carries the same kind of copy and can
only ever be wrong the other way; that difference is why both numbers are
written out in `control.py` rather than their quotient.
### ⚠️ The rig cannot pick 556 out of the table, and is not asked to
`tools/slew_sim.py --slew`, worst case over 51 export steps:
```
slew_w 1000 ← 2026-09-05 live pair step 1000 W 48/51 ≥900 W over-absorbed 958 W
slew_w 800 step 800 W 0/51 ≥900 W over-absorbed 1107 W
slew_w 700 step 700 W 0/51 ≥900 W over-absorbed 1133 W
slew_w 600 step 600 W 0/51 ≥900 W over-absorbed 1058 W
slew_w 555 ← the derived value step 560 W 0/51 ≥900 W over-absorbed 987 W
slew_w 500 step 500 W 0/51 ≥900 W over-absorbed 1029 W
slew_w 400 ← the live interim step 400 W 0/51 ≥900 W over-absorbed 1150 W
slew_w 300 step 300 W 0/51 ≥900 W over-absorbed 1143 W
slew_w 250 step 250 W 0/51 ≥900 W over-absorbed 1081 W
```
The ≥ 900 W step disappears at 800 and stays gone. Below that the table is
**flat and slightly non-monotone**, and 800 is *better* than 556 on
over-absorption. So the rig does not choose the number — **the constraint
chooses it, and the rig says what the constraint does and does not buy.** That
is the same relationship the 2026-08-22 table had to its own three columns.
⚠️ **A single step is not evidence here.** The deadband, the 10 W quantisation
and the phase of the step against the tick move the result by hundreds of watts,
non-monotonically. The first cut of this derivation was a single step and ranked
gain 0.3 as *worse* than 0.6, which the family shows is backwards. Every number
above is a worst case over a family, which is how admin/goodwe grades the same
kind of quantity (`config.yaml`'s "1890 closed-loop runs", "924 runs").
---
## 4. What ships — the relationship, not the number
**`slew_w: 0` means FOLLOW THE RAIL.** `control.slew_limit_w()` resolves it to
`SLEW_RAIL_FRAC * max_w`. It is the shipped default and it is the only value
that cannot be left behind when the rail moves. This is the idiom
`integrator_max_w: 0` has carried in the same options block since it was added —
not a new concept, the same one, applied to the key that needed it.
An explicit number is still accepted **and is never silently reduced**: the live
install runs 400, and silently reducing an operator's stated bound is case (a)
in `validate.py`'s own docstring — the defect that whole module exists to
prevent.
**`validate.py` rule 10** refuses an explicit `slew_w` above
`SLEW_RAIL_FRAC × site rail`. Graded against **`sum(unit_caps(opts))`**, the
roster sum — the same number `Controller.site_max_w` builds — and *not* against
the flat `max_w` and *not* against the weakest unit. Rules 5, 6 and 8 take
`min()` because each grades one watchdog, one shaping claim, one pack. `slew_w`
is not a per-unit quantity at all: `compute()` emits the **site** target and the
allocator divides it afterwards.
⚠️ `config.yaml`'s note on `site_sign_disagree_w` says there is deliberately no
rule pairing a site quantity with `max_w`, "because … `validate_startup_config()`
is handed options rather than a roster". That objection is to grading a site
quantity against the **flat key**, and it is answered rather than ignored:
`unit_caps()` already reads the roster the add-on will build, so the roster sum
*is* available at startup, and `site_rail_w()` is that number.
---
## 5. ⭐ Verified by breaking it
`test_validate.py`, section 10 — the acceptance criterion written as a test:
```
restoring slew_w 1000 at max_w 5000 -> 1 problem(s)
slew_w is 1000 W against a site rail of 5000 W, so the loop crosses its
whole output range in 5.0 cycles - 10 s at the 2 s tick this site was
measured running - while the plant takes 18 s to settle …
```
and the four things the refusal has to say, each graded separately: which rail
it used, how long the crossing takes, which measurement it is graded against,
and what to do about it (including `0`, which cannot go stale). Plus:
* **equality starts** — at exactly the derived value the crossing takes exactly
the settling time, which is the constraint met, not violated (rule 6's case,
not rule 5's; getting it backwards would refuse the recommended value);
* **one watt of slack starts** — a boundary that is not meaningful to one watt
must not refuse on one watt;
* **the live interim `slew_w: 400` starts**, and so does the schema floor —
there is no such thing as too slow here, and refusing it would refuse the
mitigation that is holding;
* **`slew_w: 0` starts at every rating from 100 W to 15 kW.**
`test_control.py` grades the same boundary from the law's side, so the rule can
only ever refuse what the ratio says is too fast, and the two cannot drift apart.
---
## 5b. What the change found in this repository's own tests
Five files moved, and **none of them moved because a number was rounded
differently**. Each is worth reading as a finding.
**Two fixtures encoded the defect.** `test_inverter.py`'s `BASE_OPTS` paired
`slew_w: 1000` with `max_w: 5000` — the 2026-09-05 configuration exactly — and
`test_loop.py`'s `BASE` paired 1000 with 2000. Both were typed when those rails
were new; nothing in either file had noticed. Rule 10 refused them on its first
run, so those fixtures **would not start**. That is what a rule about a
*relationship* is for, and it is the clearest evidence the rule is not a
formality.
**Two reproductions depended on a default they never named.**
`test_alloc.py`'s `close_loop` and `test_freeze.py`'s "make both terms
reachable" case reached `slew_w: 1000` through `Tuning`'s default. ARCH-01's
4000 W broadcast limit cycle and SAFETY-18's proof-of-capability alarm would
both have gone quiet — reporting a measured finding as *absent* because a
default moved underneath them. Both now write the number beside the measurement
it belongs to.
**One harness had a latent off-by-one that only a ramping loop could expose.**
`test_watchdog.py` graded SAFETY-02's banner by pairing `c.grid` with
`last_write` sampled **after** `cycle()`, while the detector is evaluated
**inside** `cycle()` against the *standing* command from the previous one. At
`slew_w: 1000` the loop reached its rail in two cycles and consecutive commands
were identical, so the wrong pair and the right pair were the same numbers. At a
rail-following slew they differ by one step and the check went red. `_drive()`
now has a `pre` hook that reads the operands the detector will actually use, and
the check reads the **latching** cycle rather than the one before it. The
assertion is strictly stronger than it was.
**One tripwire had two assertions that were exact by coincidence.**
`test_peakguard.py` part 10c read `limited_discharging == limited` (49/49) and
`min_soc <= bms_soc_floor + 0.05`. At the slower slew the loop drains that pack
~82 Wh less over the same two hours and no longer touches the cut-out *inside
that window*: 48/49, low-water 10.57 % against a 10 % cut-out, 0 cycles at the
BMS limit instead of 190. **The finding is unchanged and is sharper on the
measure that carries it** — 162 cycles of granted discharge below the EMS floor,
up from 138. The two exact equalities were artefacts of one tuning, the old and
new numbers are tabulated in the file beside the checks, and the assertions now
grade the substance. ⚠️ *Loosening an assertion to get a branch green is the
first thing a reviewer should suspect here; the table is there so the suspicion
can be settled rather than argued.*
---
## 6. ⚠️ `gain: 0.6` — measured, and deliberately NOT changed
The card asks whether `gain` still holds at this clamp. **It does not, and here
is the measurement.**
`tools/slew_sim.py --gain`, `slew_w` at the derived 556 W, same 51-step family:
```
gain 0.6 ← shipped over-absorbed 987 W meter driven to +987 W
gain 0.5 over-absorbed 941 W
gain 0.4 over-absorbed 977 W
gain 0.3 over-absorbed 876 W
gain 0.2 over-absorbed 435 W
gain 0.1 over-absorbed 66 W
```
Against the slew column in §3, which is flat. The mechanism is visible in
`control.py` and is structural rather than empirical:
* **`slew_w` bounds the OUTPUT.**
* **The integrator accumulates `gain × error` per cycle** and is bounded only by
`integrator_max_w`. At gain 0.6 into a 3.4 kW error it moves **~2040 W per
tick** and reaches a 5000 W rail in **under three ticks, whatever `slew_w`
is**.
So the 2026-08-22 derivation's own sentence — *"the gain, not the slew, is the
limit by then"* — has become literally true, and `gain` is the term that owns
the over-absorption at this rail. It is written about a 1500 W rail, where
`gain × 1500 = 900 W` and the clamp caught it in two cycles; at 5000 there is
3.3× more room to wind before the clamp binds.
**Why nothing was changed:**
* `gain` is a live control-law constant on a running house. Two of them moving
in one release makes the next measurement uninterpretable — and the interim
`slew_w: 400` has been in service since 2026-09-05 12:00, so there is a clean
baseline to measure the next change against and it would be destroyed.
* A validator rule pairing `gain` with a rail would be **inventing a
relationship nobody has measured.** The bound would have to be
`gain × error_max ≤ SLEW_RAIL_FRAC × max_w`, and `error_max` is the
disturbance, which is not config and is not bounded.
* `integrator_max_w` is **not** the lever it looks like: it bounds the output as
well as the accumulator (`target = clamp(i_w, ±max_w)`), which is why setting
it to 2000 on the live system on 2026-09-05 capped the inverter to 2000 W of
its 5000 and was reverted the same day.
This is named in `validate.py`'s *"deliberately not refused"* list so that it is
a known open item rather than an omission, and it is asserted in
`test_control.py` so that nobody can quietly read this card as having fixed it.
**It wants its own ticket.**
---
## 7. N = 1 → N = 2: the rail is what moved
⚠️ **Inverter B does not exist on site** (SPIKE-04, ≈ 2026-09-12). Its figures
are from its **datasheet and serial**, not a measurement: GW5048D-ES, serial
`55048ESU22AW0992`, 4600 W, pack 4 × Dyness DL5.0C = 20.48 kWh, floor 10 %
(goodwe/`NOTES.md` §1.1b) — and the 4600 W is printed under *battery input data*,
so it may be DC, in which case the AC ceiling is nearer 4324 W.
⚠️ **And `sim/plantsim.py`'s `INVERTER_B` is inverter A copied**, carrying
`measured=False`. **Every two-inverter row below is a result about two copies of
A on a 10000 W rail, not about the ~9600 W site B implies.**
**The site rail becomes `sum(max_w)` ≈ 9600 W while `slew_w` is per-site.** The
derived value there is `0.1111 × 9600 = 1067 W` per tick, which at an even split
is 533 W per unit against each unit's own 5000/4600 W rating — ARCH-01's
split-invariance holding, as its `two_master_gain_sweep` already shows.
**Does the enforced relationship produce it automatically? Yes.** Rule 10 reads
`sum(unit_caps(opts))` and `slew_limit_w()` reads `Tuning.max_w`, which
`main.py` sets from `Controller.site_max_w`. Declaring inverter B moves both,
with no operator action and no second derivation. That is the property that
makes this a fix rather than a re-tune, and `test_validate.py` asserts the
9600 W arithmetic directly.
⚠️ **But the direction of the rule is not the one the ticket assumed, and it
must be said.** A rail that **grows loosens** this bound: `slew_w: 1000`
crosses 9600 W in 19.2 s and **passes**, while the same 1000 at 5000 W is the
configuration measured failing. That is what the constraint says and it is
correct — the bound is on how long the crossing *takes*. What the rule protects
against is the constant being left behind when the rail moves, in either
direction. **It is not a bound on how much power the site may command** (that is
each unit's own `max_w` through the arbiter's `supervised` claim) **and it does
not bound the over-absorption** (§6).
⚠️ **The ≥ 900 W symptom goes stale at N = 2 the same way the constant did.**
On the two-copies-of-A rows, 48/51 runs contain a ≥ 900 W step *at the derived
value*, because at a 10000 W rail the derived step **is** 1111 W. A check
written on the absolute 900 W would report the correct tuning as broken.
Anything grading this symptom at N ≥ 2 has to grade it as a **fraction of the
rail** too — which is this whole card, one layer out.
---
## 8. `max_w: 5000` — a recommendation, not a change
The battery reached **5154 W against a 5000 VA inverter**, so the configured cap
left no headroom for the overshoot that the loop was going to produce anyway.
Three things are worth writing down and none of them is changed here:
1. **The cap is the rating, so the overshoot has nowhere to go but past it.**
`compute()` bounds the *command* to `±max_w`; nothing bounds the plant's
response to a command at the rail, and §6 shows the loop asks for the rail on
any large step at gain 0.6. Recommend **`max_w` at 4500–4750 W**, i.e. 90–95 %
of the 5000 VA nameplate, leaving 250–500 W for the overshoot the loop still
has. This is `freeze.py`'s `RAIL_FRAC` argument applied to the cap itself.
2. **The −5154 W may not be an AC figure at all.** `batt_entity` is the pack
sensor and `max_w` is graded against `0x0518`, the inverter's **AC** power —
`config.yaml`'s roster comment already records exactly this ambiguity for
inverter B. If the battery reading is DC, 5154 W DC is ~4900 W AC and the
inverter was never over its nameplate. **Nobody has measured which**, and the
recommendation above is worth making either way.
3. **It is the owner's number.** `translations/en.yaml` marks `max_w` "THIS IS
YOUR NUMBER" precisely so it is not confused with a derived constant, and
changing it unilaterally in a pull request would undo that distinction.
`SAFETY-20`'s `min(max_w, dev_max)` settles the device side once ESPHome has
answered; the *headroom* question is a policy choice and belongs to the owner.
---
## 9. What was deliberately not done
* **`saturation_w` and the deadband were not touched.** The card forbids it and
it is right to: widening either hides the symptom. The loop is following its
command correctly; the command is wrong.
* **`gain` was not changed.** §6.
* **`max_w` was not changed.** §8.
* **`control.py`'s slew *limit* was not clamped to the bound.** An explicit
value above it is refused at startup, not quietly reduced — silently reducing
an operator's stated bound is case (a) in `validate.py`'s docstring.
* **Nothing in admin/goodwe was modified**, and nothing reached the inverter.
+1 -1
View File
@@ -432,7 +432,7 @@ behind it would trip the firmware watchdog on a system that is working fine.
|---|---|---|
| `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 |
| `slew_w` | 0 | Largest change in one cycle. **0 means follow the rail** - `max_w / 9`, i.e. the loop takes the plant's own measured ~18 s settling time to cross its whole output range at the 2 s tick the live install runs. 222 W at `max_w: 2000`, 556 W at 5000, 1067 W at a ~9600 W two-inverter site. A fixed number is accepted and never silently reduced, but one FASTER than the rail implies is refused at startup (SAFETY-39): `slew_w: 1000` against `max_w: 5000` crossed the rail in 10 s against an 18 s plant, and on 2026-09-05 drove the meter from 3.4 kW of export to 2.8 kW of import |
| `deadband_w` | 15 | Ignore errors smaller than this |
| `target_grid_w` | -10 | What the meter should rest at. Negative = a slight export |
| `step_w` | 10 | Quantisation |
+12
View File
@@ -122,6 +122,18 @@ CIRC_OPTION_DEFAULTS = {
# 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
#
# ⚠️ SAFETY-39 MOVED THAT SCHEMA FLOOR FROM 50 TO 0, AND THE CAMPAIGN ABOVE
# WAS NOT RE-RUN. It does not have to be, and here is the argument rather
# than the assurance. What these windows are about is how long the command
# takes to CROSS ITS RAIL - the swept worst case is the SLOWEST crossing,
# which is `slew_w` at its floor, 5000/50 = 100 cycles. `slew_w: 0` means
# "follow the rail" and resolves to `SLEW_RAIL_FRAC * max_w`, which is
# exactly 9 cycles at EVERY rail by construction. So the new value can never
# be the slowest crossing at any `max_w`, and it is strictly inside the
# envelope this campaign measured. An explicit number still spans 50..5000
# and is unchanged. If `SLEW_RAIL_FRAC` is ever loosened past 1/100, this
# paragraph stops being true and the campaign has to be re-run.
#
# 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
+105 -2
View File
@@ -18,12 +18,92 @@ exists because its absence produced a specific, observed failure.
from dataclasses import dataclass
# ---------------------------------------------------------------------------
# SAFETY-39. THE ONE RELATIONSHIP IN THIS FILE THAT IS NOT A NUMBER.
#
# ⚠️ WHAT WENT WRONG, because the shape of it is the reason this is a ratio and
# not a constant. `slew_w: 1000` was derived on 2026-08-22 against a clamp of
# 1500 W (goodwe/NOTES.md, "Simulated 2 kW load step (gain 0.6, clamp 1500)"),
# and its stated justification was that it "puts most of the correction in the
# first cycle WHILE STILL CAPPING HOW FAR THE LOOP CAN JUMP AHEAD OF THE
# INVERTER". At 1500 W that sentence was true: 1000 W/cycle reaches the rail in
# two cycles and the rail itself bounds the excursion.
#
# The rail then moved to 5000 W on the live install and the constant did not.
# 1000 W per 2 s tick is 500 W/s, so the loop traverses its WHOLE OUTPUT RANGE
# in 10 s against a plant NOTES.md §5.10 measured at ~18 s up / ~23 s down for a
# 1.78 kW step. It commands its entire range before it can observe its answer to
# the first step. Measured on the owner's system 2026-09-05 11:43-11:46: a real
# 3.4 kW export, the setpoint ramping 380 -> 5000 in five ticks, the battery at
# -5154 W against a 5000 VA inverter, and the grid pushed from 3.4 kW of EXPORT
# to 2.8 kW of IMPORT - the loop manufactured the error it then chased.
#
# ⚠️ SO THE FIX IS NOT A NEW NUMBER. A number is what went stale. What is
# written here is the RELATIONSHIP the 2026-08-22 sentence was really asserting:
#
# THE LOOP MUST NOT TRAVERSE ITS FULL OUTPUT RANGE FASTER THAN THE PLANT
# TAKES TO SETTLE.
#
# slew_w <= max_w * LOOP_TICK_S / PLANT_SETTLE_S
#
# `max_w` here is the SITE rail (main.py builds `Tuning(max_w=site_max_w)`, the
# roster sum), so the bound moves with the roster and a second inverter cannot
# re-open this by arriving. validate.py rule 10 refuses a configuration that
# breaks it; `slew_w = 0` below means "follow the rail" and is the shipped
# default, exactly as `integrator_max_w = None` already means "follow max_w".
#
# ⚠️ BOTH NUMBERS ARE WRITTEN OUT RATHER THAN THEIR QUOTIENT, AND THAT IS NOT
# TIDINESS. The quotient is only meaningful in the regime the two were measured
# in, and one of them is NOT a property of this code:
#
# PLANT_SETTLE_S is the inverter and the pack. goodwe/NOTES.md §5.10,
# 2026-08-22, a 1.78 kW kettle step driven from HA with a
# plug that meters its own draw: ~18 s from the step to the
# deadband going up, ~23 s coming down. 18 is taken because
# it is the SHORTER of the two and therefore the LOOSER
# bound - this is a refusal boundary, and rules 5 and 6 in
# validate.py refuse the impossible case only, never "close
# to the rail".
#
# LOOP_TICK_S is the METER, not this loop. `run_control()` runs a cycle on
# a changed meter value or on `cycle_floor_s`, whichever comes
# first, so the tick is the meter's own update rate. 2.0 s is
# what the live install measured on 2026-09-05 (the setpoint
# stepped +1000 W every 2 s), and it is the fastest meter this
# project has ever run.
#
# ⚠️ AND THIS ONE IS NOT WRONG IN THE SAFE DIRECTION, WHICH IS WHY IT IS SAID
# HERE. A SLOWER meter makes this bound conservative - it refuses some
# configurations that would have been fine, which is visible immediately and
# costs one edit. A meter FASTER than 2 s makes it loose by exactly that ratio,
# and nothing in this add-on would say so. The tick cannot go below 1 s
# (`run_control()`'s `await asyncio.sleep(1)` bounds the loop body), so the
# worst case is a factor of two - but if a faster meter is ever fitted, this
# constant has to be RE-DERIVED and not merely re-read. Compare
# validate.FIRMWARE_INGEST_VETO_S, which carries the same kind of copy and can
# only ever be wrong the other way.
PLANT_SETTLE_S = 18.0
LOOP_TICK_S = 2.0
SLEW_RAIL_FRAC = LOOP_TICK_S / PLANT_SETTLE_S # 0.111..., i.e. 9 ticks
@dataclass(frozen=True)
class Tuning:
gain: float = 0.6
max_w: float = 2000.0
slew_w: float = 1000.0
# SAFETY-39. How far the command may move in one cycle. ⚠️ 0 MEANS "FOLLOW
# THE RAIL" - `SLEW_RAIL_FRAC * max_w` - and it is the default and the
# recommended setting, for the reason written at the top of this file: a
# fixed number here is a constant that outlives the rail it was derived
# against, and that is the defect measured on the live system on
# 2026-09-05. Read `slew_limit_w()`, never this field.
#
# It stays settable, because slower than the rail implies is a legitimate
# and sometimes necessary choice - the live install has run an explicit
# 400 W since 2026-09-05 12:00 - and because `slew_w` is an option an
# operator already has. FASTER than the rail implies is what validate.py
# rule 10 refuses.
slew_w: float = 0.0
deadband_w: float = 15.0
step_w: int = 10
saturation_w: float = 500.0
@@ -83,6 +163,28 @@ class Decision:
clamped: bool = False
def slew_limit_w(tuning: Tuning) -> float:
"""How far the command may move this cycle, in W. Always positive.
⚠️ THE ONE READER OF `Tuning.slew_w`, and everything else must come through
here. `slew_w = 0` means "follow the rail" and resolves to
`SLEW_RAIL_FRAC * max_w`, which is the whole of SAFETY-39: the limit is a
RATIO to the rail, so raising `max_w` moves it and cannot leave it behind.
A caller that read the field directly would see 0 and apply no limit at all
- the exact opposite of the setting's meaning - which is why this exists as
a function rather than as a comment telling people to remember.
⚠️ AND IT IS NOT CLAMPED TO THE BOUND. An explicit `slew_w` above the rail
fraction is refused at STARTUP by validate.py rule 10, not silently reduced
here. Silently reducing it is the failure this whole module's docstring is
about - an operator's stated number quietly meaning something else - and
validate.py's own docstring calls it case (a).
"""
if tuning.slew_w:
return abs(float(tuning.slew_w))
return SLEW_RAIL_FRAC * abs(float(tuning.max_w))
def compute(
prev_w: float,
grid_w: float,
@@ -231,7 +333,8 @@ def compute(
if clamped:
reason = "clamped"
slewed = max(prev_w - tuning.slew_w, min(prev_w + tuning.slew_w, target))
slew = slew_limit_w(tuning)
slewed = max(prev_w - slew, min(prev_w + slew, target))
if slewed != target:
reason = "slew-limited"
target = slewed
+7 -1
View File
@@ -247,7 +247,13 @@ class Controller:
# binds each unit's own share through its own `supervised` claim, so
# nothing here can over-command a device.
max_w=self.site_max_w,
slew_w=float(opts.get("slew_w", 1000)),
# ⚠️ SAFETY-39: THE FALLBACK IS 0 AND 0 MEANS "FOLLOW THE RAIL",
# which is what config.yaml ships and what `Tuning`'s own default
# is. It used to be 1000 - a third copy of a constant that had
# already gone stale against the rail in the other two - and rule
# 6's comment in validate.py documents what that costs when the
# copies disagree. `control.slew_limit_w()` is the one reader.
slew_w=float(opts.get("slew_w", 0) or 0),
deadband_w=float(opts.get("deadband_w", 15)),
target_grid_w=float(opts.get("target_grid_w", 0)),
step_w=int(opts.get("step_w", 10)),
+160
View File
@@ -183,6 +183,60 @@ NOT READY banner already names the problem, (b) does not apply.
the per-unit form and main.py runs it from `run_control()`, once every
unit's own ESPHome has replied.
10. `slew_w` above the fraction of the SITE RAIL the plant can follow. [(a)]
SAFETY-39, and the first rule here whose subject is a RELATIONSHIP rather
than a threshold. `slew_w` bounds how far the site command may move in one
cycle; `control.SLEW_RAIL_FRAC` is `LOOP_TICK_S / PLANT_SETTLE_S`, so
`SLEW_RAIL_FRAC * rail` is the largest step at which the loop still takes
the plant's own measured settling time to traverse its whole output range.
Above it the controller commands its entire range before it can observe
its answer to the first step, and the stated limit - "the command moves at
most `slew_w` per cycle, so it cannot jump ahead of the inverter" - is
untrue: it jumps ahead by construction.
⚠️ THIS IS (a) AND NOT (b), and the distinction is what makes it a refusal
rather than a warning. Nothing goes inert. What happens is that a bound
the operator set means something other than what it says, and the layer
that overrules it is the PLANT - which has no status row, publishes
nothing, and cannot be read off any page in this add-on. Measured on the
owner's system 2026-09-05 11:43-11:46 at `max_w: 5000`, `slew_w: 1000`:
setpoint 380 -> 5000 in five 2 s ticks, battery -5154 W against a 5000 VA
inverter, and the grid driven from 3.4 kW of EXPORT to 2.8 kW of IMPORT.
Large (>= 900 W) setpoint steps per 30 min climbed 2 -> 1 -> 13 -> 43 that
morning. Nothing in the add-on reported anything wrong, because nothing
was: the loop followed its command exactly, and the command was wrong.
⚠️ IT IS GRADED AGAINST THE ROSTER SUM, NOT THE FLAT `max_w` AND NOT THE
WEAKEST UNIT, and this is the one rule in this file for which that is the
right rail. Rules 5, 6 and 8 are all about ONE unit - one watchdog, one
shaping claim, one pack - so they take `min()` over `unit_caps()`.
`slew_w` is not per unit: `main.py` builds `Tuning(max_w=self.site_max_w)`
and `compute()` produces the SITE target, which the allocator then splits.
So the range this bound is about is the sum, `Controller.site_max_w`, and
`site_rail_w()` below is that same number computed from options.
⚠️ AND THE `site_sign_disagree_w` NOTE IN config.yaml IS NOT A PRECEDENT
AGAINST THIS. That note says there is deliberately no rule pairing
`site_sign_disagree_w` with `max_w`, "because 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." That objection is
to grading a site quantity against the FLAT key. It is answered rather than
ignored: `unit_caps()` already reads the roster the add-on will build, so
the roster sum IS available here, and this rule takes it.
⚠️ THE DIRECTION OF THIS RULE, SAID PLAINLY, BECAUSE IT IS NOT THE
DIRECTION THE TICKET ASSUMED. A rail that GROWS loosens this bound: at a
9600 W two-inverter rail, `slew_w: 1000` traverses the rail in 19.2 s and
passes, while at 5000 W the same 1000 W is the configuration measured
above. That is what the constraint says and it is correct - the bound is on
traverse TIME, and a bigger rail at the same step size takes longer to
cross. What this rule therefore protects against is the constant being left
behind when the rail moves EITHER way. It is NOT a bound on how much power
the site may command, and it does NOT bound the over-absorption: see the
note below on `gain`, which is the term that owns that and which SAFETY-39
measured and did not change.
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
@@ -226,6 +280,34 @@ WHAT IS DELIBERATELY *NOT* REFUSED, because it is untidy rather than unsafe:
is answered. Compare rule 5, which CAN be settled at startup because both
`sign_disagree_w` and `max_w` are config and are both known at boot.
- `gain` at any value the schema accepts, INCLUDING against a large rail.
SAFETY-39 measured this and deliberately left it alone, which is worth more
than the rule would have been. On admin/goodwe's rig, over a family of 51
export steps from 1.0 to 4.2 kW at `max_w: 5000` and a 2 s tick, the
over-absorption - peak battery power beyond what the site actually needed -
is FLAT in `slew_w`: 958 W at slew 1000 and 1081 W at slew 250. It falls
in `gain`: 987 W at 0.6, 876 W at 0.3, 435 W at 0.2 - a real reduction, but
NOT to zero, and the 0.2 figure is the one worth not rounding away. The
reason is structural and is visible in control.py: `slew_w` bounds the
OUTPUT, while the integrator accumulates `gain * error` per cycle and is
bounded only by `integrator_max_w`. At gain 0.6 into a 3.4 kW error the
integrator moves ~2040 W per tick and reaches a 5000 W rail in under three
ticks whatever `slew_w` is.
So the 2026-08-22 derivation's own sentence - "the gain, not the slew, is
the limit by then" - is now literally true, and `gain` is the constant that
needs re-deriving next. It is NOT refused and NOT changed here: it is a
live control-law constant on a running house, changing it in the same pull
request as `slew_w` would make the next measurement uninterpretable, and a
validator rule pairing `gain` with a rail would be inventing a relationship
nobody has measured. Named here so it is a known open item rather than an
omission. See DECISIONS/SAFETY-39-slew-against-the-rail.md.
- `slew_w` BELOW the rail fraction, at any value the schema accepts. Slower
than the plant is always safe and is sometimes necessary - the live install
has run an explicit 400 W against a 5000 W rail since 2026-09-05 12:00,
which is 12.5 ticks to traverse the rail against the 9 this rule requires.
Refusing "too slow" would refuse the mitigation that is holding.
- `peak_soc_floor` below `maintenance_soc_floor`, or above it. They are
DIFFERENT QUANTITIES (SAFETY-24: a drain target versus a spend limit) and
every ordering of the two is a legitimate site configuration. Refusing on
@@ -235,6 +317,7 @@ WHAT IS DELIBERATELY *NOT* REFUSED, because it is untidy rather than unsafe:
import logging
from .arbitrage import enabled as arbitrage_on
from .control import SLEW_RAIL_FRAC, LOOP_TICK_S, PLANT_SETTLE_S
from .inverter import roster_entries
from .maintenance import MAINT_OPTION_DEFAULTS
from .p1 import is_enabled, validate_meter_options
@@ -392,6 +475,27 @@ def unit_caps_indexed(opts: dict) -> list[tuple[int, float]]:
return caps
def site_rail_w(opts: dict) -> float | None:
"""The SITE rail: what the whole site may be commanded, in W. Rule 10's rail.
⚠️ THE SUM, NOT THE MINIMUM, AND NOT THE FLAT KEY - and it is the only place
in this file that wants a sum. Rules 5, 6 and 8 grade a threshold against
ONE unit (one watchdog, one shaping claim, one pack) and take `min()` over
`unit_caps()`. `slew_w` is not a per-unit quantity at all: `main.py` builds
`Tuning(max_w=self.site_max_w)` from the roster sum and `compute()` emits
the SITE target, which the allocator then divides. So the output range
`slew_w` is a rate across is `Controller.site_max_w`, and this is that same
number read out of options rather than off a built roster.
At the shipped roster of one this is `unit_caps()`'s single entry, which is
`max_w` exactly - byte for byte the number the single-inverter shape has
always meant. None when no entry carries a usable cap, which rule 9 has
already refused by the time rule 10 runs.
"""
caps = unit_caps(opts)
return float(sum(caps)) if caps else None
def unit_bms_floors_indexed(opts: dict) -> list[tuple[int, object, object]]:
"""SAFETY-32. Each pack's OWN `bms_soc_floor`, carrying its ROSTER INDEX.
@@ -935,6 +1039,62 @@ def validate_startup_config(opts: dict, dev_min=None, dev_max=None) -> list[str]
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.")
# --- 10. a slew rate the plant can actually follow -----------------------
# ⚠️ SAFETY-39. The one rule here that grades a RATIO rather than a
# threshold, and the whole point of writing it as one is that the number it
# bounds must not be able to outlive the rail again. `control.py`'s header
# carries the derivation; the short version is that `slew_w: 1000` was
# derived against a 1500 W clamp and the live install raised the clamp to
# 5000 without revisiting it, so the loop traversed its whole output range
# in 10 s against a plant measured at ~18 s.
#
# ⚠️ `slew_w: 0` IS NOT GRADED AND MUST NOT BE. Zero means "follow the
# rail" - `control.slew_limit_w()` resolves it to `SLEW_RAIL_FRAC * max_w`,
# which satisfies this rule by construction at every rail there is. It is
# the shipped default, and a rule that refused it would refuse the fix.
#
# ⚠️ STRICTLY `>`, MATCHING RULE 6 RATHER THAN RULE 5. Equality is the
# derived value itself: at `slew_w == SLEW_RAIL_FRAC * rail` the loop takes
# exactly `PLANT_SETTLE_S` to cross its range, which is the constraint
# satisfied, not violated. Refusing it would refuse the value this rule
# exists to recommend - and `slew_limit_w()` produces exactly that value
# for every default install, so `>=` would refuse the shipped default
# through a float comparison. A tolerance is applied for the same reason:
# `SLEW_RAIL_FRAC * 5000` is 555.55..., and an operator who writes the 556
# a status page rounded to is one watt over a boundary that is not
# meaningful to one watt.
slew_w = _number(opts, "slew_w", 0.0)
rail = site_rail_w(opts)
if slew_w is None:
problems.append(f"slew_w {opts.get('slew_w')!r} is not a number")
elif slew_w < 0:
problems.append(
f"slew_w is {slew_w:.0f} W and must not be negative - it is a "
"magnitude, and 0 means 'follow max_w' (the recommended setting).")
elif slew_w and rail is not None and rail > 0:
bound = SLEW_RAIL_FRAC * rail
if slew_w > bound + 1.0:
ticks = rail / slew_w
problems.append(
f"slew_w is {slew_w:.0f} W against a site rail of {rail:.0f} W, "
f"so the loop crosses its whole output range in {ticks:.1f} "
f"cycles - {ticks * LOOP_TICK_S:.0f} s at the {LOOP_TICK_S:.0f} s "
f"tick this site was measured running - while the plant takes "
f"{PLANT_SETTLE_S:.0f} s to settle (goodwe/NOTES.md §5.10, a "
"1.78 kW step). The controller would command its entire range "
"before it could observe its answer to the first step, which is "
"not a slow loop, it is a loop that MANUFACTURES the error it "
"then chases: measured on this system 2026-09-05, a 3.4 kW "
"export drove the setpoint 380 -> 5000 W in five ticks, the "
"battery to -5154 W past a 5000 VA rating, and the grid from "
"3.4 kW of export to 2.8 kW of import. The stated limit - the "
"command moves at most slew_w per cycle, so it cannot jump "
"ahead of the inverter - is untrue at this rail; THE PLANT "
f"WINS, and it has no status row. Set slew_w to 0, which means "
f"'follow the rail' and resolves to {bound:.0f} W here and "
"moves on its own if the rail does, or write a value at or "
f"below {bound:.0f} W. Lower is always accepted.")
# --- 7. two price sources on one site ------------------------------------
problems.extend(_price_problems(opts))
+12
View File
@@ -331,6 +331,18 @@ SIGN_OPTION_DEFAULTS = {
# 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
#
# ⚠️ SAFETY-39 MOVED THAT SCHEMA FLOOR FROM 50 TO 0, AND THE CAMPAIGN ABOVE
# WAS NOT RE-RUN. It does not have to be, and here is the argument rather
# than the assurance. What these windows are about is how long the command
# takes to CROSS ITS RAIL - the swept worst case is the SLOWEST crossing,
# which is `slew_w` at its floor, 5000/50 = 100 cycles. `slew_w: 0` means
# "follow the rail" and resolves to `SLEW_RAIL_FRAC * max_w`, which is
# exactly 9 cycles at EVERY rail by construction. So the new value can never
# be the slowest crossing at any `max_w`, and it is strictly inside the
# envelope this campaign measured. An explicit number still spans 50..5000
# and is unchanged. If `SLEW_RAIL_FRAC` is ever loosened past 1/100, this
# paragraph stops being true and the campaign has to be re-run.
#
# ⚠️ 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
+44 -2
View File
@@ -516,7 +516,40 @@ options:
# ==========================================================================
auto_start: false
gain: 0.6
slew_w: 1000
# ⚠️ SAFETY-39. 0 IS NOT "UNSET" AND IT IS NOT "NO LIMIT" - IT IS "FOLLOW THE
# RAIL", and it is the shipped value. `control.slew_limit_w()` resolves it to
# `SLEW_RAIL_FRAC * max_w`, which is 222 W against the 2000 W default here,
# 556 W against the live install's 5000 W, and 1067 W against the ~9600 W a
# second inverter makes of the site. `integrator_max_w: 0` two lines down has
# meant exactly this since it was added; this key now means it too.
#
# ⚠️ WHY IT IS A RATIO AND NOT A NUMBER, WHICH IS THE WHOLE OF THIS CARD. It
# WAS a number: 1000, derived 2026-08-22 against a clamp of 1500 W
# (goodwe/NOTES.md, "Simulated 2 kW load step (gain 0.6, clamp 1500)") on the
# grounds that it caps "how far the loop can jump ahead of the inverter". The
# rail then went to 5000 on the live install and the constant did not move, so
# 1000 W per 2 s tick crossed the whole output range in 10 s against a plant
# NOTES.md §5.10 measured at ~18 s up / ~23 s down. Measured on the owner's
# system 2026-09-05 11:43-11:46: a 3.4 kW export drove the setpoint 380 -> 5000
# in five ticks, the battery to -5154 W past a 5000 VA rating, and the grid
# from 3.4 kW of EXPORT to 2.8 kW of IMPORT. Large (>= 900 W) steps per 30 min
# went 2 -> 1 -> 13 -> 43 that morning. Nothing was broken; the rail moved.
#
# An explicit number is still accepted and is not clamped - the live install
# has run 400 since 2026-09-05 12:00, which is slower than the rail implies
# and is fine. What validate.py rule 10 refuses is a number FASTER than the
# rail implies, because at that setting the stated limit is not the limit and
# the layer that overrules it is the plant, which has no status row.
#
# ⚠️ AND THE COST IS REAL AND IS NOT HIDDEN: following the rail is slower to
# converge than 1000 was. Measured over 51 export steps on the in-repo model
# (test_control.py) the largest tick step falls from 1000 W to 556 W and the
# >= 900 W step disappears from every run - but the OVER-ABSORPTION does not
# move, because that is a `gain` term and not a slew term. See
# DECISIONS/SAFETY-39-slew-against-the-rail.md, which says so at length rather
# than letting this card be read as more than it is.
slew_w: 0
deadband_w: 15
target_grid_w: -10
step_w: 10
@@ -744,7 +777,16 @@ schema:
# ==========================================================================
auto_start: bool
gain: float(0.05,1.0)
slew_w: int(50,5000)
# ⚠️ THE FLOOR IS 0, NOT 50, AND 0 IS THE SHIPPED VALUE - see the options block
# above. It means "follow max_w", so the range starts at the setting that
# cannot go stale rather than at the smallest number somebody could type.
# ⚠️ THE CEILING IS STILL 5000 AND IS STILL NOT THE BOUND THAT MATTERS. The
# binding one is `SLEW_RAIL_FRAC * max_w`, a relation BETWEEN keys, and this
# grammar cannot express a relation - which is the same reason
# `maintenance_charge_w`'s ceiling is not its real bound either (see the note
# above it). validate.py rule 10 is where it is written.
slew_w: int(0,5000)
deadband_w: int(0,500)
target_grid_w: float(-200,200)
step_w: int(1,100)
+10 -1
View File
@@ -580,7 +580,16 @@ def close_loop(gain, split, cycles=200, load_w=2000.0, mode="alloc",
below. "site" is the sum of the units' power; "unit" is inverter A's alone,
which is what the shipped add-on's single `inverter_power` sensor gives it.
"""
tuning = Tuning(gain=gain)
# ⚠️ `slew_w` IS PINNED HERE AND WAS NOT BEFORE, AND THAT IS SAFETY-39.
# ARCH-01's 4000 W peak-to-peak broadcast limit cycle was measured at the
# shipped pair of the day - `max_w: 2000` with `slew_w: 1000` - and this
# function reached that 1000 through `Tuning`'s DEFAULT. SAFETY-39 made that
# default 0, meaning "follow the rail" (`SLEW_RAIL_FRAC * max_w`, 222 W at
# this rail), so the same call would now sweep a DIFFERENT law and report
# ARCH-01's measurement as absent. A reproduction that silently re-tunes
# itself when a default moves is not a reproduction. The number is written
# here, next to the measurement it belongs to.
tuning = Tuning(gain=gain, slew_w=1000.0)
prev, i_w, sat = 0.0, None, 0
power = [0.0, 0.0]
grid = load_w
+237 -5
View File
@@ -17,9 +17,19 @@ Read MUTATION.md before you report a survivor.
import sys
from app.control import Tuning, compute, maintenance_charge_floor, peak_at_risk
from app.control import (LOOP_TICK_S, PLANT_SETTLE_S, SLEW_RAIL_FRAC,
Tuning, compute, slew_limit_w,
maintenance_charge_floor, peak_at_risk)
T = Tuning()
# ⚠️ SAFETY-39: `slew_w` IS EXPLICIT HERE NOW, AND IT IS release/1.0's VALUE.
# `Tuning()`'s default became 0 - "follow the rail", `SLEW_RAIL_FRAC * max_w`,
# 222 W against this 2000 W rail - so a bare `Tuning()` here would silently
# re-tune every assertion below that the slew limit touches, and several of them
# assert on a number the slew produces. The pair written here (max_w 2000,
# slew_w 1000) is exactly what release/1.0 shipped, which is what most of this
# file is a regression test against. The new default gets its own section at the
# end, where it is the subject rather than a hidden parameter.
T = Tuning(slew_w=1000.0)
fails = []
@@ -49,6 +59,13 @@ def check(name, cond):
# A comment cannot go stale-green, because it never claims to be running.
#
# Measured at 389d9ec. Numbers are the lead's independent reproduction.
# ⚠️ THE SLEW ROWS WERE RE-MEASURED AT SAFETY-39 AND ONE OF THEM MOVED: the
# slew limit was 4 and is now 5, because the SAFETY-39 section grades it too.
# The new row is the RAIL DEFAULT specifically - `slew_limit_w()` reduced to
# `return abs(float(tuning.slew_w))`, which leaves the limit intact and only
# removes the 0-means-the-rail resolution. Three checks notice, which is over
# the invariant's floor of two. Both figures were reproduced by deleting the
# mechanism, running this file and counting, on a tree with __pycache__ purged.
#
# mechanism in compute() checks that fail when deleted
# ------------------------------------------ -----------------------------
@@ -56,7 +73,8 @@ def check(name, cond):
# integrator clamp (AC 1) 6
# integrator bound follows max_w 4
# output clamp 3
# slew limit 4
# slew limit 5
# slew follows the rail (SAFETY-39), `slew_w` read raw 3
# output freeze 2
# deadband 5
# quantisation 2
@@ -328,7 +346,14 @@ def unwind(t):
return prev
tight, loose = unwind(Tuning(max_w=2000)), unwind(Tuning(max_w=2000, integrator_max_w=3000))
# ⚠️ BOTH FIXTURES CARRY release/1.0's `slew_w` EXPLICITLY (SAFETY-39). The
# subject here is `integrator_max_w`, and the figure the check names - 1000 W on
# the first cycle after the drop - is `max_w - slew_w`, so it moves with the slew
# limit and would stop being the number DOCS.md quotes. Pinning it keeps this a
# test about integrator headroom instead of a test about two mechanisms at once;
# the shipped default's own unwind is measured in the SAFETY-39 section below.
tight = unwind(Tuning(max_w=2000, slew_w=1000.0))
loose = unwind(Tuning(max_w=2000, slew_w=1000.0, integrator_max_w=3000))
check(f"after saturation ends the command is {tight:.0f} W (<= 1000)", tight <= 1000)
check(f"headroom above max_w makes that worse ({loose:.0f} W) - hence the default",
loose > tight)
@@ -372,7 +397,15 @@ def legacy(prev, grid, actual, t, sat_count):
ALIAS = {"i-clamped": "clamped"}
diffs = []
seen = set()
for tune in (Tuning(), Tuning(target_grid_w=-10.0), Tuning(max_w=5000, slew_w=5000)):
# ⚠️ `slew_w` IS WRITTEN OUT IN ALL THREE (SAFETY-39). `legacy()` below is a
# TRANSCRIPTION of release/1.0 and reads `t.slew_w` directly, as release/1.0
# did; the new law reads `slew_limit_w(t)`, which treats 0 as 'follow the
# rail'. The two agree for every non-zero value and differ at 0 BY DESIGN, so
# a fixture that left the field at its new default would report the design as
# a regression. Fixing it in `legacy()` instead would make this sweep compare
# the new law against itself, which is the one thing it must never do.
for tune in (Tuning(slew_w=1000.0), Tuning(slew_w=1000.0, target_grid_w=-10.0),
Tuning(max_w=5000, slew_w=5000)):
for prev in (-2000.0, -500.0, -100.0, 0.0, 100.0, 500.0, 2000.0):
for grid in (-6000.0, -1000.0, -500.0, -14.0, 0.0, 14.0, 500.0, 1000.0, 6000.0):
for actual in (-2000.0, 0.0, 600.0, 2000.0):
@@ -443,6 +476,205 @@ check("worst billed rest point falls from 15 W to under 5 W",
compute(500.0, 4.9, 500.0, TB).reason == "deadband"
and compute(500.0, 5.0, 500.0, TB).reason != "deadband")
print("SAFETY-39: the slew limit is a RATIO to the rail, not a number")
# ⚠️ WHAT WENT WRONG, IN ONE LINE, BECAUSE THE SHAPE IS THE POINT. `slew_w:
# 1000` was derived on 2026-08-22 against a clamp of 1500 W and its stated
# justification was that it caps "how far the loop can jump ahead of the
# inverter". The live install then ran max_w 5000 with the same 1000, and on
# 2026-09-05 11:43-11:46 a real 3.4 kW export drove the setpoint 380 -> 5000 W
# in five 2 s ticks, the battery to -5154 W against a 5000 VA inverter, and the
# grid from 3.4 kW of EXPORT to 2.8 kW of IMPORT. Nothing was broken. The rail
# moved and the constant did not.
#
# So what is graded below is the RELATIONSHIP and not a value: at every rail,
# the loop takes the plant's own settling time to cross its whole output range.
# A check that pinned "555 W" would go stale the same way the comment did.
print(f" SLEW_RAIL_FRAC = LOOP_TICK_S / PLANT_SETTLE_S = {SLEW_RAIL_FRAC:.4f}"
f" ({1 / SLEW_RAIL_FRAC:.0f} ticks to cross the rail)")
check("0 means FOLLOW THE RAIL and resolves to SLEW_RAIL_FRAC * max_w",
slew_limit_w(Tuning(max_w=5000.0, slew_w=0.0)) == SLEW_RAIL_FRAC * 5000.0)
check("an explicit value is passed through untouched - it is the operator's "
"number and nothing here silently reduces it",
slew_limit_w(Tuning(max_w=5000.0, slew_w=400.0)) == 400.0)
check("the shipped Tuning default is 0, i.e. the rail, so the law carries no "
"second constant to go stale beside config.yaml",
Tuning().slew_w == 0.0)
# ⭐ THE RELATIONSHIP ITSELF, over every rail this add-on can be built at: the
# single-inverter schema range (100..5000), the live install (5000), and the
# roster sums a second inverter produces - 9600 with inverter B's datasheet
# figure, 10000 with two of A. ⚠️ 9600 IS NOT A MEASUREMENT: inverter B does not
# exist on site yet (SPIKE-04, ~2026-09-12) and 4600 W is its datasheet and
# serial, per goodwe/NOTES.md §1.1b. It is here because the ARITHMETIC is what
# is being graded, and the arithmetic does not care.
_rails = [100.0, 500.0, 1500.0, 2000.0, 5000.0, 9600.0, 10000.0]
_ticks = {r: r / slew_limit_w(Tuning(max_w=r)) for r in _rails}
print(" ticks to cross the rail at the default, by rail: "
+ ", ".join(f"{r:.0f}W={t:.1f}" for r, t in _ticks.items()))
check("⭐ AT EVERY RAIL THE DEFAULT TAKES THE SAME NUMBER OF TICKS TO CROSS IT - "
"which is PLANT_SETTLE_S at the measured tick. This is the whole of "
"SAFETY-39: raising max_w moves the slew limit with it, so the constant "
"cannot be left behind by the rail again",
all(abs(t - PLANT_SETTLE_S / LOOP_TICK_S) < 1e-9 for t in _ticks.values()))
check("...and that is the same as saying the crossing takes the plant's own "
f"measured settling time ({PLANT_SETTLE_S:.0f} s) at the "
f"{LOOP_TICK_S:.0f} s tick the live install was measured running",
all(abs(t * LOOP_TICK_S - PLANT_SETTLE_S) < 1e-9 for t in _ticks.values()))
# ⭐ VERIFIED BY BREAKING IT. The configuration that produced the 2026-09-05
# excursion, put through the same arithmetic: it crosses the rail in 10 s
# against a plant that takes 18 s. This is the number validate.py rule 10
# refuses on, and it is asserted HERE too so that the law and the gate cannot
# drift apart - the rule can only ever refuse what this ratio says is too fast.
_broken = Tuning(max_w=5000.0, slew_w=1000.0)
_broken_s = 5000.0 / slew_limit_w(_broken) * LOOP_TICK_S
print(f" the 2026-09-05 configuration (max_w 5000, slew_w 1000) crosses its "
f"rail in {_broken_s:.0f} s against a plant measured at {PLANT_SETTLE_S:.0f} s")
check("⭐ RESTORING slew_w 1000 AT max_w 5000 IS FASTER THAN THE PLANT, and by "
"the ratio rather than by anybody's opinion - test_validate.py's rule 10 "
"section refuses exactly this pair",
_broken_s < PLANT_SETTLE_S
and slew_limit_w(_broken) > SLEW_RAIL_FRAC * _broken.max_w)
# THE CLOSED LOOP, AND WHAT THIS PLANT IS AND IS NOT.
#
# ⚠️ THE PLANT BELOW IS MODELLED HERE AND IS NOT THE RIG. admin/goodwe's
# `plantsim.Plant` is the battery model this project grades control changes
# against, and this repository's CI cannot reach it - that repository is private
# and this job's token is minted for this one (see .gitea/workflows/checks.yml).
# So the rig evidence lives in `tools/slew_sim.py`, is quoted in the pull
# request and in DECISIONS/SAFETY-39-slew-against-the-rail.md, and what runs
# HERE is a first-order lag with the time constant that reproduces §5.10's
# measured ~18 s to the deadband. test_alloc.py makes the same split for the
# same reason and says so in the same words.
#
# ⚠️ AND IT CANNOT SHOW A BATTERY ABOVE ITS RATING, WHICH IS SAID BEFORE THE
# RESULT RATHER THAN AFTER IT. Neither this model nor `plantsim.Plant` lets the
# plant exceed `p_max`; both clamp. The -5154 W against a 5000 VA inverter that
# the ticket reports is therefore NOT REPRODUCIBLE IN SIMULATION AT ALL, by
# construction, and no acceptance criterion here is written on it. What IS
# reproducible, and is what is graded, is the loop OVER-ABSORBING and driving
# the meter from export into import - the error it then chases.
_TAU_S = 6.0 # first-order lag; with the 2 s tick it reaches the
# deadband ~18 s after a step, which is §5.10's figure
def _step_run(tuning, export_w, load_w=350.0, phase=5, cycles=90,
dt=LOOP_TICK_S):
"""One export step onto a converged loop.
-> (worst import at the meter, peak battery beyond what the site NEEDED,
largest setpoint change in one tick).
"""
import math
prev, i_w, sat, actual, pv = 0.0, None, 0, 0.0, 0.0
a = 1.0 - math.exp(-dt / _TAU_S)
worst_import, peak, biggest, last = -1e9, 0.0, 0.0, None
for c in range(cycles):
if c == phase:
pv = export_w + load_w
grid = load_w - pv - actual
d = compute(prev, grid, actual, tuning, sat, i_w)
if c >= phase and last is not None:
biggest = max(biggest, abs(d.target_w - last))
last = d.target_w
prev, i_w, sat = d.target_w, d.i_w, d.sat_count
# the plant: a first-order lag, clamped at the rating like the real one
actual += (max(-tuning.max_w, min(tuning.max_w, prev)) - actual) * a
if c >= phase:
worst_import = max(worst_import, load_w - pv - actual)
peak = max(peak, abs(actual))
return worst_import, peak - export_w, biggest
def _family(tuning):
"""The worst case over 51 export steps, 1.0-4.2 kW, at three phases.
⚠️ A FAMILY AND NOT ONE STEP, AND THAT IS A FINDING RATHER THAN CAUTION.
A single run of this loop is not evidence: the deadband, the 10 W
quantisation and the phase of the step against the tick move the result by
hundreds of watts, non-monotonically, so two adjacent slews can rank either
way on one step and the opposite way on the next. Every number below is a
worst case over the family, which is how admin/goodwe grades the same
quantities (see `config.yaml`'s "1890 closed-loop runs" and "924 runs").
"""
worst = dict(imp=-1e9, over=-1e9, step=0.0, big=0, runs=0)
for export_w in range(1000, 4300, 200):
for phase in (5, 6, 7):
imp, over, step = _step_run(tuning, float(export_w), phase=phase)
worst["runs"] += 1
worst["imp"] = max(worst["imp"], imp)
worst["over"] = max(worst["over"], over)
worst["step"] = max(worst["step"], step)
worst["big"] += step >= 900.0
return worst
_LIVE = Tuning(max_w=5000.0, slew_w=1000.0) # what ran on 2026-09-05
_RAIL = Tuning(max_w=5000.0) # slew_w 0 - follow the rail
_INTERIM = Tuning(max_w=5000.0, slew_w=400.0) # applied live 2026-09-05 12:00
_SLOWER = Tuning(max_w=5000.0, slew_w=250.0)
_GAIN03 = Tuning(max_w=5000.0, gain=0.3)
_GAIN02 = Tuning(max_w=5000.0, gain=0.2)
_R = {k: _family(t) for k, t in
(("live", _LIVE), ("rail", _RAIL), ("interim", _INTERIM),
("slower", _SLOWER), ("gain03", _GAIN03), ("gain02", _GAIN02))}
print(f" worst case over {_R['live']['runs']} export steps at max_w 5000, "
f"{LOOP_TICK_S:.0f} s tick:")
for _k, _lab in (("live", "gain 0.6 slew_w 1000 (the 2026-09-05 live pair)"),
("rail", "gain 0.6 slew_w 0 (follow the rail)"),
("interim", "gain 0.6 slew_w 400 (the live interim)"),
("slower", "gain 0.6 slew_w 250"),
("gain03", "gain 0.3 slew_w 0"),
("gain02", "gain 0.2 slew_w 0")):
_w = _R[_k]
print(f" {_lab:<48} largest tick step {_w['step']:5.0f} W, "
f"{_w['big']:2}/{_w['runs']} runs step >= 900 W, "
f"over-absorbed {_w['over']:5.0f} W, meter driven to {_w['imp']:+6.0f} W")
# ⭐ THE DEFECT, REPRODUCED BEFORE ANYTHING IS CHANGED. The live pair steps the
# setpoint by a full 1000 W on nearly every member of the family and drives the
# meter from EXPORT into IMPORT - the loop manufacturing the error it then
# chases. That is the 2026-09-05 observation and it is what makes this a control
# fault rather than a slow loop.
check("⭐ REPRODUCED: at max_w 5000 with slew_w 1000 the setpoint steps a full "
"1000 W per tick on nearly every step in the family, and the meter is "
"driven from export into import",
_R["live"]["step"] >= 900.0
and _R["live"]["big"] > 0.9 * _R["live"]["runs"]
and _R["live"]["imp"] > 200.0)
check("⭐ FIXED, ON THE THING THE SLEW ACTUALLY OWNS: following the rail removes "
"the >= 900 W step from EVERY member of the family - which is the symptom "
"that escalated 2 -> 1 -> 13 -> 43 per 30 min on the morning of the "
"2026-09-05 excursion",
_R["live"]["big"] > 0 and _R["rail"]["big"] == 0
and _R["interim"]["big"] == 0)
# ⚠️ AND WHAT IT DOES NOT BUY, MEASURED, ASSERTED, AND SAID BEFORE ANYBODY CAN
# READ MORE INTO THIS CARD THAN IT DELIVERED. `slew_w` bounds the OUTPUT; the
# integrator accumulates `gain * error` per cycle and is bounded only by
# `integrator_max_w`. At gain 0.6 into a 3.4 kW error the integrator moves
# ~2000 W per tick and reaches a 5000 W rail in under three ticks WHATEVER
# `slew_w` is. So the over-absorption is a GAIN term, and slowing the slew does
# not reduce it - on this model it gets slightly WORSE, because the command
# spends longer away from where it needs to be while the integrator keeps
# winding. admin/goodwe's rig, a different plant model, agrees: over-absorption
# 990 W at slew 1000 and 1086 W at slew 250, against 1010 W at gain 0.6 and
# 863 W at gain 0.3 (tools/slew_sim.py).
#
# `gain` is therefore the next constant to re-derive. SAFETY-39 measured it and
# CHANGED NOTHING: it is a live control-law constant on a running house, and two
# of them moving in one release makes the next measurement uninterpretable.
check("⚠️ THE SLEW DOES NOT OWN THE OVER-ABSORPTION, AND THIS CHECK IS HERE SO "
"THAT NOBODY READS SAFETY-39 AS 'THE OVERSHOOT IS FIXED'. Quartering the "
"slew from 1000 to 250 does not reduce the over-absorption at all",
_R["slower"]["over"] >= _R["live"]["over"])
check("...while the GAIN does own it: 0.6 -> 0.3 -> 0.2 falls monotonically, at "
"the same slew. That is the measurement behind 'gain is the next constant "
"to re-derive', and it is a measurement rather than an opinion",
_R["gain03"]["over"] < _R["rail"]["over"]
and _R["gain02"]["over"] < _R["gain03"]["over"])
print()
if fails:
print(f"{len(fails)} FAILED: {', '.join(fails)}")
+23 -7
View File
@@ -144,9 +144,17 @@ def check(name, cond):
fails.append(name)
def tuning(max_w=LIVE_INSTALL_MAX_W):
"""The shipped defaults from config.yaml, at the live install's max_w."""
return Tuning(gain=0.6, max_w=max_w, slew_w=1000, deadband_w=15,
def tuning(max_w=LIVE_INSTALL_MAX_W, slew_w=0):
"""The shipped defaults from config.yaml, at the live install's max_w.
⚠️ `slew_w` IS 0 - "FOLLOW THE RAIL" - AND IS A PARAMETER (SAFETY-39). 0 is
what config.yaml ships and resolves to `SLEW_RAIL_FRAC * max_w`, so it moves
with `max_w` instead of being a number typed beside it. It has to be
overridable because one case below picks an ABSURDLY SMALL rail on purpose,
and at that rail a rail-following slew is 2 W per cycle - which would make
the slew, rather than the thing under test, the reason nothing fires.
"""
return Tuning(gain=0.6, max_w=max_w, slew_w=slew_w, deadband_w=15,
target_grid_w=-10, step_w=10, saturation_w=500,
saturation_cycles=3)
@@ -327,10 +335,10 @@ check("the capture loaded", len(rows) > 1000)
# covers both kWh registers, so a real `unchanged_s` on this data can only be
# SHORTER than what is reconstructed here - this replay is the pessimistic
# version of the converged case, not a flattering one.
def replay(hold_s, max_w, cycle_floor_s=15.0):
def replay(hold_s, max_w, cycle_floor_s=15.0, slew_w=0):
"""Drive the real control law and the real detector over the capture."""
wd = FreezeWatchdog(FreezeWatchdogConfig(hold_s=hold_s))
t = tuning(max_w)
t = tuning(max_w, slew_w)
target, i_w, sat = 0.0, 0.0, 0
prev_pwr, changed_at = None, rows[0]["t"]
last_cycle = None
@@ -456,7 +464,15 @@ check("...and the shipped law really does park the command there",
# converged capture is silent" is satisfied by a detector that is wired to
# nothing. Drop the hold to 1 s and the rail to nothing, and the SAME replay
# must alarm - so the silence above is the data's doing, not the harness's.
wd_hot, _, _, fired_hot = replay(1.0, 20.0)
# ⚠️ AND THE SLEW IS PINNED FOR THIS CASE ONLY, WHICH IS THE OTHER HALF OF
# MAKING BOTH TERMS REACHABLE (SAFETY-39). The rail here is 20 W, chosen absurdly
# small so the rail term cannot be what holds the alarm off. At the shipped
# `slew_w: 0` the limit follows that rail too - `SLEW_RAIL_FRAC * 20` is 2.2 W
# per cycle - so the command could not reach 19 W inside the capture and the
# replay would go silent for a reason that has nothing to do with the detector.
# That is exactly the vacuous pass this case exists to rule out, arriving
# through the case itself, so the slew is written out here and nowhere else.
wd_hot, _, _, fired_hot = replay(1.0, 20.0, slew_w=20.0)
check("...and the same replay DOES alarm once both terms are made reachable",
fired_hot is not None and wd_hot.episodes > 0)
@@ -699,7 +715,7 @@ def _opts(**over):
o = {"setpoint_entity": "number.sp", "meter_entity": "sensor.grid",
"soc_entity": "sensor.soc", "batt_entity": "sensor.batt",
"meter_source": "off", "max_w": LIVE_INSTALL_MAX_W, "gain": 0.6,
"slew_w": 1000, "deadband_w": SHIPPED_DEADBAND_W,
"slew_w": 0, "deadband_w": SHIPPED_DEADBAND_W,
"target_grid_w": -10, "step_w": 10, "heartbeat_s": 10,
"stale_input_s": STALE_INPUT_S}
o.update(over)
+10 -1
View File
@@ -215,8 +215,17 @@ B_BMS_FLOOR_SIM = 15
A_RATING = 5000.0
# ⚠️ `slew_w` IS 0 HERE, AND IT USED TO BE 1000 - SAFETY-39, AND THE WAY THIS
# FIXTURE FOUND OUT IS THE ARGUMENT FOR THE RULE. This dict pairs `slew_w: 1000`
# with `max_w: 5000` because both were typed when the flat 5000 W install was
# new, and that pair is EXACTLY the configuration measured on the owner's system
# on 2026-09-05 driving the meter from 3.4 kW of export to 2.8 kW of import. The
# fixture was not wrong when it was written and nothing in this file noticed it
# had become so; validate.py rule 10 refused it the day it existed, which is
# what a rule about a relationship is for. 0 means "follow the rail"
# (`control.SLEW_RAIL_FRAC * max_w`) and is what config.yaml ships.
BASE_OPTS = dict(A_ENT, meter_source="off", meter_entity="sensor.grid",
max_w=A_RATING, gain=0.6, slew_w=1000, deadband_w=15,
max_w=A_RATING, gain=0.6, slew_w=0, deadband_w=15,
target_grid_w=0, step_w=10, heartbeat_s=10, stale_input_s=15)
+1 -1
View File
@@ -94,7 +94,7 @@ class _Pub:
BASE = {"setpoint_entity": "number.sp", "meter_entity": "sensor.grid",
"soc_entity": "sensor.soc", "batt_entity": "sensor.batt",
"meter_source": "off", "max_w": 2000, "gain": 0.6, "slew_w": 1000,
"meter_source": "off", "max_w": 2000, "gain": 0.6, "slew_w": 0,
"deadband_w": 15, "target_grid_w": -10, "step_w": 10,
"heartbeat_s": 10, "stale_input_s": 15}
+48 -6
View File
@@ -1007,7 +1007,7 @@ def built(db_path, opts=None, store=None):
c = Controller(dict(
{"setpoint_entity": "number.sp", "meter_source": "ha_signed",
"p1_net_entity": "sensor.net", "meter_phases": 1,
"max_w": LIVE_MAX_W, "gain": 0.6, "slew_w": 1000, "deadband_w": 15,
"max_w": LIVE_MAX_W, "gain": 0.6, "slew_w": 0, "deadband_w": 15,
"target_grid_w": 0, "step_w": 10, "heartbeat_s": 10,
"stale_input_s": 15}, **(opts or {})),
hass, store or _Store(), _Pub(), stop=asyncio.Event(),
@@ -2320,22 +2320,64 @@ print(f" the same day's high-load block "
print(f" {HOT_R['limited']} cycles reporting PEAK GUARD FLOOR-LIMITED, "
f"{HOT_R['limited_discharging']} of them with the loop simultaneously "
f"granted discharge (max {HOT_R['max_granted']:.0f} W)")
check("THE ASYMMETRY, ON REAL DATA. On every cycle where the guard reports "
print(f" {HOT_R['below']} cycles below the {SOC_FLOOR:.0f} % EMS floor, "
f"{HOT_R['below_discharging']} of them discharging; low-water "
f"{HOT_R['min_soc']:.2f} % against a {BMS_FLOOR:.0f} % BMS cut-out")
# ⚠️ THESE TWO CHECKS WERE RE-WRITTEN AT SAFETY-39 AND THE OLD NUMBERS ARE
# PRINTED HERE RATHER THAN DELETED, BECAUSE "AN ASSERTION WAS LOOSENED TO GET A
# BRANCH GREEN" IS THE FIRST THING A REVIEWER SHOULD SUSPECT AND IT HAS TO BE
# ANSWERABLE. They read `limited_discharging == limited` and `min_soc <=
# bms_soc_floor + 0.05`, and both held at `slew_w: 1000`. SAFETY-39 re-derived
# `slew_w` as a ratio to the rail (222 W at this 2000 W cap), and on this same
# two-hour replay:
#
# slew_w 1000 slew_w 0 (the rail)
# limited 49 49
# limited_discharging 49 48
# low-water SoC 9.98 % 10.57 %
# cycles at the BMS cut 190 0
# energy out 1247 Wh 1165 Wh
# below / discharging 406 / 138 406 / 162
#
# So the loop drains this pack ~82 Wh more slowly and no longer reaches the
# cut-out INSIDE THIS WINDOW. The FINDING is untouched and is in fact sharper on
# the measure that carries it - 162 cycles of granted discharge below the floor,
# up from 138. What moved is two numbers that happened to be exact at one
# tuning: one cycle of loop spin-up, and whether a two-hour window is long
# enough to touch a cut-out the loop is now approaching more slowly.
#
# The checks below therefore assert the SUBSTANCE and not the coincidence: that
# the two states occur together on all but at most one cycle, and that the pack
# still ends up past the EMS floor and within a point of its own cut-out with no
# EMS-side bound anywhere in the path. If a future change makes either of these
# fail, that IS a finding - do not widen them again.
check("THE ASYMMETRY, ON REAL DATA. On the cycles where the guard reports "
"FLOOR-LIMITED - 'commanding no forced discharge' on the status page and "
"in the operator's notification - the arbiter is at the same instant "
"granting the LOOP a discharge. A `lo` limit cannot cap a discharge, so "
"the guard's floor and the pack emptying are not alternatives; they "
"happen together",
"happen together. ⚠️ AT MOST ONE CYCLE MAY DIFFER, and that one is the "
"loop's cold start from 0 W - a tolerance of one, not a tolerance",
HOT_R["limited"] > 10
and HOT_R["limited_discharging"] == HOT_R["limited"]
and HOT_R["limited_discharging"] >= HOT_R["limited"] - 1
and HOT_R["max_granted"] > 0.0)
check("...and the loop is granted a discharge on hundreds of cycles with the "
"pack ALREADY below the EMS floor, which is the same asymmetry counted "
"over the whole window rather than over the floor-limited subset - the "
"measure the finding actually rests on, and it does not depend on one "
"cycle of spin-up",
HOT_R["below"] > 100 and HOT_R["below_discharging"] > 100)
check("...which is why SAFETY-24's floor could not be widened into this one, "
"and why the fix is not a bigger number. Recorded in "
"and why the fix is not a bigger number: the pack still ends the window "
"PAST the EMS floor and within one point of its own BMS cut-out, with no "
"EMS-side bound anywhere in the path. Recorded in "
"DECISIONS/SAFETY-25-loop-soc-floor.md, where AC 2 was DECIDED on "
"2026-09-02: Option A, the BMS stays the only backstop, and the "
"loop-side reserve is DEFERRED to ALLOC-01 - so this replay is not a "
"pending exposure but the RECORDED behaviour, and part 10 stays as its "
"tripwire", HOT_R["min_soc"] <= BMS_FLOOR + 0.05)
"tripwire",
HOT_R["min_soc"] < SOC_FLOOR
and HOT_R["min_soc"] <= BMS_FLOOR + 1.0)
# --- 10d. the trap in the obvious fix, checked rather than asserted ---------
# ⚠️ THE MEMO'S CENTRAL ENGINEERING CLAIM, RUN THROUGH THE REAL ARBITER. The
+8
View File
@@ -134,6 +134,14 @@ DERIVED = {
"bms_soc_floor": ("0x0560", "MEASURED"),
"integrator_max_w": ("MEASURED", "Do not raise it"),
"gain": ("MEASURED ON", "do not raise it"),
# SAFETY-39. `slew_w` joins the table because it stopped being an
# operator's convenience and became a DERIVED value the moment it was
# tied to the rating: 0 resolves to about a ninth of `max_w`, from an
# ~18 s measured step response. It is the one entry here whose value is
# a RATIO, so the description has to say what it follows as well as
# where the ratio came from - a citation alone would leave an operator
# reading "0" on the tab with no idea it is not "off".
"slew_w": ("SAFETY-39", "DERIVED", "0 MEANS FOLLOW"),
}
_uncited = []
for key, needles in sorted(DERIVED.items()):
+158 -5
View File
@@ -18,9 +18,10 @@ import asyncio
import sys
from app.maintenance import MAINT_OPTION_DEFAULTS, MaintConfig
from app.control import LOOP_TICK_S, PLANT_SETTLE_S, SLEW_RAIL_FRAC
from app.validate import (
ACTUATOR_WRITE_KEYS, FIRMWARE_INGEST_VETO_S, ConfigRefused,
actuator_writers, refuse, validate_startup_config,
actuator_writers, refuse, site_rail_w, validate_startup_config,
)
fails = []
@@ -457,6 +458,149 @@ check("arbiter: the drain SET is clamped, not contradicted",
check("...and the clamp names itself, which is why it is not refused",
"supervised" in (r.bound_by or "") and "limited by" in r.explain())
# --------------------------------------------------------------------------- #
print("10. a slew rate the plant can actually follow (SAFETY-39)")
# ⚠️ THIS RULE GRADES A RELATIONSHIP, WHICH IS THE POINT OF IT. Every other rule
# in this file compares a configured number against another configured number
# and refuses one ordering. This one refuses a RATIO: `slew_w` may not exceed
# `SLEW_RAIL_FRAC * rail`, so the same `slew_w` is fine at one rating and
# refused at another, and raising the rating moves the bound with it instead of
# leaving the constant behind. That is the failure the ticket is about -
# `slew_w: 1000` was derived at a 1500 W clamp, the live install went to 5000,
# and nothing anywhere said the derivation no longer held.
print(f" SLEW_RAIL_FRAC = LOOP_TICK_S / PLANT_SETTLE_S = "
f"{LOOP_TICK_S:.0f} s / {PLANT_SETTLE_S:.0f} s = {SLEW_RAIL_FRAC:.4f}")
_R5000 = base(max_w=5000, maintenance_charge_w=2000, maintenance_discharge_w=2000)
check("the rail this rule grades is the SITE rail, and at the shipped roster of "
"one it is `max_w` exactly - byte for byte the number the single-inverter "
"shape has always meant",
site_rail_w(_R5000) == 5000.0)
# ⭐ VERIFIED BY BREAKING IT. This is the acceptance criterion stated as a test:
# put the 2026-09-05 pair back and the gate must go red. A rule that could not
# be made to fire on the configuration it was written for is a rule nobody has
# checked.
_broken = validate_startup_config(dict(_R5000, slew_w=1000), -5000, 5000)
print(f" restoring slew_w 1000 at max_w 5000 -> {len(_broken)} problem(s)")
if _broken:
print(f" {_broken[0][:160]}...")
check("⭐ RESTORING THE 2026-09-05 PAIR - slew_w 1000 at max_w 5000 - IS REFUSED. "
"It crosses the whole output range in 10 s against a plant measured at "
"18 s, which is not a fast loop, it is a loop that commands its entire "
"range before it can observe its answer to the first step",
len(_broken) == 1 and why(_broken, "slew_w is 1000 W"))
check("...and the refusal says WHICH RAIL it graded against and HOW LONG the "
"crossing takes, because 'slew_w is too high' sends an operator to lower "
"a number when raising max_w or setting 0 are both correct answers too",
why(_broken, "site rail of 5000 W")
and why(_broken, "crosses its whole output range in 5.0 cycles"))
check("...and it names the plant measurement it is graded against, so the "
"number is traceable to a step response rather than to a preference",
why(_broken, "goodwe/NOTES.md §5.10"))
check("...and it says what to DO, including the setting that cannot go stale",
why(_broken, "Set slew_w to 0") and why(_broken, "556 W"))
# THE BOUNDARY. Equality is the DERIVED VALUE, not a violation - at exactly
# `SLEW_RAIL_FRAC * rail` the loop takes precisely the plant's settling time to
# cross its range, which is the constraint met. Rule 6 permits equality for the
# same shape of reason and rule 5 refuses it for the opposite one; this is
# rule 6's case, and getting it backwards would refuse the value this rule
# exists to recommend.
_bound = SLEW_RAIL_FRAC * 5000.0
check(f"at exactly the derived value ({_bound:.0f} W) the config STARTS - "
"equality is the constraint satisfied, not violated",
validate_startup_config(dict(_R5000, slew_w=int(_bound)), -5000, 5000) == [])
check("...and one watt of slack above it starts too, because a boundary that "
"is not meaningful to one watt must not refuse on one watt - an operator "
"reading 556 off a status page that rounded it is not misconfigured",
validate_startup_config(dict(_R5000, slew_w=556), -5000, 5000) == [])
check("...and well above it does not",
validate_startup_config(dict(_R5000, slew_w=600), -5000, 5000) != [])
# SLOWER IS ALWAYS ACCEPTED, and the live install is the reason it has to be.
check("the interim that is holding on the live system - slew_w 400 against "
"max_w 5000, applied 2026-09-05 12:00 - STARTS. It is 12.5 ticks to cross "
"the rail against the 9 this rule requires, and refusing 'too slow' would "
"refuse the mitigation",
validate_startup_config(dict(_R5000, slew_w=400), -5000, 5000) == [])
check("...and so does the schema floor at the biggest rail, because there is no "
"such thing as too slow here",
validate_startup_config(dict(_R5000, slew_w=50), -5000, 5000) == [])
# ⚠️ 0 IS NOT GRADED AND MUST NOT BE. It means "follow the rail" and satisfies
# this rule by construction at every rail there is; a rule that refused it would
# refuse the fix. Checked at three ratings so that "it passes" cannot be an
# accident of the default one.
# ⚠️ NO SLEW PROBLEM AT ANY RATING, rather than NO PROBLEMS AT ALL. At the
# schema floor of 100 W rules 5 and 5b fire on the shipped sign thresholds,
# which is correct and is not this rule's business - asserting an empty list
# would make this check fail for a reason it is not about, and somebody would
# then "fix" it by moving a sign threshold.
_zero_problems = {m: [p for p in validate_startup_config(
base(max_w=m, slew_w=0,
maintenance_charge_w=min(2000, m),
maintenance_discharge_w=min(2000, m)),
-abs(m), abs(m)) if "slew_w" in p]
for m in (100, 500, 2000, 5000, 15000)}
check("slew_w 0 - FOLLOW THE RAIL - is never refused at any rating, which it "
"must not be, because it is the shipped value and it satisfies this rule "
f"by construction at every rail there is: {_zero_problems}",
not any(_zero_problems.values()))
check("a negative slew_w is refused as nonsense rather than treated as 0 - it "
"is a magnitude, and 0 already has a meaning here",
why(validate_startup_config(dict(_R5000, slew_w=-400), -5000, 5000),
"must not be negative"))
# ⭐ THE ROSTER, WHICH IS THE WHOLE REASON THIS GRADES A SUM. `slew_w` is not a
# per-unit quantity: main.py builds `Tuning(max_w=self.site_max_w)` and
# `compute()` emits the SITE target. So the rail is the roster sum, and adding
# an inverter moves this bound with no operator action and no second derivation.
#
# ⚠️ INVERTER B'S 4600 W IS ITS DATASHEET AND SERIAL, NOT A MEASUREMENT, AND
# INVERTER B IS NOT ON SITE (SPIKE-04, ~2026-09-12; goodwe/NOTES.md §1.1b). It
# is used here because what is graded is the ARITHMETIC OF THE RULE, which does
# not depend on the number being measured - not because 9600 W is a fact about
# this house yet.
def _roster(a=5000, b=4600, **over):
o = base(setpoint_entity="", inverters=[
{"name": "inverter-a", "setpoint_entity": "number.a", "max_w": a,
"bms_soc_floor": 10, "soc_entity": "sensor.sa", "batt_entity": "sensor.ba"},
{"name": "inverter-b", "setpoint_entity": "number.b", "max_w": b,
"bms_soc_floor": 10, "soc_entity": "sensor.sb", "batt_entity": "sensor.bb"}])
o.pop("max_w"); o.pop("soc_entity"); o.pop("batt_entity")
o.update(over)
return o
_site = site_rail_w(_roster())
print(f" roster 5000 + 4600 (B FROM DATASHEET, NOT MEASURED) -> site rail "
f"{_site:.0f} W, bound {SLEW_RAIL_FRAC * _site:.0f} W")
check("the rail is the roster SUM and not the weakest unit, which is what "
"separates this rule from 5, 6 and 8 - those grade one watchdog, one "
"shaping claim and one pack, and this grades the range one SITE COMMAND "
"is a rate across",
_site == 9600.0)
check("⭐ AND THE BOUND MOVES ON ITS OWN WHEN THE ROSTER DOES: the derived value "
"at a 9600 W site is 1067 W with nobody re-deriving anything, which is "
"the property that makes this a fix rather than a re-tune",
abs(SLEW_RAIL_FRAC * _site - 9600.0 / 9.0) < 1e-9)
check("...so the same explicit slew_w that is REFUSED at a 5000 W rail is "
"ACCEPTED at 9600 - the bound is on how long the crossing TAKES, and a "
"bigger rail at the same step size takes longer to cross. ⚠️ This is the "
"direction of the rule stated as a test, because it is not the direction "
"the ticket assumed: a growing rail LOOSENS this bound. What the rule "
"protects against is the constant being left behind when the rail moves; "
"it is not a bound on how much the site may command, and it does not "
"bound the over-absorption, which is a `gain` term SAFETY-39 measured "
"and deliberately did not change",
validate_startup_config(dict(_R5000, slew_w=1000), -5000, 5000) != []
and validate_startup_config(_roster(slew_w=1000)) == [])
check("...and a slew that outruns even the doubled rail is still refused there, "
"so the roster path is not simply un-graded",
why(validate_startup_config(_roster(slew_w=2000)),
"site rail of 9600 W"))
# --------------------------------------------------------------------------- #
print("the SHIPPED defaults must pass the rule they are governed by (AC3)")
# ⚠️ Shipping a default the validator refuses would be worse than the bug it
@@ -470,12 +614,21 @@ import re # noqa: E402
_CFG = os.path.join(os.path.dirname(os.path.abspath(__file__)), "config.yaml")
with open(_CFG, encoding="utf-8") as _fh:
_txt = _fh.read()
# ⚠️ `slew_w` JOINED THIS SET AT SAFETY-39 AND IT IS THE INTERESTING MEMBER.
# The others are refused when they are too big for `max_w`; this one is refused
# when it is too big for `max_w` AS A RATIO, so shipping the wrong number here
# would be shipping the exact defect the card is about with the gate that
# catches it standing right beside it. Reading it out of config.yaml is what
# makes "the shipped value is 0" a fact rather than a claim.
_shipped = {k: float(v) for k, v in re.findall(
r"^ (max_w|maintenance_charge_w|maintenance_discharge_w|sign_disagree_w): "
r"(-?\d+(?:\.\d+)?)\s*$", _txt, re.M)}
check("config.yaml really was read (all four defaults found)",
r"^ (max_w|maintenance_charge_w|maintenance_discharge_w|sign_disagree_w"
r"|slew_w): (-?\d+(?:\.\d+)?)\s*$", _txt, re.M)}
check("config.yaml really was read (all five defaults found)",
set(_shipped) == {"max_w", "maintenance_charge_w",
"maintenance_discharge_w", "sign_disagree_w"})
"maintenance_discharge_w", "sign_disagree_w", "slew_w"})
check(f"...and the shipped slew_w is 0, i.e. FOLLOW THE RAIL - the one value "
f"that cannot be left behind when max_w moves (got {_shipped.get('slew_w')})",
_shipped.get("slew_w") == 0.0)
check(f"the shipped defaults are accepted {_shipped}",
validate_startup_config(base(**_shipped), -5000, 5000) == [])
check("...and the shipped charge rate is at or under the shipped ceiling",
+54 -12
View File
@@ -1393,13 +1393,29 @@ def _sign_site(hass, store=None, **over):
return c
async def _drive(c, n=14, dt=0.2, watch=None):
async def _drive(c, n=14, dt=0.2, watch=None, pre=None):
"""Drive `n` real cycles. `watch` samples AFTER each cycle, `pre` BEFORE it.
⚠️ `pre` EXISTS BECAUSE `watch` ALONE CANNOT SEE WHAT A DETECTOR WAS HANDED,
AND SAFETY-39 IS HOW THAT WAS FOUND. `cycle()` evaluates the sign watchdogs
against THE STANDING COMMAND - the write from the PREVIOUS cycle - and then
issues a new one. So `watch`'s `last_write` is the command AFTER the
detector ran, and pairing it with `c.grid` builds a pair the detector never
saw. While `slew_w` was 1000 the loop was at its rail within two cycles and
consecutive commands were IDENTICAL, so the off-by-one was invisible; at a
rail-following slew the loop ramps and the two numbers differ by one step.
That is a fault in this harness, not in the code it grades - and a check
that compares an operator-facing sentence against the wrong cycle is
precisely the "the data could not reach the failure the text names" defect
MUTATION.md keeps finding. `pre` reads the operands the detector will use.
"""
seen = []
for _ in range(n):
await c.read_inputs()
before = {} if pre is None else pre(c)
await c.cycle()
if watch is not None:
seen.append(watch(c))
seen.append({**before, **watch(c)})
await asyncio.sleep(dt)
return seen
@@ -1812,12 +1828,19 @@ async def _n1_sign():
# `_n1_calls` records what was HANDED to a detector, so grading the banner
# against it would compare the swap against itself - the DEV-02 defect.
# `last_write` and `c.grid` are read off the objects the plant moved.
seen = await _drive(c, n=12, dt=0.2, watch=lambda c: dict(
grid=c.grid,
# ⚠️ `stood` COMES FROM `pre`, i.e. BEFORE `cycle()` RUNS (SAFETY-39). It is
# the STANDING command the sign watchdog is evaluated against; taking it
# after the cycle would pair this cycle's meter with next cycle's command
# and grade the banner against a pair that never existed. See `_drive`.
# `n` is 24 rather than 12 because at the shipped rail-following `slew_w`
# the loop needs nine cycles to reach a 2000 W rail instead of two.
seen = await _drive(c, n=24, dt=0.2, pre=lambda c: dict(
stood=(c.inverters[0].last_write
if c.inverters[0].last_write is not None
else c.inverters[0].target),
tripped=c.inverters[0].sign_wd.tripped))
else c.inverters[0].target)),
watch=lambda c: dict(
grid=c.grid,
tripped=c.inverters[0].sign_wd.tripped))
return c, _n1_calls, seen
@@ -1839,12 +1862,24 @@ check("...the reason sentence still says 'a meter reading', word for word - it "
"is what an operator reads, what the action log carries and what is "
"persisted, so it is graded on the literal",
"against a meter reading" in _inv1.sign_wd.reason)
# The last cycle before the latch, named rather than indexed: afterwards the
# THE CYCLE THE LATCH HAPPENED ON, named rather than indexed: afterwards the
# failsafe stands 0 W and the plant's meter relaxes, so a fixed index reads the
# remedy. Both operands come off the controller, not off the fixture's options.
_pre1s = [x for x in _seen1s if not x["tripped"]]
_mid1s = _pre1s[-1]
print(f" last cycle before the latch: stood {_mid1s['stood']:+.0f} W, "
#
# ⚠️ IT IS THE FIRST *TRIPPED* SAMPLE, AND IT USED TO BE THE LAST UN-TRIPPED ONE
# (SAFETY-39). The detector is evaluated INSIDE `cycle()` against the STANDING
# command - the write from the previous cycle - and against the meter read at
# the top of THIS one, and it latches on the cycle whose pair crosses the hold.
# So the operands the sentence quotes belong to the LATCHING cycle, not to the
# one before it. `stood` is now sampled by `_drive`'s `pre` hook, before
# `cycle()` overwrites it with the failsafe's 0 W, which is what makes that
# cycle readable at all - and it is why the old form had to reach back a cycle.
# The two forms agreed while `slew_w` was 1000 and the loop sat at its rail with
# consecutive commands IDENTICAL; at a rail-following slew the loop ramps and
# they differ by exactly one step, which is how this was found.
_first1s = [x for x in _seen1s if x["tripped"]]
_mid1s = _first1s[0]
print(f" the cycle the latch happened on: stood {_mid1s['stood']:+.0f} W, "
f"meter {_mid1s['grid']:+.0f} W")
print(f" {_inv1.sign_wd.reason!r}")
check("⚠️ ...AND THE ORDERED PAIR ON THE SHIPPING CALL SITE. This is the SAME "
@@ -2529,7 +2564,14 @@ def _s38_frozen_ctrl(hass, ratings, unchanged_s=600.0, gain=0.05):
return c
async def _s38_frozen(ratings, meter_w=_S38_FROZEN_METER_W, n=8):
# ⚠️ `n` IS 20 AND WAS 8 (SAFETY-39). The comment on `_s38_frozen_ctrl` says
# gain 0.05 is there "to buy a ramp" so that the SAME run carries both a
# below-the-rail and an at-the-rail answer. At the shipped rail-following
# `slew_w` the ramp is now the SLEW - 55 W a cycle against this 500 W site,
# where gain 0.05 alone gave 125 - so eight cycles no longer reach the rail and
# the run carried only the counterfactual. The fixture needs the cycles, not a
# different tuning: the point is a run that crosses the rail part way through.
async def _s38_frozen(ratings, meter_w=_S38_FROZEN_METER_W, n=20):
hass = _S38Plant()
c = _s38_frozen_ctrl(hass, ratings)
_s38_seed_quarter(c, meter_w)
@@ -2604,7 +2646,7 @@ async def _s38_one():
hass = _S38Plant()
c = _s38_frozen_ctrl(hass, _S38_ONE)
_s38_seed_quarter(c, _S38_FROZEN_METER_W)
for _ in range(8):
for _ in range(20): # SAFETY-39: the slew is the ramp now - see _s38_frozen
_s38_feed(c, _S38_FROZEN_METER_W)
await c.read_inputs()
await c.cycle()
+339
View File
@@ -0,0 +1,339 @@
#!/usr/bin/env python3
"""SAFETY-39's evidence, on admin/goodwe's OWN plant model.
python3 tools/slew_sim.py --repro # ⭐ the 2026-09-05 excursion, replayed
python3 tools/slew_sim.py --slew # the derivation: slew against the rail
python3 tools/slew_sim.py --gain # what the slew does NOT own
python3 tools/slew_sim.py --roster # N=1 -> N=2, and the rail that moved
python3 tools/slew_sim.py --all
WHY THIS IS A SCRIPT AND NOT A `test_*.py`
==========================================
Byte for byte tools/alloc_sim.py's reason, and it has not changed: this needs
admin/goodwe checked out beside this repository for `plantsim.Plant`, 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 - pass SILENTLY having checked nothing.
So the rig evidence lives here and is quoted in the pull request and in
DECISIONS/SAFETY-39-slew-against-the-rail.md, and test_control.py's SAFETY-39
section grades the same properties in CI against a plant it models itself and
says it models. The two plants are INDEPENDENT - a first-order lag written in
test_control.py versus `plantsim.Plant`'s ramp-plus-lag with an efficiency and
a SoC integrator - and they agree on every sign and rank below, which is worth
more than either alone.
WHAT IS REAL IN HERE
====================
* the control law - `compute()` and `Tuning`, imported out of THIS checkout,
never transcribed.
* the wire - every command goes out through `frame_check.setpoint_atomic()`,
the firmware's own encoder, and back in through `plantsim.parse`/`decode`,
because `Inverter.command()` is what drives the modelled unit.
* the plant - `plantsim.Plant`, the model the rig uses.
MODELLED, and therefore not evidence about the thing modelled:
* the meter. `grid = load - pv - sum(battery)` with no poll delay and no
noise, sampled once per tick. The real P1 is a poll with its own age.
* the tick. 2.0 s, which is what the live install was MEASURED running on
2026-09-05; it is a parameter here (`--tick`) and not a constant, because
the whole of this card is that the derivation depends on the regime.
⚠️ WHAT THIS CANNOT SHOW, SAID BEFORE THE RESULTS RATHER THAN AFTER THEM
=======================================================================
THE -5154 W BATTERY EXCURSION IS NOT REPRODUCIBLE HERE, AND NOT BECAUSE THE
TUNING IS WRONG. `plantsim.Plant.limit()` clamps the plant at `p_max`, so the
modelled battery cannot exceed its rating by one watt at any tuning, on any
step, ever. Neither can test_control.py's model. An acceptance criterion of
"battery power no longer exceeds max_w in simulation" would therefore be
UNFALSIFIABLE - it passes on the broken configuration too - so no criterion in
this card is written on it, and the ticket's own AC to that effect is the one
that had to be rewritten rather than met.
What IS reproducible, and is what everything below measures:
* the setpoint stepping a full `slew_w` per tick, over and over (the live
symptom that escalated 2 -> 1 -> 13 -> 43 large steps per 30 min);
* the loop OVER-ABSORBING - taking more than the site needed - and driving
the meter from EXPORT into IMPORT, i.e. manufacturing the error it chases.
⚠️ INVERTER B DOES NOT EXIST. `plantsim.INVERTER_B` is inverter A's numbers
COPIED, `measured=False`. Every N=2 row below is therefore a result about TWO
COPIES OF A on a 10000 W rail, NOT about the ~9600 W site that B's datasheet
and serial imply (goodwe/NOTES.md §1.1b; B is a GW5048D-ES rated 4600 W, and
that figure may itself be DC). Each such row prints the caveat with it.
"""
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 and alloc_sim.py take,
then the sibling checkouts that actually occur. A missing sibling is not a
finding about the control law 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 / "plantsim.py").exists():
return c
return None
def load(sim):
sys.path[:0] = [str(sim), str(sim.parent / "master")]
os.environ.setdefault("GOODWE_ADDON_REPO", str(ADDON))
sys.path[:0] = [str(ADDON / "goodwe_controller")]
import plantsim # noqa: E402
from app import control # noqa: E402
return plantsim, control
# ---------------------------------------------------------------------------
# one experiment
def step_run(plantsim, control, *, gain, slew_w, rail_w, n=1, tick_s=2.0,
export_w=3385.0, load_w=350.0, phase=5, cycles=300, dt=0.05,
lag_s=None):
"""One export step onto a converged loop, through the real wire.
`rail_w` is the SITE rail - what `main.py` hands `compute()` as `max_w`
(`Controller.site_max_w`, the roster sum). Each of the `n` modelled units
is rated `rail_w / n` and is commanded its even share, which is the
arrangement ARCH-01's split-invariance says any valid split is equivalent
to at the meter.
"""
over = {} if lag_s is None else dict(lag_s=lag_s)
spec = dict(plantsim.INVERTER_A, rating_w=rail_w / n, **over)
invs = [plantsim.Inverter.from_spec(name, spec) for name in "AB"[:n]]
site = plantsim.Site(invs, load=load_w, pv=0.0)
tuning = control.Tuning(gain=gain, max_w=rail_w, slew_w=slew_w,
target_grid_w=-10.0)
prev, i_w, sat = 0.0, None, 0
worst_import, peak, biggest, last = -1e9, 0.0, 0.0, None
for c in range(cycles):
if c == phase:
site.pv = export_w + load_w
site.grid = site.load - site.pv - site.battery
# ⚠️ ONE UNIT'S POWER, NOT THE SITE'S SUM, at n > 1. The shipped add-on
# binds a single `inverter_power` sensor, so a two-inverter install has
# a loop that sees unit A only. sitesim.run_site() makes the same choice
# and says at length why feeding the sum would be a KINDER rig than the
# deployment.
actual = invs[0].plant.actual
d = control.compute(prev, site.grid, actual, tuning, sat, i_w)
if c >= phase and last is not None:
biggest = max(biggest, abs(d.target_w - last))
last = d.target_w
prev, i_w, sat = d.target_w, d.i_w, d.sat_count
for inv in invs:
inv.command(d.target_w / n)
site.settle(tick_s, dt=dt)
if c >= phase:
worst_import = max(worst_import, site.grid)
peak = max(peak, abs(site.battery))
return dict(imp=worst_import, over=peak - export_w, step=biggest)
def family(plantsim, control, *, exports=None, phases=(5, 6, 7), **kw):
"""The worst case over a family of step sizes and phases.
⚠️ A FAMILY, NOT ONE STEP, AND THAT IS ITSELF A FINDING. A single run of
this loop is not evidence: the 15 W deadband, the 10 W quantisation and the
phase of the step against the tick move the answer by hundreds of watts,
NON-MONOTONICALLY, so two adjacent slews rank either way depending on which
step you happen to run. The first version of this derivation was a single
step and reported gain 0.3 as WORSE than gain 0.6, which the family shows is
backwards. Everything printed below is a worst case over the family, which
is how admin/goodwe grades the same kind of quantity (config.yaml's "1890
closed-loop runs", "924 runs").
"""
exports = exports or range(1000, 4300, 200)
worst = dict(imp=-1e9, over=-1e9, step=0.0, big=0, runs=0)
for export_w in exports:
for phase in phases:
r = step_run(plantsim, control, export_w=float(export_w),
phase=phase, **kw)
worst["runs"] += 1
worst["imp"] = max(worst["imp"], r["imp"])
worst["over"] = max(worst["over"], r["over"])
worst["step"] = max(worst["step"], r["step"])
worst["big"] += r["step"] >= 900.0
return worst
def row(label, w):
print(f" {label:<44} step {w['step']:6.0f} W "
f"{w['big']:3}/{w['runs']} runs >= 900 W "
f"over-absorbed {w['over']:6.0f} W meter to {w['imp']:+7.0f} W")
# ---------------------------------------------------------------------------
def repro(ps, ct, tick_s):
print("⭐ THE 2026-09-05 EXCURSION, REPLAYED - gain 0.6, max_w 5000, "
f"slew_w 1000, {tick_s:.0f} s tick")
print(" Live, 11:43:55-11:45:55: grid -3385 W, setpoint 380 -> 5000 in five")
print(" ticks, battery -5154 W, grid +2831 W. One 3385 W export step here:\n")
print(f" {'t':>5} {'grid in':>9} {'setpoint':>9} {'battery':>9} {'grid out':>9} reason")
spec = dict(ps.INVERTER_A)
inv = ps.Inverter.from_spec("A", spec)
site = ps.Site([inv], load=350.0, pv=0.0)
t = ct.Tuning(gain=0.6, max_w=5000.0, slew_w=1000.0, target_grid_w=-10.0)
prev, i_w, sat = 0.0, None, 0
for c in range(34):
if c == 5:
site.pv = 3385.0 + 350.0
site.grid = site.load - site.pv - site.battery
g = site.grid
d = ct.compute(prev, g, inv.plant.actual, t, sat, i_w)
prev, i_w, sat = d.target_w, d.i_w, d.sat_count
inv.command(d.target_w)
site.settle(tick_s, dt=0.05)
print(f" {c * tick_s:5.0f} {g:9.0f} {d.target_w:9.0f} "
f"{site.battery:9.0f} {site.grid:9.0f} {d.reason}")
print("\n ⚠️ THE BATTERY NEVER PASSES 5000 W HERE AND CANNOT: plantsim.Plant")
print(" clamps at its rating. The -5154 W figure is NOT reproducible in")
print(" this model at any tuning, so nothing in this card is graded on it.")
print(" What IS reproduced is the setpoint stepping 1000 W a tick to the")
print(" rail, and the meter crossing from export into import.")
def slew_table(ps, ct, tick_s, rail):
frac = ct.SLEW_RAIL_FRAC
print(f"THE DERIVATION - gain 0.6, site rail {rail:.0f} W, {tick_s:.0f} s tick, "
f"51 export steps 1.0-4.2 kW\n")
print(f" the constraint: the loop must not cross its whole output range "
f"faster than the")
print(f" plant settles. {rail:.0f} W / ({ct.PLANT_SETTLE_S:.0f} s / "
f"{tick_s:.0f} s per tick) = {frac * rail:.0f} W per tick.\n")
for slew in (1000, 800, 700, 600, int(frac * rail), 500, 400, 300, 250):
w = family(ps, ct, gain=0.6, slew_w=float(slew), rail_w=rail,
tick_s=tick_s)
tag = " <- the derived value" if slew == int(frac * rail) else (
" <- the 2026-09-05 live pair" if slew == 1000 else (
" <- the live interim" if slew == 400 else ""))
row(f"slew_w {slew}{tag}", w)
print("\n READ IT THIS WAY. The >= 900 W step - the live symptom, which")
print(" escalated 2 -> 1 -> 13 -> 43 per 30 min that morning - is gone from")
print(" every run below 900 W of slew, and that is what the slew owns.")
print(" The OVER-ABSORPTION does not move, and at the slowest slews it is")
print(" slightly WORSE. The rig cannot pick the derived value out of that")
print(" column, and it is not asked to: the CONSTRAINT picks it, and this")
print(" table is what says what the constraint does and does not buy.")
def gain_table(ps, ct, tick_s, rail):
frac = ct.SLEW_RAIL_FRAC
print(f"WHAT THE SLEW DOES NOT OWN - slew_w at the derived "
f"{frac * rail:.0f} W, gain swept\n")
for gain in (0.6, 0.5, 0.4, 0.3, 0.2, 0.1):
w = family(ps, ct, gain=gain, slew_w=frac * rail, rail_w=rail,
tick_s=tick_s)
row(f"gain {gain}" + (" <- shipped" if gain == 0.6 else ""), w)
print("\n `slew_w` bounds the OUTPUT. The integrator accumulates")
print(" `gain * error` per cycle and is bounded only by `integrator_max_w`,")
print(" so at gain 0.6 into a 3.4 kW error it moves ~2000 W per tick and")
print(f" reaches the {rail:.0f} W rail in under three ticks WHATEVER the slew is.")
print(" The over-absorption is therefore a GAIN term. `gain: 0.6` is the")
print(" next constant to re-derive; SAFETY-39 measured it and changed")
print(" nothing, because two control-law constants moving in one release on")
print(" a running house makes the next measurement uninterpretable.")
def roster_table(ps, ct, tick_s):
frac = ct.SLEW_RAIL_FRAC
print("N=1 -> N=2: THE RAIL IS WHAT MOVED\n")
print(" ⚠️ INVERTER B DOES NOT EXIST (SPIKE-04, ~2026-09-12) AND")
print(" plantsim.INVERTER_B IS INVERTER A COPIED, measured=False. The")
print(" N=2 rows are therefore about TWO COPIES OF A on a 10000 W rail.")
print(" The site B actually implies is ~9600 W (5000 + 4600), and 4600 is")
print(" B's DATASHEET and SERIAL, not a measurement, and may be DC -")
print(" goodwe/NOTES.md §1.1b. Read the rows as architecture, not as a")
print(" prediction about this house.\n")
for n, rail in ((1, 5000.0), (2, 10000.0)):
for slew in (1000.0, frac * rail):
w = family(ps, ct, gain=0.6, slew_w=slew, rail_w=rail, n=n,
tick_s=tick_s)
lab = (f"n={n} rail {rail:.0f} slew {slew:.0f}"
+ (" [B = A COPIED]" if n == 2 else ""))
row(lab, w)
print(f"\n The derived value at the REAL 9600 W site is "
f"{frac * 9600:.0f} W per tick, and")
print(" validate.py reads it off `sum(unit_caps(opts))` - the same number")
print(" `Controller.site_max_w` builds - so adding inverter B moves the")
print(" bound with no operator action and no second derivation.")
print("\n ⚠️ AND THE DIRECTION IS NOT THE ONE THE TICKET ASSUMED. A rail that")
print(" GROWS loosens this bound: slew_w 1000 crosses a 9600 W rail in")
print(" 19.2 s and PASSES, while at 5000 W the same 1000 is the")
print(" configuration that was measured failing. That is what the")
print(" constraint says and it is correct - the bound is on how long the")
print(" crossing TAKES, and a bigger rail at the same step size takes")
print(" longer to cross.")
print("\n ⚠️ AND THE >= 900 W STEP COUNT STAYS AT 48/51 AT THE DERIVED VALUE")
print(" ON THE N=2 ROW, WHICH IS NOT A FAILURE - IT IS THE THRESHOLD GOING")
print(" STALE, on the same day and in the same way as the constant. 900 W")
print(" was a meaningful step against a 5000 W rail; against 10000 W the")
print(" derived step IS 1111 W, and a check written on the absolute 900")
print(" would report the correct tuning as broken. Anything grading this")
print(" symptom at N>=2 has to grade it as a FRACTION of the rail too.")
print("\n WHAT DOES NOT GET WORSE HERE, STATED BECAUSE IT WAS EXPECTED TO.")
print(" Over the SAME family of 1.0-4.2 kW export steps, doubling the rail")
print(" does not worsen the over-absorption (958 -> 810 W): the extra rail")
print(" is headroom these disturbances never ask for. That is a statement")
print(" about this family, not about the site - a bigger site sees bigger")
print(" steps, and the over-absorption is a `gain` term either way, which")
print(" the enforced ratio does not bound and this card did not change.")
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--repro", action="store_true")
ap.add_argument("--slew", action="store_true")
ap.add_argument("--gain", action="store_true")
ap.add_argument("--roster", action="store_true")
ap.add_argument("--all", action="store_true")
ap.add_argument("--tick", type=float, default=None,
help="seconds per control cycle (default: control.LOOP_TICK_S)")
ap.add_argument("--rail", type=float, default=5000.0)
a = ap.parse_args()
if not any((a.repro, a.slew, a.gain, a.roster, a.all)):
a.all = True
sim = find_sim()
if sim is None:
sys.exit("slew_sim: admin/goodwe's sim/ is not beside this checkout, so "
"plantsim.Plant is unavailable. Clone it as a sibling or set "
"$GOODWE_SIM. This is a missing repository, NOT a result about "
"the control law - do not report it as one.")
ps, ct = load(sim)
tick = a.tick if a.tick is not None else ct.LOOP_TICK_S
print(f"slew_sim: plant from {sim}")
print(f" control law from {ADDON / 'goodwe_controller' / 'app'}")
print(f" {ps.Inverter.from_spec('A', ps.INVERTER_A).describe()}")
print(f" tick {tick:.1f} s, SLEW_RAIL_FRAC {ct.SLEW_RAIL_FRAC:.4f} "
f"= {ct.LOOP_TICK_S:.0f} s / {ct.PLANT_SETTLE_S:.0f} s\n")
if a.repro or a.all:
repro(ps, ct, tick); print()
if a.slew or a.all:
slew_table(ps, ct, tick, a.rail); print()
if a.gain or a.all:
gain_table(ps, ct, tick, a.rail); print()
if a.roster or a.all:
roster_table(ps, ct, tick)
if __name__ == "__main__":
main()
+1 -1
View File
@@ -242,7 +242,7 @@ configuration:
description: "How much of the remaining error the loop corrects each cycle. MEASURED ON REAL HARDWARE and already at the limit - do not raise it. Lower is slower and safer."
slew_w:
name: "Advanced · Largest change per cycle (W)"
description: "How far the setpoint may move in one control cycle. It bounds how fast the site can turn around, and several safety windows were measured across the whole range this accepts."
description: "How far the setpoint may move in one control cycle. ⚠️ 0 MEANS FOLLOW THE INVERTER RATING and is the recommended setting: the limit becomes about a ninth of the rating, so the loop takes the plant's own MEASURED settling time to cross its whole output range and the number cannot be left behind when the rating changes. DERIVED (SAFETY-39) from an ~18 s measured step response against a 2 s meter tick. A fixed number is accepted and is never silently reduced, but a number faster than the rating allows is refused at startup - at 1000 W against a 5000 W rating this loop drove the meter from 3.4 kW of export to 2.8 kW of import on 2026-09-05. Lower is always accepted."
deadband_w:
name: "Advanced · Deadband (W)"
description: "Errors smaller than this are ignored. ⚠️ The deadband is a one-way ratchet: any resting point inside it holds forever, and the meter's import register counts every positive watt with no export to cancel it - which is exactly why the resting point below is slightly negative."
+1 -1
View File
@@ -222,7 +222,7 @@ configuration:
description: "Welk deel van de resterende afwijking de regeling per cyclus wegregelt. GEMETEN OP ECHTE HARDWARE en al aan de bovengrens - niet verhogen. Lager is trager en veiliger."
slew_w:
name: "Geavanceerd · Grootste verandering per cyclus (W)"
description: "Hoeveel het setpoint in één regelcyclus mag verspringen. Dit begrenst hoe snel de installatie kan omkeren; verschillende veiligheidsvensters zijn over het volledige toegelaten bereik gemeten."
description: "Hoeveel het setpoint in één regelcyclus mag verspringen. ⚠️ 0 BETEKENT VOLG HET OMVORMERVERMOGEN en is de aanbevolen instelling: de grens wordt ongeveer een negende van dat vermogen, zodat de regeling er de GEMETEN insteltijd van de installatie over doet om haar volledige bereik te doorlopen en het getal niet achterblijft wanneer het vermogen verandert. AFGELEID (SAFETY-39) uit een gemeten stapresponsie van ~18 s bij een meterinterval van 2 s. Een vast getal wordt aanvaard en wordt nooit stilzwijgend verlaagd, maar een getal sneller dan het vermogen toelaat wordt bij het starten geweigerd - bij 1000 W tegen 5000 W dreef deze regeling de meter op 2026-09-05 van 3,4 kW injectie naar 2,8 kW afname. Lager wordt altijd aanvaard."
deadband_w:
name: "Geavanceerd · Dode zone (W)"
description: "Afwijkingen kleiner dan deze waarde worden genegeerd. ⚠️ De dode zone werkt maar één kant op: elk rustpunt erbinnen blijft eeuwig staan, en het afnameregister van de meter telt elke positieve watt mee zonder injectie die dat compenseert - en precies daarom staat het rustpunt hieronder licht negatief."