Compare commits
33
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0c7e786ed5 | ||
|
|
ab6fbe2f9e | ||
|
|
1c59cfeaf5 | ||
|
|
acbdf41248 | ||
|
|
950472662e | ||
|
|
6ea84a46f6 | ||
|
|
48cd5f31ca | ||
|
|
20f9f4969d | ||
|
|
b68f288fef | ||
|
|
e8fb596b99 | ||
|
|
d0b053b150 | ||
|
|
f630ed949b | ||
|
|
d5b1ef19b3 | ||
|
|
b7267eb51a | ||
|
|
e498dd4c1c | ||
|
|
3cb9d3b7d9 | ||
|
|
99321892cb | ||
|
|
182102eeaf | ||
|
|
1e4bad8aa7 | ||
|
|
6ea79f1043 | ||
|
|
29fa39eda7 | ||
|
|
d64790b3e2 | ||
|
|
83911ed637 | ||
|
|
7b4877d56d | ||
|
|
358fbb0172 | ||
|
|
504e8daac3 | ||
|
|
f6ecd5ff03 | ||
|
|
04292c4a08 | ||
|
|
86c43eba24 | ||
|
|
d57122ec74 | ||
|
|
4601682815 | ||
|
|
b7272169b1 | ||
|
|
2b8b8cb97f |
+13
-1
@@ -18,5 +18,17 @@
|
||||
# python3, no aiohttp, no pip (`No module named pip`; checked on the box, not
|
||||
# assumed). An image is not gold-plating here, it is the only option that does
|
||||
# not mutate a shared long-lived runner.
|
||||
# ⚠️ `git` IS A TEST DEPENDENCY, NOT A CONVENIENCE (CI-02). test_ci_gate.py
|
||||
# grades the gate's own checkout by EXTRACTING the shell out of
|
||||
# .gitea/workflows/checks.yml and RUNNING it - against two throwaway local
|
||||
# repositories it builds itself, one whose pull request merges and one whose
|
||||
# does not. Reading those commands as a string would be the thing this
|
||||
# repository keeps finding: a check that never observed its subject. Running
|
||||
# them needs git in the image the checks run in.
|
||||
#
|
||||
# It costs one apk package and no network at test time: the fixtures are local
|
||||
# paths, and the token substitution in the workflow's `git remote add` is a
|
||||
# no-op on a path with no `://` in it, which is exactly why the test can use
|
||||
# the shipped line verbatim instead of a paraphrase of it.
|
||||
FROM alpine:3
|
||||
RUN apk add --no-cache python3 py3-aiohttp py3-paho-mqtt
|
||||
RUN apk add --no-cache python3 py3-aiohttp py3-paho-mqtt git
|
||||
|
||||
+179
-14
@@ -18,7 +18,9 @@
|
||||
# so it QUEUES behind a rig campaign - a delayed verdict, never a destroyed one.
|
||||
#
|
||||
# NO JS ACTIONS: the runner image has no node, so `actions/checkout` cannot run.
|
||||
# Checkout is seven lines of git below.
|
||||
# Checkout is plain git below - and since CI-02 it is a checkout of the MERGE of
|
||||
# the pull request into its base, not of the branch tip. See the long note on
|
||||
# that step; a green from this workflow is a claim about content that can land.
|
||||
name: checks
|
||||
|
||||
on:
|
||||
@@ -26,15 +28,53 @@ on:
|
||||
branches: [release/1.0, master]
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
# ⚠️ PER PULL REQUEST, NOT A BARE NAME. A shared group holds one running and
|
||||
# one pending run, so a bare name lets a second PR supersede a first PR's run
|
||||
# before any runner has picked it up - which is exactly what happened to the
|
||||
# other repo's run 521 (four jobs, `started_at` at the Unix epoch,
|
||||
# `runner_id: 0`, concluded `cancelled`, and the PR merged anyway). Do not
|
||||
# replace this with a constant.
|
||||
group: addon-checks-${{ github.event.pull_request.number || github.ref }}
|
||||
cancel-in-progress: true
|
||||
# ⚠️ NO `concurrency:` BLOCK, AND ITS ABSENCE IS AS LOAD-BEARING AS THE MISSING
|
||||
# `paths:` FILTER ABOVE. CI-01 put one here - `group: addon-checks-<pr number>`,
|
||||
# `cancel-in-progress: true` - to stop a second pull request superseding a
|
||||
# first one's run. It did stop that. It also did this, twice, on PR #14:
|
||||
#
|
||||
# run 531 created 17:08:19 `pending / Waiting to run`
|
||||
# cancelled 17:10:44 <- the exact second run 532 was created
|
||||
# run 533 created 17:45:11 `pending / Waiting to run`
|
||||
# cancelled 18:11:22 <- the exact second run 534 was created
|
||||
#
|
||||
# Both cancelled runs have `started_at` at the Unix epoch: they never executed.
|
||||
# A cancelled run posts `failure` on the required context, described
|
||||
# `Canceled after 0s`. Branch protection compares STATE, not description, so
|
||||
# "nothing ran" and "your tests are broken" arrive at the gate as the same red,
|
||||
# and the correct operator response to each is the opposite of the other.
|
||||
#
|
||||
# CI-02 MEASURED THE THREE CANDIDATE SETTINGS ON A THROWAWAY PR (#29) RATHER
|
||||
# THAN READING THE DOCS, because the docs and this Gitea disagree about which
|
||||
# knob does it. In each trial one run was made to hold the single slot and two
|
||||
# further pushes followed:
|
||||
#
|
||||
# trial 1, NO concurrency block - runs 561 and 562 both sat queued together
|
||||
# and both executed. Nothing was cancelled.
|
||||
# trial 2, group kept, cancel-in-progress: FALSE
|
||||
# - run 564 sat `pending / Blocked by required
|
||||
# conditions` and was cancelled at 0s the
|
||||
# second run 565 was created.
|
||||
#
|
||||
# So `cancel-in-progress` IS NOT THE KNOB. A shared group cancels a run that has
|
||||
# not started no matter what that flag says - GitHub documents this ("any
|
||||
# previously pending run in the group will be cancelled") and Gitea 1.27
|
||||
# implements it. The only configuration that leaves a queued run alive is having
|
||||
# no group at all, which is what is written here.
|
||||
#
|
||||
# ⚠️ DO NOT REPLACE THIS WITH A SHA-KEYED GROUP as a compromise. It looks
|
||||
# tempting - two runs on different commits could never share a group, so nothing
|
||||
# would be cancelled - but the only cancellations it still permits are the
|
||||
# same-sha ones, and those are precisely the dangerous half: a red for a run
|
||||
# that never started, landing on a commit that IS still the head. It
|
||||
# concentrates the failure instead of removing it.
|
||||
#
|
||||
# WHAT THIS COSTS, stated honestly: the runner is `capacity: 1` and shared with
|
||||
# the other repo's rig, so a developer who pushes four times in a minute now
|
||||
# occupies it four times instead of once. That is CI-01's own trade written the
|
||||
# other way round - it accepted "a delayed verdict, never a destroyed one" for
|
||||
# the rig, and this accepts the same for pushes. A destroyed verdict here is
|
||||
# worse than a slow one, because it is indistinguishable from a real failure.
|
||||
|
||||
jobs:
|
||||
unit:
|
||||
@@ -58,19 +98,132 @@ jobs:
|
||||
# exist, so the test dies on `IndexError: 1` before its first assertion.
|
||||
# Measured during CI-01; the flat layout was tried first and did exactly
|
||||
# that. $WS/goodwe-addon/goodwe_controller gives parents[1] == $WS.
|
||||
- name: checkout into a path the host shares (git; no node for actions/checkout)
|
||||
#
|
||||
# ⚠️ WHAT THIS CHECKS OUT IS THE MERGE, NOT THE BRANCH, AND THAT IS THE
|
||||
# WHOLE OF CI-02. What was here before was one line:
|
||||
#
|
||||
# git fetch -q --depth 1 origin "$GITHUB_REF" \
|
||||
# || git fetch -q --depth 1 origin "$GITHUB_SHA"
|
||||
#
|
||||
# CI-02 measured what those two names actually are on this Gitea, on a
|
||||
# deliberately conflicted throwaway PR (#29, runs 558 and 559), by asking
|
||||
# one question per STEP - the Actions log endpoints 404 here, so a step's
|
||||
# own conclusion is the only channel out of a job. The answers:
|
||||
#
|
||||
# GITHUB_REF == refs/pull/<n>/head (step P01 passed)
|
||||
# GITHUB_REF != refs/pull/<n>/merge (step P02 failed)
|
||||
# GITHUB_SHA == the pull request head sha (step P03 passed)
|
||||
# fetching GITHUB_REF succeeds (step P04 passed)
|
||||
# ...and lands on the bare head (step P05 passed)
|
||||
# refs/pull/<n>/merge does not exist (step P06 failed)
|
||||
#
|
||||
# ⚠️ SO THE FALLBACK NEVER FIRED, AND THE DEFECT IS WORSE THAN THE ONE
|
||||
# REPORTED. The ticket says a conflicted PR loses its merge ref and the
|
||||
# `||` quietly grades the bare head instead. It does not: this Gitea has
|
||||
# no merge refs at all - `git ls-remote origin 'refs/pull/*'` advertises
|
||||
# only `/head`, for open and closed pull requests alike - so the FIRST
|
||||
# half always succeeds, and both halves name the same commit anyway
|
||||
# (GITHUB_REF resolves to GITHUB_SHA). The gate has never once graded
|
||||
# merged content, on any pull request in this repository's history. Green
|
||||
# has meant "this branch passed on its own", which on a base that has
|
||||
# moved - and `block_on_outdated_branch` is off here, so it usually has -
|
||||
# is not the content that lands. PR #14 reporting success while
|
||||
# `mergeable: false` was not the fallback misfiring; it was the gate
|
||||
# working exactly as written.
|
||||
#
|
||||
# A fallback that cannot fire cannot be "kept for the case it was for", so
|
||||
# it is gone from this path and kept, ANNOUNCED, on the one path that has
|
||||
# no pull request to merge (workflow_dispatch, below).
|
||||
#
|
||||
# ⚠️ NOT `--depth 1` ANY MORE. A merge needs the merge base, and a shallow
|
||||
# pair does not have one. Measured before changing it: a full fetch of
|
||||
# this repository is 6.8 MB and 1.1 s against this server, over 95
|
||||
# commits. The depth flag was buying nothing worth a wrong verdict.
|
||||
#
|
||||
# ⚠️ THE WORKFLOW AND THE CONTENT NOW COME FROM DIFFERENT TREES. Gitea
|
||||
# picks the workflow file from refs/pull/<n>/head, so THIS file is always
|
||||
# the branch's; the tree graded below - including .gitea/ci/Dockerfile -
|
||||
# is the merge. That is the right way round (a pull request must not be
|
||||
# able to grade itself with a gate the base has not seen) but it means a
|
||||
# change to this file is tested by the branch it is on, which is how you
|
||||
# are reading this.
|
||||
- name: check out the base branch and the pull request head (git; no node for actions/checkout)
|
||||
env:
|
||||
URL: ${{ github.server_url }}/${{ github.repository }}.git
|
||||
TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
PRNUM: ${{ github.event.pull_request.number }}
|
||||
BASEREF: ${{ github.base_ref }}
|
||||
run: |
|
||||
set -eu
|
||||
rm -rf "$WS" && mkdir -p "$WS/goodwe-addon" && cd "$WS/goodwe-addon"
|
||||
git init -q .
|
||||
git remote add origin "$(echo "$URL" | sed "s#://#://x-access-token:${TOKEN}@#")"
|
||||
git fetch -q --depth 1 origin "$GITHUB_REF" || git fetch -q --depth 1 origin "$GITHUB_SHA"
|
||||
git checkout -qf FETCH_HEAD
|
||||
if [ -n "$PRNUM" ]; then
|
||||
# Two fetches, not one, so that a failure to reach either ref fails
|
||||
# HERE with the ref in the message, rather than inside the merge
|
||||
# step where it would read as a conflict. `github.base_ref` being
|
||||
# populated at all was checked on the probe PR too (step Q01).
|
||||
git fetch -q origin "+refs/heads/$BASEREF:refs/remotes/origin/base"
|
||||
git fetch -q origin "+refs/pull/$PRNUM/head:refs/remotes/origin/pr"
|
||||
git checkout -qf refs/remotes/origin/base
|
||||
echo "base $BASEREF $(git rev-parse refs/remotes/origin/base)"
|
||||
echo "head refs/pull/$PRNUM/head $(git rev-parse refs/remotes/origin/pr)"
|
||||
else
|
||||
# NO PULL REQUEST (workflow_dispatch). There is nothing to merge
|
||||
# into, so this path grades a bare ref and SAYS SO - which is all
|
||||
# the old `||` ever needed to do. It is kept here because a branch
|
||||
# can be deleted or renamed between the dispatch and the fetch, and
|
||||
# unlike the pull_request path that is a case nobody has ruled out.
|
||||
if git fetch -q origin "$GITHUB_REF"; then
|
||||
echo "GRADED: the bare ref $GITHUB_REF - NOT merged content (no pull request in this event)."
|
||||
else
|
||||
git fetch -q origin "$GITHUB_SHA"
|
||||
echo "GRADED: the bare commit $GITHUB_SHA - NOT merged content, and NOT $GITHUB_REF either, which would not fetch."
|
||||
fi
|
||||
git checkout -qf FETCH_HEAD
|
||||
fi
|
||||
echo "checked out $(git log --oneline -1)"
|
||||
|
||||
# ⚠️ THIS STEP IS THE ONE THAT MAKES A GREEN MEAN SOMETHING. It exists as
|
||||
# its OWN step rather than as three lines of the checkout because the
|
||||
# Actions log endpoints 404 on this Gitea and
|
||||
# /api/v1/repos/.../actions/runs/<id>/jobs - which carries a per-step
|
||||
# conclusion - is the only machine-readable account of what a run did. A
|
||||
# reader who sees this step red knows the pull request does not apply and
|
||||
# that NO TEST RAN; a reader who sees the next two red knows the tests ran
|
||||
# and spoke. Collapse them back together and that distinction is gone
|
||||
# again, which is the shape of defect this whole ticket is about.
|
||||
#
|
||||
# The refusal is a FAILURE rather than a skip on purpose. "Reports
|
||||
# nothing" would leave the required context pending forever, which this
|
||||
# file's own header explains is unmergeable-forever; and a conflicted pull
|
||||
# request cannot be merged by Gitea anyway, so the red blocks nothing that
|
||||
# was not already blocked. What it does is stop a green being posted about
|
||||
# content that cannot land.
|
||||
- name: grade the merge, not the branch - refuse a pull request that does not apply
|
||||
env:
|
||||
PRNUM: ${{ github.event.pull_request.number }}
|
||||
BASEREF: ${{ github.base_ref }}
|
||||
run: |
|
||||
set -eu
|
||||
cd "$WS/goodwe-addon"
|
||||
if [ -z "$PRNUM" ]; then
|
||||
echo "no pull request in this event - nothing to merge, and the previous step said what it graded."
|
||||
exit 0
|
||||
fi
|
||||
if git -c user.email=checks@localhost -c user.name=checks \
|
||||
merge --no-edit refs/remotes/origin/pr; then
|
||||
echo "GRADED: refs/pull/$PRNUM/head merged into $BASEREF"
|
||||
echo " result $(git rev-parse HEAD)"
|
||||
echo " tree $(git rev-parse 'HEAD^{tree}')"
|
||||
else
|
||||
git merge --abort 2>/dev/null || true
|
||||
echo "REFUSED: refs/pull/$PRNUM/head does not merge into $BASEREF."
|
||||
echo " NOTHING HAS BEEN TESTED. This is not a test failure - no test ran."
|
||||
echo " Rebase or merge $BASEREF into the branch and push again."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: build the test image (shipped deps, from apk - see .gitea/ci/Dockerfile)
|
||||
run: |
|
||||
set -eu
|
||||
@@ -101,10 +254,22 @@ jobs:
|
||||
# hwsim section was skipped - so "test_freeze.py: PASS" below is a weaker
|
||||
# claim than it looks. That belongs to whoever owns test_freeze.py next;
|
||||
# naming it here is the least this gate can do about it.
|
||||
# ⚠️ PYTHONDONTWRITEBYTECODE=1 IS BELT AND BRACES, NOT A FIX FOR A LIVE
|
||||
# HOLE. TEST-15 measured this runner's actual exposure and found none: the
|
||||
# checkout below is bind mounted `:ro`, so the interpreter physically
|
||||
# cannot write a __pycache__ into the tree it is grading - it fails
|
||||
# SILENTLY, no error and exit status 0 - and every job `rm -rf`s $WS and
|
||||
# clones afresh, so nothing survives from a previous job on this shared
|
||||
# runner either. The variable is here because the `:ro` is the load-bearing
|
||||
# part and it is one character wide: delete it while debugging a write and
|
||||
# the gate quietly starts caching bytecode across a rebuild again. Note
|
||||
# what it does NOT do, per TEST-15 part 2 - it stops bytecode being
|
||||
# WRITTEN, never a stale one being READ. It is not a substitute for the
|
||||
# purge in goodwe_controller/tools/mutation_run.sh.
|
||||
- name: the add-on's own tests
|
||||
run: |
|
||||
set -eu
|
||||
docker run --rm -v "$WS:/w:ro" goodwe-addon-checks:1 sh -eu -c '
|
||||
docker run --rm -e PYTHONDONTWRITEBYTECODE=1 -v "$WS:/w:ro" goodwe-addon-checks:1 sh -eu -c '
|
||||
cd /w/goodwe-addon/goodwe_controller
|
||||
set -- test_*.py
|
||||
if [ "$1" = "test_*.py" ]; then
|
||||
|
||||
+13
@@ -57,6 +57,14 @@ python3 test_control.py && python3 test_maintenance.py && python3 test_arbiter.p
|
||||
&& python3 test_loop.py
|
||||
```
|
||||
|
||||
⚠️ **Mutating a module to prove a check bites? Read `goodwe_controller/
|
||||
MUTATION.md` first, and run `goodwe_controller/tools/mutation_run.sh`.** A
|
||||
same-size edit reverted inside one second changes neither the file size nor the
|
||||
whole-second mtime, so CPython reuses the bytecode it already compiled and the
|
||||
suite grades code that is not there - once already, reported as a survivor and
|
||||
disproved by disassembly (TEST-15). `python3 -B` does **not** save you: it stops
|
||||
bytecode being written, not a stale `.pyc` being read. The purge is the fix.
|
||||
|
||||
`test_watchdog.py` covers SAFETY-02's logic, its arming gate (derived from the
|
||||
real arbiter, not passed in), its trip path, and the fact that the latch survives
|
||||
an add-on restart. Its headline validation is not here at all: `sim/replay_sign.py`
|
||||
@@ -165,6 +173,11 @@ Each of these was found the expensive way. They are in the code comments too.
|
||||
`timestamp` attribute.
|
||||
- **Alpine ships paho-mqtt 1.x**, which has no `CallbackAPIVersion`, and musl has
|
||||
no aiohttp wheel — install from apk, not pip.
|
||||
- **A mutation run can grade code that is not there.** CPython validates a
|
||||
`.pyc` on (source size, source mtime in whole seconds), so a same-size edit
|
||||
reverted within one second is invisible to it and the old bytecode runs. It
|
||||
manufactures *survivors*, never reds. Purge `__pycache__` -
|
||||
`tools/mutation_run.sh` does - and see `goodwe_controller/MUTATION.md`.
|
||||
- **The inverter holds its last command forever.** It has no meter-timeout. Every
|
||||
failsafe here exists because of that one fact, and anything in doubt commands
|
||||
**0 W** rather than holding.
|
||||
|
||||
@@ -19,6 +19,8 @@ goodwe_controller/ the add-on
|
||||
test_control.py runnable checks — no framework needed
|
||||
test_maintenance.py runnable checks — walks a full cycle in fake time
|
||||
DOCS.md the add-on's documentation tab
|
||||
MUTATION.md how to run a mutation so the result means something
|
||||
tools/mutation_run.sh the mutation harness - purges bytecode, then grades
|
||||
firmware/goodwe-master.yaml ESPHome config for the T-CAN485
|
||||
estop/rs485_log.py optional RS485 e-stop / bus witness
|
||||
docs/GoodWe-RS485-Field-Guide.pdf the guide techs carry (10pp, A4)
|
||||
@@ -82,7 +84,12 @@ python3 test_control.py
|
||||
python3 test_maintenance.py
|
||||
```
|
||||
|
||||
Both must pass before shipping any change. They are not unit-test theatre —
|
||||
Both must pass before shipping any change. To prove a check *bites* - the way
|
||||
almost every claim in this repository was established - mutate the module and
|
||||
run `tools/mutation_run.sh`, which clears `__pycache__` first. It is not
|
||||
optional: a same-size edit reverted inside one second leaves CPython reusing the
|
||||
old bytecode, and the run grades code that is not there. `goodwe_controller/MUTATION.md`
|
||||
has the mechanism, the measurement, and what the flags do not do. They are not unit-test theatre —
|
||||
each assertion corresponds to a rule whose absence produced an observed failure
|
||||
on real hardware, and the comments in `control.py` say which.
|
||||
|
||||
|
||||
@@ -2,6 +2,712 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
**SAFETY-25's open question is ANSWERED: the BMS cut-out is the DELIBERATE and
|
||||
only backstop for demand-driven discharge, and a loop-side reserve floor is
|
||||
DEFERRED to `ALLOC-01` rather than rejected (SAFETY-25).** Decided by the
|
||||
product owner on 2026-09-02. **Option A is the shipped behaviour, so `app/`
|
||||
changed only where a comment claimed the question was still open** - no
|
||||
setpoint, no claim, no option, no default moved, and the 17-suite run is green
|
||||
on the same numbers as before.
|
||||
|
||||
* **Why deferring is the safe direction, and it is a property of the shape
|
||||
rather than a preference.** Option B's proof - `bms_soc_floor <
|
||||
loop_soc_floor <= peak_soc_floor`, verified through the real arbiter in
|
||||
`test_peakguard.py` part 10d - has an unstated premise: the reserve predicate
|
||||
and `discharge_permitted()` read the **same** state of charge. With two packs
|
||||
they read different numbers. The reserve binds on the emptier pack and files
|
||||
`hi = 0` while the peak guard, reading the other pack or an average, files
|
||||
`lo = excess > 0`; `lo > hi` is arbiter clause 3 and the answer is **0 W, the
|
||||
battery parked in the billed quarter** - the failure the memo itself marks
|
||||
fatal. **No config-ordering validator can catch it**, because it is a runtime
|
||||
divergence between two readings and not a config ordering, so CFG-01's shape
|
||||
of check would pass on the exact tree that parks the battery. Option A's cost
|
||||
is energy; Option B's cost built too early is a parked battery in the one
|
||||
quarter of the month that sets the bill.
|
||||
* **The revisit trigger is recorded explicitly, and it is `ALLOC-01`.** Under
|
||||
`ARCH-01`'s host-side allocator the two claims stop sharing a list: the loop
|
||||
floor becomes a **per-inverter `hi` consumed as an interval at stage A**,
|
||||
while the peak floor stays a **site `lo` at stage B**. Different claim lists,
|
||||
different stages, **structurally unable to cross** - which is a stronger
|
||||
argument than the ordering rule, because it makes the crossing unreachable
|
||||
rather than harmless. That is the shape in which Option B becomes safe to
|
||||
build, and the memo says so at the point a future reader will look.
|
||||
* **What will have to be RE-EARNED at N=2 is stated plainly rather than left
|
||||
for someone to discover.** `SAFETY-27` now names **five floors across two
|
||||
packs**, so "the SoC" stops being a scalar the config can bound. And
|
||||
`test_peakguard.py` **part 10f - the pin that made SAFETY-25 mergeable** -
|
||||
**cannot express two packs**: its dynamic half is a scalar 0-100 % SoC sweep
|
||||
against a single-series capture, and a two-pack exposure lives in the
|
||||
*difference* between two readings, which that sweep visits at no resolution.
|
||||
Its static half (the AST scan pinning the eight claim sources) still bites at
|
||||
N=2; the dynamic half goes silent. Merging a two-pack reserve on 10f's
|
||||
current green would be merging on a check that cannot see the failure.
|
||||
* **The options analysis is kept intact on purpose.** A memo that recorded the
|
||||
verdict and deleted the reasoning is the failure mode this `DECISIONS/`
|
||||
directory exists to prevent, so §1-§7 stand exactly as written - including
|
||||
§5's *"(recommended)"* on Option B and §6's recommendation - with the new §0
|
||||
saying what was decided and §6 marked as answered. Part 10e's check moved
|
||||
with the memo: it used to pin the honest `Status: OPEN` line and now pins
|
||||
that the memo names the option, the date and the trigger **and still carries
|
||||
both options and the recommendation**.
|
||||
* **The tripwire stays, and "deferred" is why it stays.** Part 10 and mutation
|
||||
13 are unchanged in substance: a ninth claim source in `Controller.cycle()`
|
||||
still takes 10f red on the line it is written. Deferred, not rejected, is
|
||||
precisely the state in which someone builds Option B by accident.
|
||||
|
||||
Operator-facing surfaces follow the decision and nothing else changed on them:
|
||||
`DOCS.md`'s SAFETY-25 section now says a choice was made and points at the
|
||||
trigger, and `app/freeze.py`'s finding and `app/peakguard.py`'s point 2 say
|
||||
"decided, on purpose" where they said "open".
|
||||
|
||||
**`PeakStore.record_block()` now has its POLICY ARGUMENT graded, and the
|
||||
SAFETY-20 import check now looks at all three ways of writing an import
|
||||
(TEST-13).** Two survivors from TARIFF-01's review, both closed in
|
||||
`test_tariff.py` only - `app/` is untouched and no shipped behaviour changed.
|
||||
|
||||
* **The plumbing of the per-phase reduction was unobservable.** Mutating
|
||||
`record_block()`'s `billed_w(block, policy)` to `billed_w(block, POLICY_NET)`
|
||||
left all 17 suites green (+4 B; recorded by TARIFF-01's reviewer, re-run
|
||||
through the purge harness for TEST-15, and re-run again here). The cause is
|
||||
the third instance of the same shape as WITNESS-02's span normalisation and
|
||||
TARIFF-01's own DST window: **a stimulus evaluated where the quantity it
|
||||
grades is degenerate.** `billed_w()` short-circuits to `block.offtake_avg_w`
|
||||
whenever `per_phase_offtake_avg_w` is absent, and every block that reached a
|
||||
store anywhere in the suite was single-phase or built with
|
||||
`per_phase_offtake_avg_w=None` - so NET, SUM and MAX collapsed onto one
|
||||
number and the argument could not be seen. Section 7 already owns an
|
||||
UNBALANCED fixture, `(3000, 500, -200) W`, whose three reductions are 3300 /
|
||||
3500 / 3000 W; that block is now round-tripped **through the store** under
|
||||
each policy and read back from both tables. NET is the smallest of the three
|
||||
here, so a store that quietly billed NET while asked for MAX would
|
||||
under-record the month's peak - maximum headroom for SAFETY-07, the same
|
||||
under-guarding direction as the `getattr(..., 0.0)` default SAFETY-07 already
|
||||
removed from `project()`.
|
||||
* **The import half of the SAFETY-20 grader made a claim it did not check.** It
|
||||
collected `ImportFrom.module` only, which is blind to two of Python's three
|
||||
import spellings: `from . import arbiter as _ab` is an `ImportFrom` whose
|
||||
`.module` is **None** (the module name is in `.names`), and `import
|
||||
app.arbiter` is an `ast.Import` node the walk never visited. Both were added
|
||||
to `app/tariff.py` and the shipped suite stayed **green**. Never a live
|
||||
exposure - the `_names` half still catches any USE of either alias - but the
|
||||
printed sentence "it imports nothing from arbiter, clamp or control" was
|
||||
false for two forms out of three, which is worse than claiming less. The
|
||||
grader now walks `Import` as well, joins `from . import X` onto its base, and
|
||||
matches per dotted SEGMENT so `app.arbiter` cannot hide behind a package
|
||||
prefix while `clamps` / `arbiters` / `controller` are not falsely flagged.
|
||||
Both graders are also now shown non-vacuous against `main.py`, which really
|
||||
does import all three modules.
|
||||
* **Two items on the card were already closed and are struck, not
|
||||
re-implemented.** `PeakReading.is_observed` is `self.state == OBSERVED`
|
||||
(`app/tariff.py:266`), already false for `NO_RECORD`; and `project()`'s
|
||||
`held` read is `max(averager.held_net_w, 0.0)` with **no** `getattr` default,
|
||||
fixed by SAFETY-07 in 616b62d with a comment naming TEST-13 item 4. Restoring
|
||||
a default there would re-open a money guard. Removing `clear_partial()` also
|
||||
stays green and that remains a **PASS**: the `quarter_start` PRIMARY KEY plus
|
||||
`ON CONFLICT ... WHERE excluded > existing` makes a replay a structural
|
||||
no-op, which is TARIFF-01's claim rather than a hole in it.
|
||||
|
||||
Verified through `tools/mutation_run.sh` (purge, `python3 -B`, tree re-read from
|
||||
disk, mutated line grepped off disk, byte delta recorded): 7 mutations, all red
|
||||
on the named checks, plus green baselines before and after and a control run
|
||||
showing the shipped suite passing every one of them.
|
||||
|
||||
**The two `arbitrage()` rungs SAFETY-26's AC4 sweep found pinned from ONE SIDE
|
||||
ONLY are now pinned from both - and, the actual finding, are pinned so they stop
|
||||
MASKING EACH OTHER (TEST-16).** `spread == 0.0` weakened to `<= 0.001` survived
|
||||
the whole suite at +2 B, and `len(firm) < 2` weakened to `< 1` survived at
|
||||
+0 B - the delta MUTATION.md names as the risky one. Neither was individually
|
||||
live, and that was the problem: a single firm hour *also* has a spread of zero,
|
||||
so each rung's failure was absorbed by the other and both could be weakened
|
||||
together with nothing reporting it. That is invisible to single-mutation
|
||||
testing, which is how the pair survived four rounds of review on TARIFF-03 and
|
||||
FCST-03. `test_static_tariff.py` gains section 9, which grades WHICH RUNG
|
||||
answered each stimulus rather than only whether it refused - the masked case
|
||||
refuses correctly while reporting the false sentence "the tariff is flat" about
|
||||
a series that is not flat, so a check asserting only "refused" passes on a
|
||||
broken tree. The flat rung is swept with small-but-REAL spreads down to
|
||||
0.000001 EUR/kWh at `min_spread_eur_kwh=0.0` (a value `arbitrage()`'s docstring
|
||||
documents and its validator accepts on purpose), the firm-pair rung is probed
|
||||
with a ONE-FIRM-HOUR series and graded on §8.3's sentence coming back rather
|
||||
than the flat rung's, and a five-row table denies the masking on both sides.
|
||||
Verified through TEST-15's `tools/mutation_run.sh` unchanged - recursive
|
||||
`__pycache__` purge, `python3 -B`, tree re-copied from disk between rounds,
|
||||
mutated line grepped off disk, byte delta printed: 7 mutations plus a green
|
||||
baseline, 4 of them at +0 B, ALL RED, including both rungs weakened AT ONCE
|
||||
(5 checks red). **No shipped behaviour changed - both rungs were correct all
|
||||
along**; `app/` is untouched. `MUTATION.md` gains a section on masking as a
|
||||
second way a survivor lies, and `test_arbitrage.py`'s SAFETY-26 AC4 note is
|
||||
marked closed rather than left reading as an open finding.
|
||||
|
||||
**`check_output_clamp()` could be moved above `write_setpoint()` in `cycle()`
|
||||
with test_clamp.py, test_freeze.py and test_loop.py all staying GREEN — the
|
||||
guard's write-path evidence, `self.clamp_last`, had nothing watching it.**
|
||||
Measured before the fix, on the move itself: all three suites green. The guard
|
||||
has two evidence sources and only one of them was covered. `self.loop_clamped`
|
||||
is set from the `Decision` well above the write, so it survives the move — and
|
||||
on the §10.3 runaway replay it is the source of every engagement the alarm
|
||||
reports (0 write-path engagements against 2 loop-side ones), which is precisely
|
||||
what made the move nearly invisible. `self.clamp_last` is assigned by
|
||||
`write_setpoint()` and by nothing else (`main.py`), is `None` until it has run,
|
||||
and is what `engaged_write` reads; moved above the write, that consumer goes
|
||||
quietly false and a DEVICE-bound clamp — `max_w` above the inverter's own
|
||||
rating, SAFETY-20's install — stops being reported by anything.
|
||||
test_clamp.py gains part 6, and it grades the CONSEQUENCE rather than the
|
||||
position: a spy subclassed from the shipped `ClampWatchdog` records what
|
||||
`self.clamp_last` held each time the guard consulted it, over a slew-limited
|
||||
ramp where every cycle's command is a different number, and asserts the
|
||||
evidence is always the write of THAT cycle. Hooking `clamp_wd.note()` rather
|
||||
than the guard's name is what keeps a rename legitimate; the same assertions
|
||||
are re-run through a controller whose guard is renamed and whose write lives in
|
||||
a helper, and were verified against `main.py` itself — renaming the method
|
||||
throughout and moving both calls into a new `_emit_and_guard()` helper keeps
|
||||
part 6 green, while swapping the two calls turns it red on a line that names
|
||||
`clamp_last`. AC 3 needed a stimulus of its own: through the real `cycle()` the
|
||||
write-path half can never engage, because the arbiter files the device range
|
||||
and `max_w` as P_SAFETY LIMIT claims and `resolution.target_w` is already
|
||||
inside both bounds before `write_setpoint()` re-applies them — that duplication
|
||||
is deliberate defence in depth, and part 6 now measures the 0 engagements
|
||||
rather than leaving it as a claim in a comment. So the write path is driven
|
||||
directly at `max_w` 5000 against a ±2500 W device: the wire carries 2500 W,
|
||||
every loop-side flag stays clean, and the alarm fires on `clamp_last` alone —
|
||||
with the two calls swapped, the same stimulus clamps the same value and the
|
||||
alarm is silent. `main.py` gains one comment sentence pointing at the check,
|
||||
mirroring the one SAFETY-18's block already carries for test_freeze.py part 5.
|
||||
|
||||
**`max_w` and the `LIVE_MAX_W` literal beside it were unpinned in test_freeze.py
|
||||
and test_tariff.py, the same gap TEST-06 closed one key over for
|
||||
`meter_freeze_s` (TEST-10).** Measured before the fix: `max_w: 2000 -> 4500`
|
||||
in `config.yaml` left every check in both files GREEN, and `LIVE_MAX_W = 5000.0`
|
||||
was a bare literal that silently disagreed with the shipped default (2000) with
|
||||
nothing saying so — for contrast, `deadband_w: 15 -> 5` already went RED 2 + 1,
|
||||
so the pinning technique itself was known to work, just not applied here.
|
||||
Fixed three ways. First, `test_freeze.py` gained a check comparing `Tuning()`'s
|
||||
code default (`control.py`, 2000.0) against `SHIPPED_MAX_W`, read from
|
||||
`config.yaml` by extending the file's existing `_cfg_default()` regex reader
|
||||
rather than reimplementing test_arbitrage.py's `_shipped`. Second, the literal
|
||||
itself is renamed `LIVE_INSTALL_MAX_W` in both files, with a comment stating
|
||||
plainly that 5000 is the live install's own override and not config.yaml's
|
||||
shipped `max_w` — the defect was the silent literal, not the number. Third,
|
||||
`test_freeze.py` now states `PINNED_KEYS = ("meter_freeze_s", "deadband_w",
|
||||
"max_w")` in one place as the complete set of config keys this suite pins,
|
||||
deliberately excluding `maintenance_*` (CFG-03 gave those a separate source of
|
||||
truth in `app/maintenance.py`). Verified by breaking what the new check
|
||||
watches: `max_w: 2000 -> 4500` in `config.yaml` now fails exactly
|
||||
`"the code default and the shipped default agree on max_w too"` and nothing
|
||||
else, and reverting returns the file to all-green.
|
||||
|
||||
**Maintenance option defaults lived in three places that had already disagreed,
|
||||
and MAINT-04's tripwire was holding them apart rather than closing them
|
||||
(CFG-03).** `config.yaml` shipped `maintenance_charge_w: 2000`, `main.py` carried
|
||||
two `opts.get("maintenance_charge_w", 2500)` fallbacks, and `MaintConfig`'s
|
||||
dataclass carried a third `2500.0`. An options dict with the key **absent** was
|
||||
therefore accepted by `validate.py`'s rule 6 — which read 2000 — and then built
|
||||
by `main.py` at 2500, against a 2000 W ceiling. Demonstrated through the shipped
|
||||
code:
|
||||
|
||||
options dict with maintenance_charge_w ABSENT, max_w=2000
|
||||
validate_startup_config -> [] (ACCEPTED, no problems)
|
||||
MaintConfig().charge_w -> 2500.0
|
||||
arbiter.resolve() -> 0.0 W, contradiction=True
|
||||
|
||||
That is the bug rule 6 exists to refuse, **passing rule 6**. Unreachable through
|
||||
the Supervisor, which always supplies every key from `config.yaml`; fully
|
||||
reachable from `sim/inject.py` and from the test suite, which is where anyone
|
||||
debugging maintenance is.
|
||||
|
||||
**`maintenance_discharge_w` had the identical divergence** (`config.yaml` 2000,
|
||||
`MaintConfig` 2500) and the card named only the charge side. Closing one key and
|
||||
leaving its twin would have reproduced the defect one line down, so both are
|
||||
closed.
|
||||
|
||||
**The single source of truth is `config.yaml`'s `options:` block** — the file the
|
||||
Supervisor reads and the operator edits. There is now exactly **one** in-code
|
||||
copy, `maintenance.MAINT_OPTION_DEFAULTS`, which is TARIFF-02's
|
||||
`PRICE_OPTION_DEFAULTS` and SAFETY-24's `PEAK_OPTION_DEFAULTS` pattern applied to
|
||||
the family that named the card. A mirror rather than a runtime read because the
|
||||
`Dockerfile` copies `app/` and `run.sh` into the image and **not** `config.yaml`:
|
||||
the running add-on cannot open the file it is configured by. `test_maintenance.py`
|
||||
pins every entry by **reading** the shipped file, so a drift is a CI failure
|
||||
rather than a comment. Every other declaration site now derives from it or has
|
||||
ceased to exist:
|
||||
|
||||
- `MaintConfig`'s eight dataclass defaults are indexed out of the mirror — no
|
||||
numeric literal survives in the class that held the third opinion;
|
||||
- `MaintConfig.from_options()` is the **only** place in the add-on that reads a
|
||||
`maintenance_*` option. `main.py`'s eight inline `opts.get(key, <literal>)`
|
||||
calls are gone;
|
||||
- `main.py`'s second fallback site (the cheap-window charge floor) reads
|
||||
`self.maint.cfg.charge_w` instead of re-opening the options dict, so the rate
|
||||
the shaping asks for and the rate the state machine drains at cannot be two
|
||||
numbers from one install;
|
||||
- `validate.py`'s rule 6 and its `maintenance_discharge_w` warning take their
|
||||
fallbacks from the mirror.
|
||||
|
||||
**Where the RANGE lives is now stated and checked, so the next person does not
|
||||
add a fifth site.** `maintenance_charge_w: int(500,5000)` in `config.yaml`'s
|
||||
`schema:` block is a fourth declaration of a different kind — a bound, not a
|
||||
default. Bounds live in the schema block **only**: the Supervisor enforces them
|
||||
and reads only that file. `test_maintenance.py` asserts that every mirrored key
|
||||
has a schema entry (or the Supervisor silently drops the option and the add-on
|
||||
runs on the mirror instead of the operator's value) and that every shipped
|
||||
default lies **inside** its own range. What the schema grammar cannot express is
|
||||
a relation *between* keys — `maintenance_charge_w` against `max_w` — which is
|
||||
why rule 6 is written in Python and does not belong in the mirror either.
|
||||
|
||||
**MAINT-04's tripwire in `test_validate.py` is DELETED, not left passing**, as it
|
||||
and `validate.py`'s ⚠️ block both instructed each other to do. Its passing
|
||||
condition *was* the bug. In its place, the same four consumers exercised the same
|
||||
way and now agreeing: the validator accepts a dict with every `maintenance_*` key
|
||||
missing, a **real `Controller`** built from that dict holds 2000 W, `MaintConfig()`
|
||||
answers 2000 W with no dict at all, and the real arbiter emits `-2000 W, limited
|
||||
by supervised(max_w)` instead of `0 W, contradiction=True`.
|
||||
|
||||
**Checked by breaking it, five ways, each observed red before being reverted:**
|
||||
move `config.yaml` alone → the mirror pin fails; move `config.yaml` **and** the
|
||||
mirror to 1500 → every consumer follows together (`MaintConfig()` 1500 W, the
|
||||
`Controller` 1500 W, the arbiter `-1500 W, limited by maintenance(cheap-window
|
||||
charge)`) and both suites go green again; retype `charge_w: float = 2500.0` into
|
||||
the dataclass → red; restore `opts.get("maintenance_charge_w", 2500)` in
|
||||
`main.py` → red; delete a key from `config.yaml`'s options block → red.
|
||||
|
||||
Stale prose that asserted the closed divergence as current is corrected in
|
||||
`app/watchdog.py`, `test_watchdog.py` and `test_peakguard.py`.
|
||||
|
||||
**`peak_soc_floor` reads like a pack-wide reserve and is not one, and on a
|
||||
sustained-load evening the grid-following loop discharges straight past it to
|
||||
the BMS cut-out (SAFETY-25).** The gap has been written down four times without
|
||||
being filed — SAFETY-18's finding (`freeze.py`), SAFETY-24's module note, its PR
|
||||
body, and its honestly-uncaught 13th mutation — and never once measured. It is
|
||||
measured now, on the committed 2026-08-20 capture, driving the shipped
|
||||
`control.compute()`, `peakguard.decide()`, `peakguard.claim()` and the real
|
||||
`arbiter.resolve()`:
|
||||
|
||||
19:00-22:00 UTC, 830 W mean, minimum 701 W, not one watt of export
|
||||
reference pack (300 Ah x 51.2 V x DoD 90) started at 21 %, one point
|
||||
above peak_soc_floor
|
||||
|
||||
ends at 10.0 % - the bms_soc_floor cut-out
|
||||
1525 Wh delivered by the LOOP over 587 cycles
|
||||
549 cycles below peak_soc_floor, 343 of them still discharging
|
||||
0 cycles on which the peak guard filed any floor at all
|
||||
|
||||
**And it is a behaviour, not a config value.** The same evening ends at
|
||||
`9.9715 %` at `peak_soc_floor` = 5, 11, 20 **and** 60 — the shipped value and
|
||||
both ends of the schema range — identical to four decimal places. The option an
|
||||
operator would reach for cannot move the number by any amount. On the same day's
|
||||
high-load block the two states coexist: 49 cycles reporting `PEAK GUARD
|
||||
FLOOR-LIMITED` and, on **all 49**, the arbiter simultaneously granting the loop
|
||||
up to 2000 W of discharge.
|
||||
|
||||
**Why SAFETY-24 could not close it.** The peak guard files a `lo` limit — a
|
||||
*lower* bound. That asymmetry is what makes it provably unable to lower a target,
|
||||
cap a discharge or contradict the arbiter, and it is therefore equally unable to
|
||||
stop a discharge the loop itself wants. A floor on the guard cannot become a
|
||||
floor on the pack by being raised.
|
||||
|
||||
**What changed is the honesty, on four operator-facing surfaces**, because that
|
||||
half is required whichever way the open question is answered and it is the actual
|
||||
misstatement on the live system today:
|
||||
|
||||
- `config.yaml` says next to the option that it **bounds the peak guard only** and
|
||||
is **not a pack-wide reserve**, with the replayed evening and the sweep;
|
||||
- `DOCS.md` says it in the options table and in a new section carrying the
|
||||
figures above;
|
||||
- the **status-page row** for a floor-limited guard carries the scope sentence —
|
||||
it is the one line a human reads at the moment the guard stops, and read alone
|
||||
it implies a reserve the replay shows does not exist;
|
||||
- the **persistent notification** says what has stopped (the guard buying a lower
|
||||
bill) and what has not (the pack being spent).
|
||||
|
||||
`peakguard.py` and `freeze.py` carry the measurement beside the findings they
|
||||
already recorded.
|
||||
|
||||
**The product decision is NOT taken here.** Whether the loop gets a reserve floor
|
||||
of its own moves real energy on this house and belongs to the owner.
|
||||
`DECISIONS/SAFETY-25-loop-soc-floor.md` records the options, what each costs and
|
||||
protects, weighed against MAINT-01 and against the fact that this would be the
|
||||
**fifth** SoC key (OPT-04's `arbitrage_soc_floor` fired SAFETY-24's "revisit if a
|
||||
third floor appears" trigger unremarked), and a recommendation. It also records a
|
||||
trap found while writing it and now checked through the real arbiter: the obvious
|
||||
shape — a `hi` limit on the loop — crosses the peak guard's `lo` and resolves to a
|
||||
**CONTRADICTION at 0 W**, the battery parked in the quarter that sets the bill,
|
||||
unless `bms_soc_floor < loop_soc_floor <= peak_soc_floor` is enforced at startup.
|
||||
|
||||
**`test_peakguard.py` part 10 is a tripwire, not a guarantee, and part 10f is
|
||||
what makes it one.** The replay half records the defect; on its own it could not
|
||||
see the defect being FIXED, because `replay_loop()` hand-builds main.py's claim
|
||||
list and is therefore blind to any claim main.py adds — which is exactly where a
|
||||
loop-side floor would be built. PR #31's reviewer proved that by building the
|
||||
memo's own Option B in `main.py` and watching the whole suite stay green. **10f
|
||||
pins the claim-source set:** every `claims.append(...)` in `Controller.cycle()`
|
||||
is read off its AST and must be one of eight named sources, and real
|
||||
`Controller.cycle()`s — spied at main.py's own `resolve`, swept over the whole
|
||||
0–100 % state-of-charge range in both the idle and the floor-limited state — must
|
||||
hand the arbiter exactly `{device, supervised, loop}` and
|
||||
`{device, supervised, loop, peak}`. A ninth source, at any state of charge, in
|
||||
any configuration, takes part 10 red on the line it is written. A floor built
|
||||
inside `control.compute()` or the guard instead moves 10a–10c's replayed numbers,
|
||||
which the replay drives directly. So the exposure cannot change size under a
|
||||
green suite.
|
||||
|
||||
**Nine mutations, re-run against the fixed tree**, each against a freshly copied
|
||||
tree with no `__pycache__` present at all, mounted `:ro` — the same structural
|
||||
immunity `MUTATION.md` records for CI. Six are the AC 3 and behaviour mutations
|
||||
already on this ticket's record (the status row's scope sentence, the
|
||||
notification's, `config.yaml`'s, the memo deleted, the loop's gain zeroed, the
|
||||
guard's claim given a `hi`); two are the reviewer's, and are the ones that
|
||||
motivated 10f — the memo's own Option B at its recommended default, **now three
|
||||
checks red where it was fully green**, and an absurd always-binding 95 % reserve,
|
||||
**six red**; one is new, against the banner short form below. All nine are red,
|
||||
no survivors, and no byte delta is `+0 B`.
|
||||
|
||||
**The gate has never once graded the content a pull request would land, and a
|
||||
run that never started reported as a test failure (CI-02).** Both halves were
|
||||
measured on a deliberately conflicted throwaway pull request rather than read
|
||||
off the workflow, because the Actions log endpoints 404 on this Gitea and a
|
||||
step's own conclusion is the only channel out of a job.
|
||||
|
||||
**Case 1, and the ticket's mechanism was wrong in a way that made it worse.**
|
||||
CI-02 was filed saying a conflicted pull request loses its merge ref, so that
|
||||
`git fetch $GITHUB_REF || git fetch $GITHUB_SHA` falls through and grades the
|
||||
bare branch head. The symptom was real — PR #14 reported `checks / unit ->
|
||||
success` while `mergeable: false` — but the mechanism is not. On this server
|
||||
`GITHUB_REF` **is** `refs/pull/<n>/head`, `GITHUB_SHA` is the same commit, and
|
||||
`git ls-remote origin 'refs/pull/*'` advertises no `/merge` refs at all, for
|
||||
open and closed pull requests alike. The first fetch has always succeeded; **the
|
||||
fallback has never fired once.** So the gate did not lose merged content on
|
||||
conflicted pull requests — it has never had merged content, on any pull request
|
||||
in this repository's history. Green has meant "this branch passed on its own",
|
||||
which on a base that has moved is not what lands, and `block_on_outdated_branch`
|
||||
is off on release/1.0 so the base usually has moved.
|
||||
|
||||
**The checkout now fetches the base tip and the pull request head, merges them,
|
||||
and refuses if the merge does not apply** — as its own named step, so
|
||||
`/actions/runs/<id>/jobs` distinguishes "nothing was tested" from "the tests
|
||||
spoke". Verified by producing it: with the fix on a conflicted pull request the
|
||||
required context went `failure` in 2 s with the two test steps `skipped`. The
|
||||
`--depth 1` is gone (a merge needs a merge base; a full fetch of this repository
|
||||
is 6.8 MB and 1.1 s), and the fallback survives only on the `workflow_dispatch`
|
||||
path, which has no pull request to merge and now says so in its output.
|
||||
|
||||
**Case 2: `concurrency:` is gone, and `cancel-in-progress` was never the knob.**
|
||||
Runs 531 and 533 on PR #14 were cancelled at 0 s each at the exact second the
|
||||
next run was created, having never started; a cancelled run posts `failure` on
|
||||
the required context, described `Canceled after 0s`, and branch protection
|
||||
compares state and not description — so "nothing ran" and "your tests are
|
||||
broken" arrive at the gate as the same red, wanting opposite responses. Three
|
||||
settings were measured with one run holding the single runner slot and two
|
||||
pushes behind it: with **no block at all** both queued runs survived and
|
||||
executed; with the group kept and **`cancel-in-progress: false`** the queued run
|
||||
was still cancelled at 0 s. A shared group cancels a run that has not started
|
||||
regardless of that flag. Having no group is the only configuration measured to
|
||||
leave a queued run alive, and it is what ships. The cost — a developer who
|
||||
pushes four times occupies the shared runner four times — is CI-01's own trade
|
||||
written the other way round: a delayed verdict, never a destroyed one.
|
||||
|
||||
**`test_ci_gate.py` grades the gate by running it, not by reading it.** It
|
||||
extracts the checkout and merge steps out of `checks.yml` and executes the
|
||||
shipped commands against two throwaway local repositories it builds — one whose
|
||||
pull request merges, one whose does not — and pins that the old one-liner exits
|
||||
0 on the unmergeable one while the new steps refuse. It also pins the two tokens
|
||||
that assemble `checks / unit (pull_request)`: renaming `name:` or the `unit:`
|
||||
job key would leave every open and future pull request waiting forever on a
|
||||
context that never arrives, with no error anywhere in that sequence. Seven
|
||||
mutations of `checks.yml` were each confirmed red. `.gitea/ci/Dockerfile` gains
|
||||
`git` for it.
|
||||
|
||||
**What was NOT established, stated so nobody reads more into this.** The
|
||||
original report that "no run was ever created for `0942228d`" was already
|
||||
corrected on the card — run 533 was created and cancelled — and this work
|
||||
confirms that from the runs list and the per-commit status history. A commit
|
||||
that never had a run carries an empty `/statuses/<sha>` list; a queued one
|
||||
carries `pending / Waiting to run` within seconds, and a concurrency-held one
|
||||
`pending / Blocked by required conditions`. Those are distinguishable at the
|
||||
API. `/actions/tasks`, which is what was polled originally, lists only tasks
|
||||
that started, and cannot answer the question at all.
|
||||
|
||||
**The NOT READY banner no longer repeats the row underneath it.**
|
||||
`status_payload()` renders the first hard-failing check as the page headline, so
|
||||
the scope sentence above turned the loudest element on the page into a
|
||||
550-character paragraph that the checks list then repeated verbatim. A row may
|
||||
now carry an optional short `banner` form; the floor-limited row does, and its
|
||||
headline is the guard's own line plus a 68-character scope tag. **The row itself
|
||||
is unchanged** — the checks list is where an operator reads what the floor does
|
||||
and does not bound, and shortening that would have been weakening AC 3. Rows
|
||||
without the key are unaffected, and the page still renders with `textContent`.
|
||||
|
||||
**A setpoint device smaller than `max_w` silently disarmed the frozen-meter
|
||||
detector, and the status page reported it as armed (SAFETY-20).** SAFETY-18's
|
||||
conjunction needs `abs(commanded_w) >= 0.95 * max_w`, but the emitted command is
|
||||
clipped to the setpoint device's own `[dev_min, dev_max]` range as well as to
|
||||
`max_w` — in `clamp_to_rating()` and again as the arbiter's `device` P_SAFETY
|
||||
limit claim. Measured on the shipped predicate at the ticket's numbers,
|
||||
`max_w: 5000` on a ±4700 W inverter:
|
||||
|
||||
looks_frozen(unchanged_s=3600, commanded_w=4700, max_w=5000) -> False
|
||||
|
||||
The command is pinned at the hardware's rail, the meter has been frozen for an
|
||||
hour, and term 2 is unsatisfiable by construction because 4700 < 4750. Any
|
||||
rating at or below `0.95 * max_w` disarms the conjunction outright. The page
|
||||
then printed `armed (… command is over 4750 W)` — a guard that cannot fire,
|
||||
advertising that it can, which is the failure SAFETY-15, SAFETY-19 and
|
||||
validate.py rule 5 all exist to prevent.
|
||||
|
||||
**The rail is now measured against `min(max_w, |dev_min|, |dev_max|)`** —
|
||||
`freeze.rail_ceiling_w()`, threaded through `looks_frozen()`,
|
||||
`FreezeWatchdog.evaluate()` and both call sites in `main.py`. An unread rating
|
||||
(`hass.limits()` returning `None` when ESPHome is not up) leaves the old
|
||||
behaviour exactly, and correctly: on that path no device clamp is applied
|
||||
either, so `max_w` really is the ceiling. A rating *larger* than `max_w` cannot
|
||||
raise the rail — this is a `min()`, not a swap. The status row prints the rail
|
||||
the predicate actually uses and names the device when the device is what capped
|
||||
it; the log line and the HA notification do the same, since they outlive the
|
||||
page.
|
||||
|
||||
**The smaller of the two device bounds, not a per-sign pair.** A per-sign rail
|
||||
is tighter and is not wrong, but it is two rails needing two coverage verdicts
|
||||
on a status row that carries one number, and the only configuration that
|
||||
distinguishes them is refused at startup anyway. The symmetric ceiling can only
|
||||
*lower* the rail, which widens term 2 rather than disarming it; term 1 carries
|
||||
the no-false-positive argument and is untouched.
|
||||
|
||||
**A ceiling of 0 W is NOT COVERED, not "armed at 0 W".** A device that can
|
||||
command nothing in one direction would make `abs(command) >= 0` true of every
|
||||
command including a parked one — term 2 degenerately *true*, collapsing the
|
||||
conjunction into the bare `unchanged_s > N` threshold TEL-05 refused for
|
||||
false-tripping at this controller's own operating point. `rail_unreachable()`
|
||||
returns the reason, `looks_frozen()` stays silent, and the page uses the NOT
|
||||
COVERED row the unsupported-transport case already has — a second reason to use
|
||||
that surface, not a new mechanism.
|
||||
|
||||
**AC4, decided rather than assumed: no new `validate.py` rule.** The
|
||||
configuration is `max_w` above the device rating, which rule 2 (CFG-01) already
|
||||
refuses on the identical predicate, re-run by `run_control()` once the real
|
||||
rating is known. A rail-specific rule would fire on a strict subset of what rule
|
||||
2 refuses (`0.95 * max_w > dev_max` implies `max_w > dev_max`) and could never
|
||||
be the rule that stopped a start. The residue is the state where `hass.limits()`
|
||||
answered `(None, None)` and the range checks were skipped — there is nothing to
|
||||
refuse there, by construction, which is why the answer is a runtime row. Written
|
||||
into validate.py's "deliberately not refused" list, and *pinned* by four checks
|
||||
in `test_validate.py` so the decision's premise goes red if rule 2 is ever
|
||||
softened back to a warning.
|
||||
|
||||
**And it was verified by breaking it.** Reverting `rail_w()` to bare `max_w`
|
||||
fails nine checks; deleting the NOT COVERED handling fails five; and — the one
|
||||
that mattered — shipping the corrected predicate while *not* passing the rating
|
||||
from `check_meter_frozen()` originally left the whole suite green, because
|
||||
nothing graded the caller. `test_freeze.py` part 5b now drives the real
|
||||
`cycle()` on a ±4700 W device and asserts on the notification that leaves the
|
||||
process; the unwiring mutation fails three checks there. The peak-guard call
|
||||
site's wiring is still ungraded — it sits behind `p1_enabled` and needs a fed
|
||||
averager to have any observable consequence — and that gap is named in the file
|
||||
rather than implied.
|
||||
**A mutation run could grade code that was not there, and the fix is a purge
|
||||
rather than a flag (TEST-15).** FCST-03's developer reverted `self.provisional`
|
||||
to `here.provisional`, re-ran, and reported a survivor; disassembly showed the
|
||||
source read `here` while the running code loaded `self`. CPython validates a
|
||||
`.pyc` on (source size, source mtime truncated to whole seconds), and a
|
||||
size-preserving edit reverted inside one second moves neither number, so the
|
||||
stale bytecode was reused. That does not make past results wrong - it made them
|
||||
unverified, and the distinction is the whole card.
|
||||
|
||||
Reproduced rather than reasoned about. `test_bytecode.py` builds a real package
|
||||
whose two return values are the same length, imports it in a real subprocess,
|
||||
rewrites it inside the same second and reads back which value ran. Part 1 shows
|
||||
the interpreter running `SELF` off a file that says `HERE`.
|
||||
|
||||
**And it shows the two obvious mitigations do not work.** `python3 -B` and
|
||||
`PYTHONDONTWRITEBYTECODE=1` are write-side only: neither stops an EXISTING stale
|
||||
`.pyc` being read, and a mutation run always has one because the previous run
|
||||
wrote it. The advice already in `test_control.py`'s coverage audit led with `-B`
|
||||
and is corrected here - the purge is the half that works, and `-B` earns its
|
||||
place by protecting the NEXT edit rather than this one. No `sleep` anywhere:
|
||||
one-second mtime resolution is the mechanism, and waiting it out would slow every
|
||||
run down while still only covering the edit somebody remembered to slow.
|
||||
|
||||
`goodwe_controller/tools/mutation_run.sh` is the harness the house adopts: it
|
||||
purges, prints a sha256/byte fingerprint of every `app/*.py` it is about to
|
||||
grade - so a mutation report can say WHICH source produced it - runs each suite
|
||||
under `python3 -B`, refuses a tree with no `test_*.py` (CI-01's rule), and fails
|
||||
if a cache appears during the run. It takes the tree as an argument so the infra
|
||||
repo's replay harnesses can call it.
|
||||
|
||||
`MUTATION.md` states the guarantee where a mutation gets written, and every one
|
||||
of the 16 suites now points at it from its docstring - a list `test_bytecode.py`
|
||||
derives from the tree, so a new suite joining without the pointer is red.
|
||||
|
||||
CI was already immune and is described that way rather than as a hole being
|
||||
closed: `checks.yml` mounts the checkout `-v "$WS:/w:ro"`, and a read-only tree
|
||||
cannot take a `__pycache__` at all - measured, and it fails silently, exit
|
||||
status 0 - while each job `rm -rf`s its workspace and clones afresh.
|
||||
`PYTHONDONTWRITEBYTECODE=1` is added as belt and braces, because the `:ro` is one
|
||||
character wide. The shipped add-on was never affected: `Dockerfile` has set
|
||||
`PYTHONDONTWRITEBYTECODE=1` since it was written.
|
||||
|
||||
**The survey of this week's mutation claims is in `MUTATION.md`, scoped by the
|
||||
property rather than by re-running everything.** The defect is one-directional -
|
||||
stale bytecode turns a red into a green survivor and never the reverse - so every
|
||||
"all red, no survivors" result in the window is not at risk, and the exposure is
|
||||
the recorded SURVIVORS from source-edit runs made before the purge discipline
|
||||
landed on 2026-08-31. Two of them were re-run here under the harness and both
|
||||
still stand (TARIFF-01's `record_block()` ignoring its `policy` argument;
|
||||
SAFETY-03's `abs()` on the clamp limit). The rest are labelled still-unverified
|
||||
rather than quietly assumed or noisily re-run.
|
||||
|
||||
Out of scope and recorded: the infra repo's `sim/` replay harnesses import the
|
||||
add-on and write bytecode into both trees. Anyone mutating a module graded by a
|
||||
replay must purge both by hand until that repo adopts the harness.
|
||||
|
||||
**`release/1.0` went red at midnight on a commit nobody had touched (TEST-17).**
|
||||
`Controller.checks()` read the capacity-tariff peak with `self.peak.peak()` - no
|
||||
argument - so `tariff.py` resolved the month from `datetime.now()`, while
|
||||
`test_tariff.py` section 10 banks its quarter at the fixed fixture
|
||||
`2026-08-30`. From 1 September the page was correctly asked for September,
|
||||
correctly answered `NO_RECORD`, and the row read *"no completed quarter recorded
|
||||
yet"* - a string containing no `"peak"`, which the section's filter required.
|
||||
Four checks failed. The suite had been a latent time bomb since TARIFF-01
|
||||
merged on 2026-08-30 and every PR that ran it ran in August.
|
||||
|
||||
Isolated by holding the commit and the image constant and moving only the clock
|
||||
under `libfaketime`: green at 2026-08-30, four failures at 2026-09-01, identical
|
||||
at `f4914a1`, `04292c4~1` and `04292c4`. The calendar, not a regression.
|
||||
|
||||
**The product was right and the test was wrong**, so the fix does not change what
|
||||
the live page says. `checks()` takes `when: datetime | None = None` and threads
|
||||
it into `peak()` and `warning_frac()` - the convention every other peak query in
|
||||
`tariff.py` already follows. The single production caller passes nothing and
|
||||
still means today. Section 10 now grades at its own fixture's month.
|
||||
|
||||
Three new checks make the defect detectable rather than seasonal: the same
|
||||
controller read at two different reference months must produce two different
|
||||
rows, which no clock can satisfy; the later month must read `NO_RECORD` and stay
|
||||
distinguishable from both an observed peak and an unreadable store; and calling
|
||||
`checks()` with no argument must still mean today. Verified by mutation - a
|
||||
`checks()` that drops `when` is now red at every clock tried, where the old
|
||||
section went green in August. Full suite green, 15 files, at the real clock and
|
||||
at faked clocks in four other months.
|
||||
|
||||
One thing left alone deliberately: only the UNREADABLE branch prefixes its row
|
||||
with `capacity-tariff peak:`. The `NO_RECORD` row carries neither that phrase
|
||||
nor the word `peak`, which is what made the original filter brittle and what
|
||||
broke the first draft of the new checks too. It is product text with other
|
||||
suites reading it, so it is noted here rather than changed.
|
||||
|
||||
**Thirty days of the real meter, and the acceptance criterion three cards
|
||||
deferred is now a number (DATA-01).** TARIFF-01 and SAFETY-07 both merged with
|
||||
AC 3 - *"monthly peak held under the soft limit in >= 95 % of intervals over a
|
||||
30-day simulation replay"* - honestly unmet, on the belief that only two days of
|
||||
capture existed and nothing longer could be produced. That belief came from a
|
||||
true statement about the past being read as one about the future: HA's recorder
|
||||
still held the whole month. `scenarios/p1-net-30d-2026-08/` is 2026-08-01 to
|
||||
2026-08-30, **485,841 samples, 30/30 days read, 0 failed, 4.13 MB gzipped**, in
|
||||
the same schema as the two days that were already there.
|
||||
|
||||
`tools/export_p1_history.py` is the exporter, committed and runnable - the
|
||||
2026-08-25 one-off was not, and that is exactly why the data was thought
|
||||
unobtainable. It reads day-at-a-time, retries, and **never lets a failed read
|
||||
look like an empty hour**: a day whose read fails writes no file, is recorded as
|
||||
`"read": "FAILED"`, and the run exits non-zero; the entity is proved to exist
|
||||
before any empty day is believed. Nothing is interpolated, so the month's 13
|
||||
gaps (1291 s, 99.95 % covered) and its 3 `unavailable` samples stay visible.
|
||||
`--verify` re-fetches the two committed days by the same route and reproduces
|
||||
them **byte for byte** after decompression.
|
||||
|
||||
`tools/replay_ac3.py` runs the month. Over 30 days the criterion measures
|
||||
**98.89 % uncontrolled and 98.99 % guarded**, so it is met on that reading - and
|
||||
the uncontrolled figure is the finding: a month with no controller at all passes
|
||||
it. On the other reading of the same sentence it is not met - the guard takes
|
||||
August's peak from **5029.8 W to 4107.3 W**, still over the 3500 W soft limit,
|
||||
because once a month peak is set `CEILING_MONTH_PEAK` defends that peak rather
|
||||
than the cap. Neither number is hidden; both are in that directory's README.
|
||||
|
||||
The size decision is committed and measured, not absorbed: a `git bundle` of
|
||||
the whole history goes from **1.58 MB to 5.28 MB** (+3.70 MB, x3.3), which a
|
||||
Home Assistant supervisor clones on every install. Downsampling was not
|
||||
available - `meter_max_age_s` is 30 s, so any coarser resample converts real
|
||||
coverage into modelled meter-gap and moves the number being measured.
|
||||
|
||||
The thirty files sit in a SUBDIRECTORY on purpose: `test_tariff.py` part 9 and
|
||||
`test_peakguard.py` part 6 glob `scenarios/p1-net-*.jsonl.gz` non-recursively,
|
||||
so CI keeps replaying the two small days and does not grow ~50 s per PR. Both
|
||||
files' honesty notes are corrected to point at the month.
|
||||
|
||||
**OPT-04's AC4 is met: twelve months of real EPEX BE day-ahead prices are now in
|
||||
the repository, and the strategy has been replayed against them (DATA-02).**
|
||||
AC4 asked for "net-positive across 12 months of replayed prices". OPT-04 shipped
|
||||
it as NOT MET and replayed a synthetic year instead, because `scenarios/` held
|
||||
only P1 meter captures. That was the right call at the time and the wrong
|
||||
diagnosis of why: the criterion was being carried alongside a 30-day *meter*
|
||||
criterion as though both needed waiting, and EPEX BE day-ahead is **public data,
|
||||
not a capture**. It needed a fetch, not a month.
|
||||
|
||||
`scenarios/epex-be-dayahead-2025-09-01_2026-09-01.json` — **8760 hourly points**,
|
||||
2025-09-01 to 2026-09-01 Brussels-local, in §9.3's canonical three-field shape.
|
||||
`scenarios/fetch_epex_be.py` produced it and `--verify` re-derives every claim it
|
||||
makes about itself without touching the network.
|
||||
|
||||
**Licensing was checked before anything was committed.** The source is
|
||||
Fraunhofer ISE's Energy-Charts API, which publishes the **BE** zone under
|
||||
**CC BY 4.0 from Bundesnetzagentur | SMARD.de** and other zones under
|
||||
private-use-only terms — so this zone is redistributable with attribution and the
|
||||
data is committed rather than left as a script plus a checksum. The fetcher
|
||||
**refuses to write a file** whose per-response `license_info` stops saying
|
||||
CC BY 4.0. Cross-checked against the upstream: SMARD's own `4996/DE` series
|
||||
matched this feed on all 96 quarter-hours of 2026-04-10, maximum difference
|
||||
0.00 EUR/MWh.
|
||||
|
||||
**The figures are raw wholesale and the file says so.** `"all_in": false`, with
|
||||
the markup/tax assumption carried in `provenance.all_in_assumption` as *numbers
|
||||
to apply* rather than numbers already applied — TARIFF-02's double-counting trap
|
||||
in data form. `test_arbitrage.py` section 7B applies it in one visible place and
|
||||
**asserts arithmetically** that its two additive terms cancel out of every daily
|
||||
spread, so the trade counts depend on the VAT multiplier alone and not on the
|
||||
guessed markup. The same replay is run on raw wholesale as well, so how much of
|
||||
the answer rests on the guess is reported (110 trades all-in, 88 raw).
|
||||
|
||||
**DST is handled by construction, not by a special case.** The fetcher iterates
|
||||
in UTC and renders through `price.brussels()`, so **2025-10-26 comes out 25
|
||||
points and 2026-03-29 comes out 23** — verified by counting per Brussels day
|
||||
rather than asserting 24, and by checking that October's 02:00 appears twice at
|
||||
`+02:00` and `+01:00` with two different prices while March's 02:00 does not
|
||||
appear at all. The window is bounded at *local* midnight: bounding it at 00:00
|
||||
UTC produced a 22-hour first day, and a 24-hour day silently missing from the
|
||||
end, both of which the point-and-gap accounting caught.
|
||||
|
||||
**The result, at the shipped default, whatever it is.** At
|
||||
`cycle_cost_threshold_eur` **0.10** widened by FCST-03's no-weather **1.5×** to a
|
||||
required 0.1500 EUR/kWh, the real year completes **110 round trips** and is
|
||||
**net-positive at +24.88 EUR** of benefit net of the cycle cost (2 kWh a trade).
|
||||
Unwidened it completes 173. **Nothing was tuned:** the shipped default and the
|
||||
2.5/1.5 factors are untouched, and every figure comes out of the same `decide()`.
|
||||
|
||||
**What the product owner's open decision now has under it.** The four
|
||||
independent reports that a static day/night spread of ~0.0840 does not clear
|
||||
0.10 **all stand** — a static-tariff site still never trades. What was missing
|
||||
was the other half: a *dynamic* site's daily spread clears the widened
|
||||
requirement on **121 of 365 days**, median daily all-in spread **0.1130**. The
|
||||
threshold at which a median day would clear is **0.0754**, and at that value the
|
||||
same year completes 156 trips for +35.42 EUR. Both numbers are reported; neither
|
||||
is applied.
|
||||
|
||||
**And the synthetic year stays, because the real one cannot grade §17.** Not one
|
||||
of the 365 real days has a negative *dearest* hour — 372 negative wholesale hours
|
||||
and 0 days where the strategy would have sold into one — so "0 discharges into a
|
||||
negative-price hour" over real prices is a count of something that could not
|
||||
happen, and deleting the guard would not change it. Section 7B asserts that
|
||||
degeneracy instead of quietly reporting the zero; section 7's generator is still
|
||||
the only thing here that puts a negative price where the strategy would sell.
|
||||
|
||||
**Size, measured rather than assumed.** Plain JSON: 893 KB in the working tree
|
||||
but **74.6 KB as a git object**, against 56.5 KB for a committed `.json.gz`. Git
|
||||
already compresses blobs, so gzipping saves 18 KB and costs a reviewer the
|
||||
ability to read the provenance block — including the licence claim they are
|
||||
meant to check — in the diff. Plain, and `load()` still accepts `.gz` for a
|
||||
future dataset that earns it.
|
||||
|
||||
**Nothing is wired into the add-on.** `generic_dayahead` remains the live fetch
|
||||
path; nothing under `app/` imports the script, and the dataset is for replay.
|
||||
|
||||
**The capacity-peak guard's forced discharge now has an EMS-side energy floor
|
||||
(SAFETY-24).** SAFETY-07 can command a discharge to hold a billed quarter down,
|
||||
and nothing below it consulted the state of charge — `soc_floor` belongs to the
|
||||
|
||||
@@ -0,0 +1,417 @@
|
||||
# SAFETY-25 — does the grid-following loop get a reserve floor?
|
||||
|
||||
**Status: DECIDED 2026-09-02 — Option A.** The product owner has answered §1:
|
||||
**the BMS cut-out stays the only backstop for demand-driven discharge on the
|
||||
grid-following loop.** **Option B — a loop-side reserve floor — is DEFERRED**,
|
||||
not rejected, with an explicit revisit trigger recorded in §0c: **`ALLOC-01`**.
|
||||
|
||||
Option A **is the shipped behaviour**, so recording this decision changed no
|
||||
code. The honesty half of SAFETY-25 — `peak_soc_floor`'s scope made true in the
|
||||
config, in `DOCS.md` and on the status page — had already shipped and was
|
||||
required under every option. What was missing was the answer, and the answer is
|
||||
now here rather than in a Trello card that scrolls away.
|
||||
|
||||
**Everything from §1 down is the memo exactly as it was written before the
|
||||
decision, and is deliberately left intact.** It is the record of *why*, and a
|
||||
future reader arriving at the revisit trigger needs the options analysis, the
|
||||
costs, the measured replay and the trap in Option B's obvious shape — not a
|
||||
one-line verdict. §5 still labels Option B *"(recommended)"* and §6 still says
|
||||
"Option B is what I would build"; those were the engineering recommendation put
|
||||
to the owner, they are preserved as written, and **§0 is what was decided.**
|
||||
|
||||
Filed with SAFETY-25. Card 6a94b2b98b73123d520e69f2. The other half of that
|
||||
ticket — making `peak_soc_floor`'s scope honest in the config, the docs and on
|
||||
the status page — **shipped in SAFETY-25's own PR** and did not wait on this,
|
||||
because it was required whichever way the answer went.
|
||||
|
||||
*This directory exists so a recorded decision has somewhere to live that is not a
|
||||
comment in a source file nobody reads and not a Trello card that scrolls away.
|
||||
`SAFETY-27` asks for a second one (the naming of the floors); it belongs here
|
||||
too, and §0d says what N=2 does to it.*
|
||||
|
||||
---
|
||||
|
||||
## 0. The decision
|
||||
|
||||
### 0a. What was decided, and the owner's reasoning
|
||||
|
||||
**Option A. The BMS remains the only backstop for demand-driven discharge on the
|
||||
grid-following loop. Option B is deferred until `ALLOC-01` exists.**
|
||||
|
||||
The reasoning is not "Option B is wrong" — §5 and §6 still stand as engineering.
|
||||
It is that **deferring is the safe direction, and building now is not.**
|
||||
|
||||
Option B's safety proof is the ordering constraint in §5:
|
||||
|
||||
bms_soc_floor < loop_soc_floor <= peak_soc_floor
|
||||
|
||||
That proof has an unstated premise: **the reserve predicate and
|
||||
`discharge_permitted()` must read the SAME state of charge.** At N=1 they do,
|
||||
which is why the proof reads as airtight, and why part 10d can run it through
|
||||
the real arbiter and watch the contradiction disappear.
|
||||
|
||||
**With two packs they read different numbers.** The reserve binds on whichever
|
||||
pack is emptier and files `hi = 0`; the peak guard, reading the other pack or an
|
||||
average of the two, is *not* floor-limited and files `lo = excess > 0`. Then
|
||||
`lo > hi`, arbiter clause 3 fires, and the result is **0 W — the battery parked,
|
||||
in the billed quarter.** That is precisely the failure §5 marks *"⚠️ fatal if
|
||||
missed"*, arriving by a route the ordering rule cannot close, because
|
||||
`loop_soc_floor <= peak_soc_floor` is still perfectly satisfied while it happens.
|
||||
|
||||
**And no config-ordering validator can catch it.** The rule §5 proposes — refuse
|
||||
the bad ordering at startup, in CFG-01's manner — grades *configuration*. This is
|
||||
a **runtime divergence between two readings**, not a config ordering. The startup
|
||||
check would pass, every time, on the exact tree that parks the battery.
|
||||
|
||||
So the shape of the risk decides the direction: **Option A's cost is energy
|
||||
(§5, "every watt below the reserve becomes billed import" — inverted: the pack
|
||||
may sit on its own cut-out). Option B's cost, built too early, is a parked
|
||||
battery in the one quarter of the month that sets the bill.** One of those is a
|
||||
tariff line; the other is the failure this memo already calls fatal. Take the
|
||||
one that cannot park the battery, and build Option B when its proof holds again.
|
||||
|
||||
### 0b. What this decision does NOT say
|
||||
|
||||
- It does **not** say a loop-side reserve is a bad idea. §5's protection
|
||||
argument — keeping the pack off its own cut-out, which is the `MAINT-01` drift
|
||||
condition — is unchanged and still wanted.
|
||||
- It does **not** close §4's fifth-key question. `SAFETY-27` still owns the
|
||||
naming of the floors, and any future `loop_soc_floor` still lands after it.
|
||||
- It does **not** weaken §6 item 3: **the tripwire in `test_peakguard.py`
|
||||
part 10 stays.** A deferred option needs its tripwire more than an open one
|
||||
does, because "deferred" is exactly the state in which someone builds it by
|
||||
accident. Part 10f still takes red on the line a ninth claim source is
|
||||
written. Do not remove it.
|
||||
|
||||
### 0c. The revisit trigger: `ALLOC-01`
|
||||
|
||||
**`ALLOC-01` is the trigger, and it is a trigger because it changes the SHAPE of
|
||||
the two claims, not because it changes anyone's mind.**
|
||||
|
||||
`ARCH-01` decided that the site grid target is **allocated host-side, above the
|
||||
driver seam**: one integrator on P1, a sum-invariant split into per-inverter
|
||||
shares, and each inverter told a function of **its own share** only. It also
|
||||
decided that **per-inverter constraints are consumed by the allocator as
|
||||
INTERVALS, never filed as site-level claims** — which is the structural fix for
|
||||
the cross-inverter `lo > hi -> 0 W` contradiction.
|
||||
|
||||
Under the allocator, the two claims that collide in §0a stop sharing a claim
|
||||
list at all:
|
||||
|
||||
| | today (N=1, no allocator) | under `ALLOC-01` |
|
||||
|---|---|---|
|
||||
| the loop reserve | a site `hi` at `P_LOOP` | a **per-inverter `hi`**, consumed at **stage A** as that unit's interval |
|
||||
| the peak floor | a site `lo` at `P_PEAK` | still a **site `lo`**, filed at **stage B** against the site target |
|
||||
|
||||
**Different claim lists, evaluated at different stages, structurally unable to
|
||||
cross.** The reserve bounds one inverter's share; the peak floor bounds the site
|
||||
sum. There is no arbiter resolution in which one is the other's `lo` and `hi`,
|
||||
so §0a's failure cannot be constructed — not "is guarded against", *cannot be
|
||||
constructed*. That is the same class of argument as §5's ordering rule but a
|
||||
stronger one: §5 makes the crossing harmless, `ALLOC-01` makes it unreachable.
|
||||
|
||||
**That is the shape in which Option B becomes safe to build.** When `ALLOC-01`
|
||||
exists, reopen this memo at §5 Option B, restate the reserve as a stage-A
|
||||
per-inverter interval, and the ordering rule becomes an implementation
|
||||
convenience rather than the load-bearing proof.
|
||||
|
||||
### 0d. What has to be RE-EARNED at N=2, stated plainly
|
||||
|
||||
Two things this decision leans on do not survive a second pack, and saying so is
|
||||
part of the decision rather than a footnote to it.
|
||||
|
||||
**1. `SAFETY-27` now names FIVE floors across TWO packs.** §4's table already
|
||||
carries four keys plus "the loop"; two of them ship the same default of 20 from
|
||||
different cards. At N=2 each of those is a floor *per pack*, and "the SoC" stops
|
||||
being a scalar the config can bound — which is the same divergence that makes
|
||||
§0a's contradiction possible. `SAFETY-27` inherits a harder question than the
|
||||
one it was filed with.
|
||||
|
||||
**2. `test_peakguard.py` part 10f — the guarantee that made SAFETY-25 mergeable —
|
||||
CANNOT EXPRESS TWO PACKS, and will not cover the two-pack case.** Say it flatly,
|
||||
because it is the load-bearing pin (§6 item 3: PR #31 shipped this section
|
||||
claiming a tripwire it did not have, and the reviewer disproved the claim by
|
||||
building Option B under a green suite):
|
||||
|
||||
- 10f's dynamic half is a **scalar 0–100 % SoC sweep** — one number swept over
|
||||
one range, in the idle and floor-limited states — against a **single-series
|
||||
capture** (§7: the fixtures carry signed net power at the meter and nothing
|
||||
else; the pack is modelled, and one pack is modelled).
|
||||
- A two-pack exposure lives in the **difference** between two SoC readings. A
|
||||
sweep over one scalar visits no point of that space, at any resolution. It
|
||||
cannot fail on the divergence because it cannot represent it.
|
||||
- 10f's **static** half — the AST scan pinning the eight claim sources in
|
||||
`Controller.cycle()` — survives, and is the half that keeps working: a ninth
|
||||
source still goes red on the line it is written, at N=2 as at N=1. It is the
|
||||
*dynamic* half, the one that proves the named sources actually reach the
|
||||
arbiter across the whole state space, that goes silent.
|
||||
|
||||
So: **10f remains a valid tripwire against building Option B today, and is not a
|
||||
guarantee about N=2.** Whoever reaches the `ALLOC-01` revisit inherits the job of
|
||||
re-earning it — a two-pack fixture with two SoC series, or a claim-shape argument
|
||||
at stage A that does not need one. Merging a two-pack reserve on 10f's current
|
||||
green is merging on a check that cannot see the failure.
|
||||
|
||||
---
|
||||
|
||||
## 1. The question
|
||||
|
||||
> Does the grid-following (self-consumption) loop get an SoC floor of its own, or
|
||||
> is the BMS cut-out **deliberately** the only backstop under demand-driven
|
||||
> discharge?
|
||||
|
||||
Either answer is defensible. What is not defensible is the state we have been in
|
||||
for four tickets: **silence, plus a config key called `peak_soc_floor` that reads
|
||||
like the answer is "yes".**
|
||||
|
||||
## 2. What is actually exposed — replayed, not argued
|
||||
|
||||
The exposure was written down three times (SAFETY-18's finding, SAFETY-24's
|
||||
module note and PR body, and SAFETY-24's honestly-uncaught 13th mutation) and
|
||||
never measured. SAFETY-25 measured it. The replay is `test_peakguard.py` part 10;
|
||||
it drives the **shipped** `control.compute()`, `peakguard.decide()`,
|
||||
`peakguard.claim()` and `arbiter.resolve()` over the committed capture
|
||||
`scenarios/p1-net-2026-08-20.jsonl.gz`, with the battery and the state of charge
|
||||
modelled (the captures carry meter power only — see §7).
|
||||
|
||||
### 2a. A sustained-load evening takes the pack to the BMS cut-out
|
||||
|
||||
19:00–22:00 UTC on 2026-08-20 — three hours of house load after the sun has gone,
|
||||
**830 W mean, minimum 701 W, maximum 1223 W, not one watt of export in the whole
|
||||
window.** The pack is the 13.8 kWh reference pack (300 Ah × 51.2 V × DoD 90),
|
||||
started at **21 %** — one point above the shipped `peak_soc_floor`.
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| pack at the start of the evening | **21.0 %** |
|
||||
| pack three hours later | **10.0 %** — `bms_soc_floor` |
|
||||
| energy the loop delivered | **1525 Wh** |
|
||||
| control cycles with the pack below `peak_soc_floor` | **549 of 587** |
|
||||
| …of those, cycles still delivering discharge | **343** |
|
||||
| cycles on which the peak guard filed *any* floor | **0** |
|
||||
|
||||
### 2b. It is a behaviour, not a config value
|
||||
|
||||
The same replay, same pack, same evening, with `peak_soc_floor` set to **5, 11,
|
||||
20 and 60** — the shipped value and both ends of the schema range:
|
||||
|
||||
peak_soc_floor = 5 -> ends at 9.9715 %, 1524.58 Wh out
|
||||
peak_soc_floor = 11 -> ends at 9.9715 %, 1524.58 Wh out
|
||||
peak_soc_floor = 20 -> ends at 9.9715 %, 1524.58 Wh out
|
||||
peak_soc_floor = 60 -> ends at 9.9715 %, 1524.58 Wh out
|
||||
|
||||
Identical to four decimal places. **Raising the option does nothing, because the
|
||||
guard it bounds is not the thing doing the discharging.**
|
||||
|
||||
### 2c. The two states coexist in the same cycle
|
||||
|
||||
On the same day's high-load block (15:00–17:00 UTC), with the pack started one
|
||||
point *below* the floor, the guard reports `PEAK GUARD FLOOR-LIMITED` —
|
||||
*"commanding no forced discharge"* — on **49 cycles**, and on **all 49** the
|
||||
arbiter simultaneously grants the loop a discharge of up to **2000 W**. The
|
||||
status page tells the operator the truth about the guard while the pack empties.
|
||||
|
||||
### 2d. Stated fairly, because overstating it is how a real finding gets ignored
|
||||
|
||||
This is **not** a runaway. Self-consumption discharge is demand-driven and
|
||||
self-limiting: it stops when the house stops drawing, and every watt of it is
|
||||
serving load that would otherwise have been imported. It is not SAFETY-18's
|
||||
frozen-meter rail, and nothing here is spending the pack for a reason of its own.
|
||||
What it means is narrower and still real:
|
||||
|
||||
- the **depth** the pack reaches on a heavy evening is set by the house, not by
|
||||
anything an operator can configure; and
|
||||
- `peak_soc_floor` **reads like a system-wide guarantee it is not.** A floor that
|
||||
binds one consumer and not the other is worse than no floor if its name does
|
||||
not say so — which is precisely what SAFETY-25's other half fixed.
|
||||
|
||||
## 3. Why SAFETY-24's floor cannot be extended to cover this
|
||||
|
||||
The peak guard files a `lo` limit — a **lower** bound on the setpoint. That
|
||||
asymmetry is what makes the guard trustworthy: a reviewer proved across 19,800
|
||||
combinations that it can never lower a target, never cap a discharge, never
|
||||
contradict the arbiter, and never file a negative floor. `peakguard.claim()`
|
||||
leaves `hi` at `+inf` as a fact about the object rather than a rule someone has
|
||||
to remember.
|
||||
|
||||
**A `lo` limit is structurally incapable of stopping a discharge the loop itself
|
||||
wants.** So the same property that makes the guard safe makes it useless here.
|
||||
Raising `peak_soc_floor` cannot become the answer; §2b is that statement
|
||||
measured.
|
||||
|
||||
## 4. The floors we already have — and this would be the fifth key
|
||||
|
||||
SAFETY-24 recorded a decision to keep `maintenance_soc_floor` separate with an
|
||||
explicit revisit trigger: *"if a third floor appears."* **The trigger has already
|
||||
fired, unremarked**, when OPT-04 shipped `arbitrage_soc_floor`.
|
||||
|
||||
| option | default | bounds | priority of the consumer |
|
||||
|---|---|---|---|
|
||||
| `maintenance_soc_floor` | 11 | the monthly recalibration's **drain target** | `P_MAINTENANCE` 60 |
|
||||
| `peak_soc_floor` | 20 | the peak guard's forced discharge | `P_PEAK` 50 (a `lo` limit) |
|
||||
| `bms_soc_floor` | 10 | *nothing* — it describes the pack, so rule 8 can refuse a floor that cannot bind | — |
|
||||
| `arbitrage_soc_floor` | 20 | arbitrage discharge | `P_ARBITRAGE` 30 |
|
||||
| **the loop** | — | **nothing** | `P_LOOP` 10 |
|
||||
|
||||
Two of them ship the same default (20) from different cards for different
|
||||
reasons, which is how a value that looks deliberate becomes a coincidence nobody
|
||||
dares change. **`SAFETY-27` owns the naming question and this memo does not
|
||||
pre-empt it** — but any answer to §1 that adds a fifth key should land *after*
|
||||
SAFETY-27's decision, or it adds a fifth accreted name to four.
|
||||
|
||||
## 5. The options
|
||||
|
||||
### Option A — record the BMS as the deliberate backstop; add nothing
|
||||
|
||||
Say plainly, in `DOCS.md` and in `freeze.py`'s finding, that demand-driven
|
||||
discharge is bounded by the pack's own cut-out on purpose, and close the
|
||||
question.
|
||||
|
||||
- **Protects:** the whole point of the product. Every watt the loop discharges is
|
||||
self-consumption the house would otherwise have imported; a reserve is
|
||||
literally energy bought at the import tariff and held back.
|
||||
- **Costs:** on a heavy evening the pack ends at the BMS cut-out with no EMS-side
|
||||
record of why. That is the SoC-drift condition **MAINT-01** exists to correct,
|
||||
and the first symptom — a battery that is never available when it is wanted —
|
||||
is indistinguishable from a coulomb counter that has drifted. It also means the
|
||||
morning's peak-guard capacity is whatever last night left, which the peak guard
|
||||
cannot influence.
|
||||
- **Cost of building it:** zero. It is already the shipped behaviour, and after
|
||||
SAFETY-25's honesty half it is already documented.
|
||||
|
||||
### Option B — a `hi` limit at `P_LOOP`, with an enforced ordering *(recommended)*
|
||||
|
||||
A new option `loop_soc_floor`. While `soc <= loop_soc_floor`, `main.py` files
|
||||
`Claim.limit("reserve", P_LOOP, hi=0.0)`. Zero forbids **discharge** and permits
|
||||
charging, which is the mirror image of the guard's `lo = 0` and one-directional
|
||||
in the safe direction.
|
||||
|
||||
**⚠️ This shape has one trap and it is fatal if missed.** `arbiter.resolve()`
|
||||
applies **every** limit at or above the winning `set` claim's priority and takes
|
||||
the most restrictive, *with no notion of one limit outranking another* — that is
|
||||
deliberate and is what makes the safety bounds unconditional. So when the loop
|
||||
wins at `P_LOOP`, a reserve `hi = 0` and the peak guard's `lo = excess > 0` are
|
||||
**both** applied, `lo > hi`, and the arbiter resolves a **CONTRADICTION to 0 W**:
|
||||
the battery parked, in the one quarter of the month that sets the bill. This is
|
||||
the same crossing-limits hazard `shaping_suspended()` already exists to avoid for
|
||||
the maintenance charge-only clamp.
|
||||
|
||||
**The fix is an ordering constraint, and it is provable:** require
|
||||
|
||||
bms_soc_floor < loop_soc_floor <= peak_soc_floor
|
||||
|
||||
Then whenever the reserve binds (`soc <= loop_soc_floor <= peak_soc_floor`) the
|
||||
guard is *already* floor-limited and files `lo = 0.0`, so `lo == hi == 0` and the
|
||||
result is 0 W with no contradiction. Refuse any other ordering at startup, in
|
||||
CFG-01's manner and with rule 8's message shape. **A `loop_soc_floor` above
|
||||
`peak_soc_floor` must not be merely discouraged; it is the parked-battery bug.**
|
||||
|
||||
- **Protects:** the pack from routinely sitting on its own cut-out, which is the
|
||||
MAINT-01 drift condition; and it gives the operator one number that means what
|
||||
its name says.
|
||||
- **Costs:** a fifth SoC key (see §4), a validator rule, and — the real cost —
|
||||
**every watt below the reserve becomes billed import.** Set too high it turns a
|
||||
working battery into a smaller one.
|
||||
- **What it does *not* touch, correctly:** a maintenance DRAIN sets at
|
||||
`P_MAINTENANCE` 60 and arbitrage sets at `P_ARBITRAGE` 30, both above `P_LOOP`
|
||||
10, so a limit filed at `P_LOOP` is not applied to either. The monthly
|
||||
recalibration still drains to `maintenance_soc_floor`; arbitrage is still
|
||||
bounded by its own key. That is the right answer and it falls out of the
|
||||
priorities rather than needing a special case.
|
||||
- **Recommended starting value if this option is taken:** a *low* one — three
|
||||
points above `bms_soc_floor`, i.e. **13 %**, well under `peak_soc_floor`'s 20.
|
||||
The purpose is to keep the pack off its own cut-out, **not** to reserve energy
|
||||
for anything, and an over-tight reserve is the version of this that fights
|
||||
MAINT-01 from the other side: it shrinks the band the pack actually cycles in,
|
||||
which is the condition a coulomb counter drifts in. It does not matter that 13
|
||||
sits above `maintenance_soc_floor`'s 11 — the maintenance drain sets at
|
||||
`P_MAINTENANCE` 60 and a `P_LOOP` limit is not applied to it, so the two never
|
||||
interact. **The number itself is part of the owner's answer**; what this memo
|
||||
offers is the derivation and the ordering constraint that makes any number in
|
||||
that range safe.
|
||||
|
||||
### Option C — a `set` claim above `P_PEAK`
|
||||
|
||||
File `Claim.set("reserve", 55, 0.0)` when the pack is under the reserve. Because
|
||||
clause 2 applies only limits at or **above** the winner's priority, the guard's
|
||||
`lo` at 50 would then be dropped and there is no contradiction to engineer
|
||||
around.
|
||||
|
||||
- **Protects:** the same as B, without the ordering rule.
|
||||
- **Costs:** it is a **stop**, not a bound. It parks the battery outright rather
|
||||
than merely forbidding discharge, so it also blocks the charging that would end
|
||||
the condition, and it silently outranks peak shaving in a way that is invisible
|
||||
on the priority table. This project's rule is that a floor about **energy** is
|
||||
not a stop of last resort (`peakguard.py`, point 1). **Not recommended.**
|
||||
|
||||
### Option D — clamp inside `control.compute()`
|
||||
|
||||
- **Costs:** it puts precedence back inside a strategy, which is the exact thing
|
||||
`arbiter.py` was built to end, and it would be invisible to `explain()`. **Not
|
||||
recommended.**
|
||||
|
||||
## 6. Recommendation
|
||||
|
||||
⚠️ **This section is the recommendation that was PUT to the owner, kept as
|
||||
written. It was answered on 2026-09-02 — see §0. The owner took Option A and
|
||||
deferred Option B to `ALLOC-01`; item 3 below (keep the part 10 tripwire)
|
||||
was taken as written and still stands.**
|
||||
|
||||
**Option A is honest and cheap; Option B is what I would build.** Concretely:
|
||||
|
||||
1. **Now (shipped with SAFETY-25):** the honesty half. `peak_soc_floor`, its
|
||||
documentation and the status page say plainly that it bounds the peak guard
|
||||
only. This is required under every option and it is the actual dishonesty on
|
||||
the live system today.
|
||||
2. **Owner's call:** A or B. If B, take it **after `SAFETY-27`'s naming decision**
|
||||
so the fifth key lands into a scheme rather than onto a pile, and **after
|
||||
`MAINT-01`** has run one real cycle — until then nobody has observed what this
|
||||
pack's SoC reading does over a full cycle, and picking a reserve against a
|
||||
reading that has never been recalibrated is picking a number against an
|
||||
instrument we have not checked.
|
||||
3. **Whichever way:** the tripwire in `test_peakguard.py` part 10 stays until the
|
||||
question is answered, so the day someone builds a loop-side floor it goes red
|
||||
and has to be updated deliberately, rather than the exposure quietly changing
|
||||
under a green suite. It has two halves and they cover the two places the floor
|
||||
can land:
|
||||
|
||||
- **10f pins the claim-source set.** Every `claims.append(...)` in
|
||||
`Controller.cycle()` is read off its AST and must be one of eight named
|
||||
sources, and real cycles — spied at main.py's own `resolve`, swept over the
|
||||
whole 0–100 % SoC range in both the idle and the floor-limited state — must
|
||||
file exactly those. **Option B is a ninth source**, and so is **Option C**'s
|
||||
`set` claim, so filing either takes part 10 red on the line it is written.
|
||||
**Option A** files no claim at all — it is the honesty half already
|
||||
shipped, and part 10 is the record it leaves behind.
|
||||
- **10a–10c replay the shipped code**, so **Option D** — a clamp inside
|
||||
`control.compute()` — moves the replayed numbers instead.
|
||||
|
||||
⚠️ **10f is load-bearing and was added late.** PR #31 shipped this section
|
||||
claiming the tripwire without it, and the reviewer disproved the claim by
|
||||
building Option B in `main.py`: the entire suite, part 10 included, stayed
|
||||
green, and mutation 13 went on printing *"nothing prevents it, on purpose"* on
|
||||
a tree where something did. Do not remove 10f while this question is open.
|
||||
|
||||
## 7. What the replay is and is not
|
||||
|
||||
The committed captures carry **one** series — signed net power at the meter — so
|
||||
the pack is modelled, and the model is stated rather than hidden:
|
||||
|
||||
- the captured `w` is the load presented to the meter; the modelled battery's
|
||||
delivered power is subtracted from it, one telegram late (an actuation delay);
|
||||
- the loop's command is the **shipped** `control.compute()` at the shipped
|
||||
tuning, resolved through the **shipped** `arbiter.resolve()` against the
|
||||
**shipped** `peakguard.claim()`, at a `cycle_floor_s` tick;
|
||||
- SoC falls by the delivered discharge integrated over the real telegram
|
||||
timestamps, on a pack of 300 Ah × 51.2 V × DoD 90;
|
||||
- the BMS is modelled as a hard cut: at or below `bms_soc_floor` the modelled
|
||||
battery delivers 0 W whatever is asked of it. Without that the run would be
|
||||
unphysical — the BMS really does stop the pack, and the whole finding is that
|
||||
it is then the **only** thing that does;
|
||||
- nothing recharges the pack inside the window. One evening, one direction.
|
||||
|
||||
**The fixtures cannot express a low pack on their own** — there is no battery or
|
||||
SoC telemetry in them — so the starting state of charge is a fixture parameter,
|
||||
not a measurement. It is chosen as *one point above `peak_soc_floor`*, which is
|
||||
derived from the shipped option rather than picked. Everything downstream of that
|
||||
one number is the real capture and the real code.
|
||||
@@ -430,7 +430,7 @@ help - see "Why the tuning is what it is".
|
||||
|---|---|
|
||||
| `peak_forecast_entity` | Quarter-hour demand forecast, for capacity-tariff markets. Empty = no cap |
|
||||
| `peak_cap_w` | The site's capacity-tariff target |
|
||||
| `peak_soc_floor` (20) | **The percent below which the capacity-peak guard will not discharge the battery.** Not optional and not the same thing as `maintenance_soc_floor` — see below |
|
||||
| `peak_soc_floor` (20) | **The percent below which the capacity-peak guard will not discharge the battery.** ⚠️ It bounds **the peak guard only** — it is **not a pack-wide reserve**, and ordinary self-consumption discharges straight past it (SAFETY-25, see below). Not optional and not the same thing as `maintenance_soc_floor` |
|
||||
| `bms_soc_floor` (10) | The pack's **own** cut-out percent, the number the BMS enforces whatever you set above. `peak_soc_floor` must be **strictly above** it or the add-on refuses to start |
|
||||
| `price_now_entity`, `price_avg_entity` | Dynamic tariff. Empty = never force a paid grid top-up |
|
||||
|
||||
@@ -552,8 +552,13 @@ exactly like the SoC drift the monthly maintenance cycle exists to correct.
|
||||
- **`peak_soc_floor` (20 %)** is where the forced discharge stops. Below it the
|
||||
guard files a **0 W** floor instead of a sized one: charging stays blocked
|
||||
(that can only ever lower your offtake), and no further discharge is asked for.
|
||||
- **It does not stop the ordinary self-consumption loop.** That loop still has no
|
||||
SoC guard of its own. This bounds what the *peak guard* spends for money.
|
||||
- **⚠️ IT BOUNDS THE PEAK GUARD ONLY. IT IS NOT A PACK-WIDE RESERVE, AND THE NAME
|
||||
READS LIKE ONE.** The ordinary self-consumption loop — the grid-following
|
||||
control law that holds your meter at zero — has **no SoC floor of any kind**.
|
||||
It will discharge straight past this number and keep going until the pack's own
|
||||
BMS cut-out stops it. What you are promised by `peak_soc_floor: 20` is *"the
|
||||
capacity-peak guard will not spend the pack for money below 20 %"*, and
|
||||
**nothing more**. See below for what that costs on a real evening.
|
||||
- **When it binds you are told**, once per episode, with notification
|
||||
`goodwe_peak_soc_floor` and a status-page row reading `PEAK GUARD
|
||||
FLOOR-LIMITED`: the quarter **will** go over the ceiling, so shedding load is
|
||||
@@ -572,6 +577,59 @@ Why 20 %: the reference pack is 13.8 kWh usable, so 10 points of margin over the
|
||||
BMS cut-out is about 1.6× the guard's worst measured day. If your pack is
|
||||
smaller, or your quarters are worse, raise it.
|
||||
|
||||
#### ⚠️ What `peak_soc_floor` does **not** protect (SAFETY-25)
|
||||
|
||||
**On a sustained-load evening this add-on will take your battery to the BMS
|
||||
cut-out, whatever `peak_soc_floor` says.** That is measured, not argued. Replayed
|
||||
on the committed 2026-08-20 capture, 19:00–22:00 UTC — three hours of house load
|
||||
after the sun has gone, 830 W average, not one watt of export in the window — with
|
||||
the 13.8 kWh reference pack started at 21 %, one point above the shipped floor:
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| pack at the start of the evening | **21 %** (one point above `peak_soc_floor`) |
|
||||
| pack three hours later | **10.0 %** — the `bms_soc_floor` cut-out |
|
||||
| energy the loop took out | **1525 Wh** |
|
||||
| control cycles below `peak_soc_floor` | **549 of 587**, and **343** of those still delivering discharge |
|
||||
| cycles on which the peak guard filed *any* floor | **0** |
|
||||
| same replay at `peak_soc_floor` = 5, 11, 20, 60 | **the same 10.0 %, to four decimal places** |
|
||||
|
||||
That last row is the point: **this is a property of the control law, not a value
|
||||
you can configure.** Raising `peak_soc_floor` to 60 % changes nothing at all,
|
||||
because the guard it bounds is not the thing doing the discharging.
|
||||
|
||||
**And the two can happen in the same cycle.** On the high-load block of the same
|
||||
day (15:00–17:00 UTC) with the pack below the floor, the guard reports
|
||||
`PEAK GUARD FLOOR-LIMITED` — *"commanding no forced discharge"* — on 49 cycles,
|
||||
and on **all 49 of them** the loop is simultaneously being granted a discharge of
|
||||
up to 2000 W by the arbiter. The status page is telling you the truth about the
|
||||
guard while the battery empties.
|
||||
|
||||
**Why it is built this way, and why SAFETY-24 could not fix it.** The peak guard
|
||||
files a `lo` limit — a *lower* bound on the setpoint. That asymmetry is exactly
|
||||
what makes the guard safe: it is provably incapable of lowering a target, capping
|
||||
a discharge or contradicting the arbiter. The same property makes it incapable of
|
||||
stopping a discharge the loop itself wants. A floor on the guard cannot become a
|
||||
floor on the pack by being raised.
|
||||
|
||||
**Is this a runaway?** No. Self-consumption discharge is demand-driven and
|
||||
self-limiting: it stops when the house stops drawing, and every watt of it is
|
||||
serving load you would otherwise have imported. It is not SAFETY-18's frozen-meter
|
||||
rail. What it means is that the *depth* your pack reaches on a heavy evening is
|
||||
set by your house, not by any number in this file, and the BMS is the only thing
|
||||
underneath it.
|
||||
|
||||
**This is now a recorded decision, not an open question.** On **2026-09-02** the
|
||||
product owner took **Option A**: the BMS cut-out is **deliberately** the only
|
||||
backstop for demand-driven discharge, and a loop-side reserve floor is
|
||||
**deferred** rather than rejected. The options, their costs, the measured replay
|
||||
and the reasoning are in
|
||||
[`DECISIONS/SAFETY-25-loop-soc-floor.md`](DECISIONS/SAFETY-25-loop-soc-floor.md),
|
||||
together with the revisit trigger (`ALLOC-01`, the host-side share allocator)
|
||||
under which a reserve becomes safe to build. **Nothing about the behaviour above
|
||||
changed** — Option A is what has always shipped. What changed is that this
|
||||
section now describes a choice somebody made, and you can read why.
|
||||
|
||||
### The winding-loop alarm (the output clamp)
|
||||
|
||||
Every setpoint this add-on writes is clamped to `max_w` before it leaves the
|
||||
@@ -640,7 +698,18 @@ The add-on alarms when **both** of these are true at once:
|
||||
|
||||
- the meter's own document (power figure *and* both kWh registers) has not
|
||||
changed for `meter_freeze_s` — 300 s by default; **and**
|
||||
- the command standing on the wire is at the rail, within 5 % of `max_w`.
|
||||
- the command standing on the wire is at the rail, within 5 % of the ceiling
|
||||
the command can actually reach.
|
||||
|
||||
**That ceiling is `min(max_w, the setpoint device's own rating)`, not `max_w`.**
|
||||
The emitted command is clipped to the device's reported range as well as to
|
||||
`max_w`, so on a 4700 W inverter configured with `max_w: 5000` a rail measured
|
||||
at 4750 W is one the command can never stand at — the guard could not fire, and
|
||||
the status page said `armed` anyway. It now measures the rail against the
|
||||
smaller number and the page names it, saying *"below max_w because …"* when the
|
||||
device is what capped it. (On an install that started, the two are equal: a
|
||||
`max_w` above the device rating is refused at startup. This matters when the
|
||||
rating could not be read at boot — see below.)
|
||||
|
||||
Neither half is usable alone. A bare "unchanged for N seconds" rule false-trips
|
||||
at the exact operating point this controller aims for — at a converged −10 W a
|
||||
@@ -666,6 +735,13 @@ that reads the meter's own document; on `ha_dsmr`, `mqtt_p1`, `ha_signed` and
|
||||
`off` there is no signal to threshold and the status page says **NOT COVERED**
|
||||
rather than pretending the guard is armed.
|
||||
|
||||
The same row appears for a second reason: a setpoint device that reports a range
|
||||
from which no command magnitude is available in both directions leaves no rail
|
||||
to measure at all, and a 0 W rail would be satisfied by *every* command. That is
|
||||
reported as **NOT COVERED** too, and the detector stays silent rather than
|
||||
degenerating into the bare "unchanged for N seconds" rule this design exists to
|
||||
avoid.
|
||||
|
||||
| option | default | meaning |
|
||||
|---|---|---|
|
||||
| `meter_freeze_s` | 300 | Seconds of an unchanged measurement, *while the command is at the rail*, before the alarm |
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
# Mutation runs in this repository — and the one way they lie
|
||||
|
||||
Nearly every safety claim in this add-on was established the same way: change
|
||||
the shipped module, run the suites, watch one go **red**, put the module back,
|
||||
watch it go **green**. There is no coverage tool here and there is not meant to
|
||||
be — the check that matters is whether a *check* notices when the behaviour it
|
||||
names is removed.
|
||||
|
||||
That method has exactly one silent failure mode, and TEST-15 exists because we
|
||||
walked into it.
|
||||
|
||||
## The defect
|
||||
|
||||
FCST-03's developer reverted `self.provisional` to `here.provisional`, re-ran,
|
||||
and reported the mutation as a **survivor**. It was not. CPython decides a
|
||||
cached `.pyc` is still valid from two numbers:
|
||||
|
||||
* the source file's **size in bytes**, and
|
||||
* the source file's **mtime truncated to whole seconds**.
|
||||
|
||||
`self` and `here` are the same length, and the revert happened in the same
|
||||
second as the edit. Neither number moved, so the interpreter loaded the
|
||||
bytecode it already had. Confirmed at the time by disassembly: **the source read
|
||||
`here`, the running code loaded `self`.** The suite had graded code that was not
|
||||
there — no error, no warning, exit status 0.
|
||||
|
||||
The same collision, in the other direction, can leave a **red** standing on
|
||||
correct source after a revert that never took.
|
||||
|
||||
### Which way it lies, and why that scopes everything
|
||||
|
||||
A mutation that never took effect leaves the suite **green**, and a green run of
|
||||
a mutated tree is reported as a survivor. So stale bytecode **manufactures
|
||||
survivors**; it cannot manufacture a red. The false-red case exists but
|
||||
announces itself, because a developer chases a failure they cannot explain.
|
||||
|
||||
Two consequences, and both are used below:
|
||||
|
||||
* a recorded **"all red, no survivors"** result is not at risk from this defect;
|
||||
* a recorded **survivor** — and a recorded *zero*, such as a coverage-audit
|
||||
count of 0 — is exactly what this defect produces.
|
||||
|
||||
`test_control.py`'s coverage-audit table says the same thing in its own terms:
|
||||
the error is one-directional, so every figure there is a lower bound at worst.
|
||||
|
||||
## The rule
|
||||
|
||||
**Purge `__pycache__` before every mutation run.** Not afterwards, not usually,
|
||||
not when the edit looks big enough.
|
||||
|
||||
```sh
|
||||
cd goodwe_controller
|
||||
tools/mutation_run.sh # every test_*.py in this directory
|
||||
tools/mutation_run.sh . test_tariff.py # or just the ones you are watching
|
||||
tools/mutation_run.sh "$GOODWE_ADDON_REPO/goodwe_controller" # from elsewhere
|
||||
```
|
||||
|
||||
The harness purges, prints a `sha256`/byte-count fingerprint of every `app/*.py`
|
||||
it is about to grade, runs each suite under `python3 -B`, and fails if a cache
|
||||
appeared during the run. Diff two fingerprints and the file you mutated is the
|
||||
line that changed — which is also how a mutation report proves *which source*
|
||||
produced it.
|
||||
|
||||
### What does **not** fix this
|
||||
|
||||
| | writes bytecode | reads a stale `.pyc` |
|
||||
|---|---|---|
|
||||
| `python3 -B` | no | **yes** |
|
||||
| `PYTHONDONTWRITEBYTECODE=1` | no | **yes** |
|
||||
| purging `__pycache__` | (unchanged) | **no — nothing to read** |
|
||||
|
||||
Both flags are *write-side only*. A mutation run always has a cache already,
|
||||
because the previous run wrote it, so a harness that only adds `-B` closes
|
||||
nothing. This is measured, not read off documentation: `test_bytecode.py`
|
||||
part 2 arranges the collision and shows both flags still running the old code.
|
||||
|
||||
`-B` is still worth passing — it stops **this** run leaving a cache for the
|
||||
**next** edit to inherit, which is the one nobody is thinking about three
|
||||
mutations into a batch. Purge for this run, `-B` for the next one.
|
||||
|
||||
### And not a `sleep`
|
||||
|
||||
One-second mtime resolution is the *mechanism*, not the enemy. Waiting out the
|
||||
clock would slow every run down, and would still only cover the edit somebody
|
||||
remembered to slow down. Stop trusting mtime instead.
|
||||
|
||||
## Reporting a mutation
|
||||
|
||||
State the things a reviewer cannot reconstruct afterwards:
|
||||
|
||||
1. **the byte delta** of the mutated file (`+5 B`, `+0 B`). `+0 B` is the risky
|
||||
one — say so;
|
||||
2. **that the mutated line was on disk** when the run started (the harness
|
||||
fingerprint, or a `grep` of the line);
|
||||
3. **which suite went red, and on which named check** — "the suite is red" and
|
||||
"the check that watches this is red" are different claims;
|
||||
4. for a **survivor**, that the run was purged. An unpurged survivor is not a
|
||||
result.
|
||||
|
||||
## The other thing a mutation sweep cannot see: masking (TEST-16)
|
||||
|
||||
Stale bytecode is not the only way a survivor lies. **Two guards can mask each
|
||||
other**, and a sweep that mutates one line at a time is structurally blind to it.
|
||||
|
||||
TEST-16 is the worked example. `static_tariff.arbitrage()` refuses a
|
||||
one-firm-hour series at `len(firm) < 2`, and refuses a flat series at
|
||||
`spread == 0.0`. A single firm hour *also* has a spread of zero. So:
|
||||
|
||||
* weaken the firm-pair rung alone → the flat rung refuses the stimulus anyway;
|
||||
* weaken the flat rung alone → the tiny-spread stimulus is still refused, just
|
||||
for the wrong reason;
|
||||
* and the suite, grading `kind == "refused"`, reports **nothing either way**.
|
||||
|
||||
Both rungs could then be weakened *together* and still nothing would report —
|
||||
which is precisely the state in which the next edit to either one opens a real
|
||||
hole. It survived four rounds of review on TARIFF-03 and FCST-03.
|
||||
|
||||
Two rules come out of it, and both are cheap:
|
||||
|
||||
1. **Grade the reason, not just the verdict.** "Refused" and "refused for the
|
||||
right reason" are different claims, and a masked rung is the case where the
|
||||
first is true and the second is false. A refusal sentence is what the
|
||||
operator reads; it is also the only observable that moves when one rung
|
||||
quietly absorbs another's work.
|
||||
2. **When two rungs can answer the same stimulus, mutate them together.** One
|
||||
extra run per suspected pair. If a sweep finds two survivors in the same
|
||||
function, that pair is the first thing to try — TEST-16's two survivors were
|
||||
adjacent lines in one function and neither was individually live.
|
||||
|
||||
## Where each surface stands
|
||||
|
||||
* **Local and dev-harness runs — the exposed one.** This is where FCST-03 hit
|
||||
it. `goodwe_controller/__pycache__` and `app/__pycache__` are gitignored and
|
||||
are sitting in most working trees right now. Use the harness.
|
||||
* **CI — structurally immune, and it was before this card.** `.gitea/workflows/
|
||||
checks.yml` bind mounts the checkout `-v "$WS:/w:ro"`, so the interpreter
|
||||
cannot write a `__pycache__` into the tree under test at all; measured for
|
||||
TEST-15, and it fails *silently* — no error, exit status 0. Each job also
|
||||
`rm -rf`s its workspace and clones afresh, so nothing crosses between jobs on
|
||||
the shared runner. `PYTHONDONTWRITEBYTECODE=1` is now set there too, as belt
|
||||
and braces: the `:ro` is one character wide and the next person debugging a
|
||||
write will be tempted by it.
|
||||
* **The shipped add-on — not affected, and this is closed.**
|
||||
`goodwe_controller/Dockerfile` has carried `PYTHONDONTWRITEBYTECODE=1` since
|
||||
it was written. There is no deploy-side finding here; do not re-open it.
|
||||
* **The infra repo's `sim/` harnesses — exposed, and NOT fixed by this card.**
|
||||
`sim/replay_sign.py` and friends import the add-on out of
|
||||
`$GOODWE_ADDON_REPO` and write `__pycache__` into *both* trees
|
||||
(`goodwe/sim/__pycache__` exists today). SAFETY-02's headline validation is a
|
||||
replay, not a suite, so a mutation graded through it carries the same
|
||||
exposure. `tools/mutation_run.sh` takes the tree to purge as its first
|
||||
argument precisely so that repo can call it, but the change belongs in that
|
||||
repo and some of those harnesses want the rig. **Anyone mutating a module
|
||||
graded by a replay must purge both trees by hand until then.**
|
||||
|
||||
## Survey — mutation claims of 2026-08-25 … 2026-09-01
|
||||
|
||||
Scoped **by the property, not by re-running everything**. A claim is at risk
|
||||
only if a mutation could have preserved the file's byte count *and* been
|
||||
reverted inside the same second, *and* the claim is of the kind stale bytecode
|
||||
can fabricate (see "which way it lies"). Sources: `git log release/1.0` and the
|
||||
commit and PR bodies.
|
||||
|
||||
| claim | verdict | why |
|
||||
|---|---|---|
|
||||
| **FCST-03** M9 `self.provisional`→`here.provisional` (dd40c56, 71cd784) | **re-verified** | this is the original false survivor. Re-run with the cache cleared, M9 is caught. The shipped source was correct throughout. |
|
||||
| **FCST-03** X1, X6 degenerate stimuli (71cd784) | **not at risk** | run after the purge discipline landed in that branch. |
|
||||
| **SAFETY-24** 11 author + 9 reviewer mutations (e709554, 4601682) | **not at risk** | the commit records them run under `python -B` with a purged `__pycache__` and real byte deltas. Its one survivor is an equivalent mutant, argued structurally rather than by a green run. |
|
||||
| **SAFETY-26** tolerance sweep over `arbitrage.py` and `static_tariff.py`, 2 survivors (2b8b8cb) | **not at risk** | purge, printed `+5 B` delta, mutated line asserted present, tree re-read before each run. One survivor is explicitly recorded at `+0 B` — the risky delta — and was produced *under* the purge. **Both survivors are now closed by TEST-16** (`test_static_tariff.py` section 9), which also found that the two of them *masked each other* — each was individually non-live only because the other rung caught its stimulus, an arrangement single-mutation testing cannot see. Its own ledger is 7 mutations, 4 of them at `+0 B`, all red. |
|
||||
| **OPT-04** mutations reported on PR #22 (bdd7f18) | **not at risk** | `test_arbitrage.py`'s header records the exact command: purge, then `python3 -B`. |
|
||||
| **TEST-17** `checks()` dropping `when` (504e8da) | **not at risk** | a *red* claim, and dropping an argument changes the file length. Neither half of the collision is available. |
|
||||
| **SAFETY-07** wiring mutations B1/B2/B3 and `test_peakguard.py` parts 7 and 10 (2d570d8, e7c95bf) | **not at risk** | those mutations are **executed in-process**, monkeypatched onto the imported module. No source file is edited, so no `.pyc` is consulted. |
|
||||
| every **"all red, no survivors"** claim in the window — TARIFF-02 (24/0), TARIFF-03 (11), MAINT-04 (10), SAFETY-18 (6+4), SAFETY-03 (6), TEL-04 (10), TEL-05 (6) | **not at risk** | direction. Stale bytecode turns a red into a green survivor, never the reverse. A red is evidence that *something* changed under the check. |
|
||||
| **TEST-06**'s deleted assertion, "no new notification while parked at 0 W" (c34b5a2) | **not at risk / superseded** | it was recorded as undecidable and then *falsified* — `test_freeze.py` records the one-line mutation that takes the file red 9 times. The stronger later claim is a red one. |
|
||||
| **TARIFF-01** reviewer survivor: `record_block()` ignoring its `policy` argument (0dbd485) | **re-verified — still a survivor** | re-run here through `tools/mutation_run.sh` against the 15 suites that were on the record, all green with `billed_w(block, policy)` mutated to `billed_w(block, POLICY_NET)`. The recorded diagnosis holds: every block reaching the store is single-phase, where NET, SUM and MAX collapse. **Now CLOSED by TEST-13** (`test_tariff.py` section 7), which round-trips section 7's own unbalanced `(3000, 500, -200) W` block THROUGH the store under each policy - three distinct banked figures, so a hardcoded policy takes at least two of them red. Third instance of "a stimulus evaluated where the quantity it grades is degenerate", after WITNESS-02's span normalisation and TARIFF-01's own DST window. |
|
||||
| **SAFETY-25** 8 mutations against `test_peakguard.py` part 10, then 9 more after review, all red | **not at risk** | each run against a tree copied fresh with `__pycache__` excluded and mounted `:ro`, so no `.pyc` existed to go stale - the same structural immunity recorded for CI above. Byte deltas recorded on the PR; none is `+0 B`. All are **reds**, which is the direction this defect cannot fabricate. ⚠️ The second round exists because the first round's mutations were all aimed at DISARMING the guard, and the claim part 10 actually made was about the guard being FIXED - the reviewer built the fix and the suite stayed green. Bytecode was never the issue there; an unaimed battery was. |
|
||||
| **SAFETY-03** reviewer survivor: `abs()` dropped from `clamp_to_rating`'s limit (6aabb83) | **re-verified — still a survivor** | re-run the same way, all 15 green. Also as recorded: unreachable under the `int(100, 5000)` schema. |
|
||||
| **TARIFF-01**'s other three survivors, **SAFETY-03**'s `describe()` survivor, **TARIFF-02**'s M3/M5/M7, **SAFETY-18**'s three | **still unverified** | recorded before the purge discipline, with no byte delta on the record, so a `+0 B` same-second revert cannot be excluded. All are survivors, which is the direction this defect fabricates. TARIFF-02's and SAFETY-18's were **closed by later commits whose claims are reds**, so what is unverified is the *diagnosis*, not the current state of the code. |
|
||||
|
||||
**Nothing here says a past result is wrong.** The two survivors re-run above
|
||||
both stood. What changed is that they are now on the record as measured rather
|
||||
than assumed, and the rest are labelled honestly. The still-unverified rows are
|
||||
cheap to close — one harness run each — and the right moment is when somebody
|
||||
next touches that module, not in a re-run campaign nobody will read.
|
||||
@@ -46,8 +46,18 @@ the validation did not run or no longer holds - `hass.limits()` returns
|
||||
(None, None) whenever ESPHome is not up yet, and the range checks are skipped
|
||||
rather than guessed at - and that is a louder fault than the first stage, not a
|
||||
quieter one. It therefore alarms too, through the same channel, with the bound
|
||||
named. This is NOT SAFETY-20; nothing here changes what `freeze.py` measures its
|
||||
rail against.
|
||||
named.
|
||||
|
||||
⚠️ SAFETY-20 UPDATED THE SECOND HALF OF THAT SENTENCE. It used to read "this is
|
||||
NOT SAFETY-20; nothing here changes what `freeze.py` measures its rail against",
|
||||
and that was true of this module and false of the system: this stage is exactly
|
||||
what clips the emitted command below `RAIL_FRAC * max_w`, which is how a device
|
||||
rating disarmed the freeze detector while the page said `armed`. `freeze.py` now
|
||||
takes `dev_min`/`dev_max` and measures its rail against
|
||||
`min(max_w, |dev_min|, |dev_max|)`. THE CLAMP ITSELF IS UNCHANGED - it still
|
||||
clamps to `max_w` first and to the device range second, for the reasons above,
|
||||
and it still does not `min()` the two. What changed is only that the detector
|
||||
downstream now knows this stage exists.
|
||||
|
||||
------------------------------------------------------------------------------
|
||||
WHERE THE WIND ACTUALLY SHOWS UP - READ THIS BEFORE "SIMPLIFYING" THE CALLER
|
||||
|
||||
+181
-15
@@ -18,6 +18,17 @@ THE FAILURE NEEDS NO FAULT ANYWHERE ELSE. A frozen-but-talking meter is
|
||||
- there is no SoC guard on the grid-following loop at all. `soc_floor` belongs
|
||||
to the maintenance cycle; the BMS is the sole energy backstop.
|
||||
|
||||
⚠️ STILL TRUE, AND NOW FILED. SAFETY-24 added `peak_soc_floor` and
|
||||
OPT-04 added `arbitrage_soc_floor`, so the sentence above is no longer
|
||||
"there is one SoC floor and it is maintenance's" - but neither of the new
|
||||
ones binds THIS loop, and `peak_soc_floor`'s name reads as though it does.
|
||||
SAFETY-25 replayed the exposure (test_peakguard.py part 10) and recorded
|
||||
the options in DECISIONS/SAFETY-25-loop-soc-floor.md. DECIDED 2026-09-02,
|
||||
Option A: the BMS is the sole energy backstop for demand-driven discharge
|
||||
ON PURPOSE. A loop-side reserve is DEFERRED, not rejected - its revisit
|
||||
trigger is ALLOC-01. So the sentence above is a recorded decision, not an
|
||||
oversight and no longer an open question.
|
||||
|
||||
The loop reads a constant error and integrates it. Time from freeze to the rail,
|
||||
replaying the real `control.compute()` at 15 s cycles:
|
||||
|
||||
@@ -151,12 +162,77 @@ THE RAIL TERM, PRECISELY
|
||||
reason SAFETY-02 uses the emitted value: the wire carries the emitted number.
|
||||
|
||||
RAIL_FRAC is 0.95 and is a constant rather than an option. The command is
|
||||
quantised to `step_w` (max 100) and clamped to `max_w` (min 100), so at the rail
|
||||
the emitted value IS `max_w` on every schema-legal combination; the 5 % is slack
|
||||
for a device rating that clips `max_w` slightly in `write_setpoint()`, not a
|
||||
tuning knob. Making it configurable would offer a way to widen the one term that
|
||||
quantised to `step_w` (max 100), so at the rail the emitted value IS the ceiling
|
||||
on every schema-legal combination; the 5 % is quantisation slack, not a tuning
|
||||
knob. Making it configurable would offer a way to widen the one term that
|
||||
carries the whole no-false-positive argument.
|
||||
|
||||
⚠️ SAFETY-20 - AND THE CEILING IS NOT `max_w`. THE 5 % USED TO BE DESCRIBED AS
|
||||
"slack for a device rating that clips `max_w` slightly in `write_setpoint()`",
|
||||
AND THAT SENTENCE WAS THE BUG. 5 % of slack does not absorb a device rating; it
|
||||
inverts the guard. `write_setpoint()` clamps the emitted command to `max_w` AND
|
||||
THEN to the setpoint device's own `[dev_min, dev_max]` range (clamp.py,
|
||||
`clamp_to_rating()`), and the arbiter files the same range as a P_SAFETY limit
|
||||
claim, so the largest magnitude that can ever stand on the wire is
|
||||
|
||||
min(max_w, |dev_min|, |dev_max|)
|
||||
|
||||
not `max_w`. Measured on the shipped predicate at `max_w: 5000` against a device
|
||||
of +-4700 - the exact case the ticket is named for:
|
||||
|
||||
looks_frozen(unchanged_s=3600, commanded_w=4700, max_w=5000) -> False
|
||||
|
||||
The command is pinned at the hardware's rail, the meter has been frozen for an
|
||||
hour, and term 2 is unsatisfiable BY CONSTRUCTION because 4700 < 4750. Any
|
||||
device rating at or below `RAIL_FRAC * max_w` disarms the conjunction outright.
|
||||
The status page then printed `armed (...command is over 4750 W)`, which is the
|
||||
"disarmed guard that advertises itself as armed" failure validate.py rule 5 and
|
||||
SAFETY-15/19 all exist to prevent - so `rail_ceiling_w()` below takes the device
|
||||
range and the rail is measured against the smaller number.
|
||||
|
||||
WHY THE SMALLER OF THE TWO DEVICE BOUNDS, AND NOT A SIDE-AWARE PAIR. The rail is
|
||||
a MAGNITUDE test against what clamp.py calls a magnitude clamp - it binds import
|
||||
and export identically - so the ceiling here is a magnitude that is available in
|
||||
BOTH directions. The alternative considered was a per-sign rail:
|
||||
`min(max_w, dev_max)` for a positive command, `min(max_w, |dev_min|)` for a
|
||||
negative one. That is arithmetically tighter and it is NOT wrong - on a device
|
||||
range of -500..+5000 it would grade a -480 W charge command as railed, which the
|
||||
symmetric ceiling reaches only by dropping the discharge rail to 475 W too. It
|
||||
was rejected on cost, not on correctness: a per-sign rail is two rails, and two
|
||||
rails need two coverage verdicts (`dev_min == 0` is a degenerate charge rail
|
||||
whatever the discharge side can do) on a status row that carries one number and
|
||||
in a predicate that takes one magnitude. That is a bigger change than this
|
||||
defect earns, and the ONLY configuration that distinguishes the two - a device
|
||||
range narrower than `max_w` on one side - is refused at startup by CFG-01 (see
|
||||
the reachability note below). Between the two, the symmetric ceiling can only
|
||||
ever LOWER the rail, which widens term 2 rather than disarming it; term 1
|
||||
(`unchanged_s >= hold_s`) is the term carrying the no-false-positive argument,
|
||||
and it is untouched. Whoever needs the tighter version should take both status
|
||||
rows with it.
|
||||
|
||||
⚠️ AND WHEN THE CEILING IS ZERO THE RAIL IS NOT "LOW", IT IS GONE. A device that
|
||||
accepts no command in one direction at all (`dev_max == 0`, or `dev_min == 0`)
|
||||
gives a ceiling of 0 W, and `abs(commanded_w) >= 0` is TRUE FOR EVERY COMMAND
|
||||
INCLUDING 0 W. Term 2 would not be disarmed there, it would be degenerately
|
||||
true, and the detector would collapse into the bare `unchanged_s > N` threshold
|
||||
TEL-05 refused - false-tripping at the converged operating point we aim for.
|
||||
That case is reported as NOT COVERED, through the row the unsupported-transport
|
||||
case already uses, and `looks_frozen()` returns False rather than firing.
|
||||
|
||||
⚠️ HOW REACHABLE IS ANY OF THIS - READ THIS BEFORE "SIMPLIFYING" IT AWAY.
|
||||
`validate_startup_config()` rule 2 (CFG-01) already REFUSES TO START on
|
||||
`max_w > dev_max` or `-max_w < dev_min`, and `run_control()` re-runs that gate
|
||||
once ESPHome is up and the real rating is known. So on any install that reaches
|
||||
the control loop with a rating it could read, `min(max_w, |dev_min|, |dev_max|)`
|
||||
IS `max_w` and everything above is arithmetically dead. That is not an argument
|
||||
against it - it is clamp.py's argument for its own second stage, word for word:
|
||||
the case where this bites is the case where the startup gate did not run or no
|
||||
longer holds (`hass.limits()` returns (None, None) whenever ESPHome is not up,
|
||||
and the range checks are then skipped rather than guessed at, so a rating that
|
||||
arrives late is never re-read), and a guard that quietly assumes the gate ran is
|
||||
a guard that reports armed in exactly the state it cannot fire in. See AC 4's
|
||||
decision, recorded in validate.py under WHAT IS DELIBERATELY *NOT* REFUSED.
|
||||
|
||||
⚠️ NOT GATED ON `following`, and that is deliberate. A maintenance charge
|
||||
commands against the meter on purpose and can sit at the rail for hours - but it
|
||||
does so while pushing kilowatts through the meter, so the FIRST term is what
|
||||
@@ -192,6 +268,8 @@ otherwise would be worse than the gap.
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
|
||||
from .clamp import is_commandable
|
||||
|
||||
# See "THE RAIL TERM, PRECISELY" above. A constant, on purpose.
|
||||
RAIL_FRAC = 0.95
|
||||
|
||||
@@ -203,13 +281,72 @@ class FreezeWatchdogConfig:
|
||||
hold_s: float = 300.0
|
||||
|
||||
|
||||
def rail_w(max_w) -> float:
|
||||
"""The magnitude at or above which a command counts as railed."""
|
||||
return abs(float(max_w)) * RAIL_FRAC
|
||||
def rail_ceiling_w(max_w, *, dev_min=None, dev_max=None) -> float:
|
||||
"""The largest command magnitude that can actually stand on the wire.
|
||||
|
||||
SAFETY-20, and the whole point of the ticket: this is NOT `max_w`. The
|
||||
emitted command is bounded by `max_w` AND by the setpoint device's own
|
||||
`[dev_min, dev_max]` range - twice, in `clamp_to_rating()` and again as the
|
||||
arbiter's `device` P_SAFETY limit claim - so the reachable ceiling is the
|
||||
smallest of the three magnitudes. See "THE RAIL TERM, PRECISELY" for why it
|
||||
is the smaller of the two device bounds rather than a per-sign pair, and for
|
||||
why this is arithmetically dead on any install CFG-01 let start.
|
||||
|
||||
`dev_min` / `dev_max` are `hass.limits()`'s answer and are None whenever
|
||||
ESPHome could not be reached. UNKNOWN IS NOT ZERO: a missing bound means
|
||||
this add-on applies no device clamp at all on that side (clamp.py's second
|
||||
stage is skipped unless BOTH are known), so an unknown bound must not lower
|
||||
the ceiling. `is_commandable()` is write_setpoint()'s own predicate, reused
|
||||
rather than retyped: a NaN rating must not become a 0 W ceiling.
|
||||
|
||||
Returns 0.0 when the device can command nothing - see rail_unreachable().
|
||||
"""
|
||||
ceiling = abs(float(max_w))
|
||||
for bound in (dev_min, dev_max):
|
||||
if is_commandable(bound):
|
||||
ceiling = min(ceiling, abs(float(bound)))
|
||||
return max(0.0, ceiling)
|
||||
|
||||
|
||||
def rail_unreachable(max_w, *, dev_min=None, dev_max=None) -> str:
|
||||
""""" when the rail is a real threshold, else WHY it is not. SAFETY-20 AC2.
|
||||
|
||||
The status page renders this as a NOT COVERED row - the same row, for the
|
||||
same reason, that an unsupported transport already gets. It is a second
|
||||
reason to use that surface, not a new mechanism: in both states the honest
|
||||
report is "this guard is not watching", and the one thing this project has
|
||||
decided repeatedly it will not ship is a page that says `armed` instead.
|
||||
|
||||
⚠️ THE UNREACHABLE CASE IS NOT "THE RAIL IS HIGH", IT IS "THE RAIL IS 0 W".
|
||||
A ceiling of zero makes `abs(commanded_w) >= 0` true for every command
|
||||
including a parked 0 W one, so term 2 is not disarmed but DEGENERATELY TRUE,
|
||||
and the conjunction decays into the bare `unchanged_s > N` threshold TEL-05
|
||||
refused - which false-trips at the converged operating point this controller
|
||||
aims for. Silence plus a NOT COVERED row is strictly better than that.
|
||||
"""
|
||||
if not max_w or not is_commandable(max_w):
|
||||
return (f"max_w is {max_w!r}, so there is no ceiling to measure a rail "
|
||||
f"against")
|
||||
if rail_ceiling_w(max_w, dev_min=dev_min, dev_max=dev_max) > 0.0:
|
||||
return ""
|
||||
return (f"the setpoint device reports a range of {dev_min}...{dev_max} W, "
|
||||
f"which leaves no command magnitude available in both directions, "
|
||||
f"so the rail term would be true of every command including 0 W")
|
||||
|
||||
|
||||
def rail_w(max_w, *, dev_min=None, dev_max=None) -> float:
|
||||
"""The magnitude at or above which a command counts as railed.
|
||||
|
||||
Measured against the REACHABLE ceiling, not against `max_w` - SAFETY-20.
|
||||
Callers that do not know the device range pass none and get the old
|
||||
behaviour, which is correct precisely when there is no device clamp to
|
||||
account for.
|
||||
"""
|
||||
return rail_ceiling_w(max_w, dev_min=dev_min, dev_max=dev_max) * RAIL_FRAC
|
||||
|
||||
|
||||
def looks_frozen(unchanged_s, commanded_w, max_w,
|
||||
cfg: FreezeWatchdogConfig) -> bool:
|
||||
cfg: FreezeWatchdogConfig, *, dev_min=None, dev_max=None) -> bool:
|
||||
"""The predicate, and the ONLY place the conjunction is written down.
|
||||
|
||||
Public for the same reason `watchdog.disagrees()` is: the checks that grade
|
||||
@@ -220,12 +357,28 @@ def looks_frozen(unchanged_s, commanded_w, max_w,
|
||||
`unchanged_s` seconds since the meter served a different measurement, or
|
||||
None on a transport that cannot know (see the module note).
|
||||
`commanded_w` the EMITTED setpoint standing on the wire.
|
||||
`max_w` the configured output bound the rail is measured against.
|
||||
`max_w` the configured output bound.
|
||||
`dev_min` / the setpoint device's own reported range, or None when it
|
||||
`dev_max` could not be read. SAFETY-20: the rail is measured against
|
||||
`min(max_w, |dev_min|, |dev_max|)`, because that - not
|
||||
`max_w` - is what the wire can carry.
|
||||
|
||||
⚠️ THE DEVICE BOUNDS ARE KEYWORD-ONLY AND DEFAULT TO None, WHICH IS THE
|
||||
CONSERVATIVE DIRECTION AND ALSO THE HONEST ONE. A caller that does not know
|
||||
the rating gets a rail measured against `max_w` - correct, because when this
|
||||
add-on has no rating it applies no device clamp either (clamp.py's second
|
||||
stage needs both bounds), so `max_w` really is the ceiling on that path.
|
||||
"""
|
||||
if unchanged_s is None or commanded_w is None or not max_w:
|
||||
return False
|
||||
# SAFETY-20. A ceiling of 0 W would make term 2 true of EVERY command; that
|
||||
# is the degenerate case, not the armed one. Silence, and the status page
|
||||
# says NOT COVERED - see rail_unreachable().
|
||||
if rail_unreachable(max_w, dev_min=dev_min, dev_max=dev_max):
|
||||
return False
|
||||
return (float(unchanged_s) >= cfg.hold_s
|
||||
and abs(float(commanded_w)) >= rail_w(max_w))
|
||||
and abs(float(commanded_w))
|
||||
>= rail_w(max_w, dev_min=dev_min, dev_max=dev_max))
|
||||
|
||||
|
||||
class FreezeWatchdog:
|
||||
@@ -249,24 +402,37 @@ class FreezeWatchdog:
|
||||
self.reason = ""
|
||||
self.episodes = 0
|
||||
|
||||
def evaluate(self, unchanged_s, commanded_w, max_w, now: datetime) -> bool:
|
||||
def evaluate(self, unchanged_s, commanded_w, max_w, now: datetime, *,
|
||||
dev_min=None, dev_max=None) -> bool:
|
||||
"""Advance one cycle. Returns True ONLY on the rising edge.
|
||||
|
||||
`now` is the caller's clock so this stays testable and replayable - the
|
||||
same discipline as `SignWatchdog.evaluate()`.
|
||||
same discipline as `SignWatchdog.evaluate()`. `dev_min`/`dev_max` are
|
||||
the setpoint device's reported range; see looks_frozen().
|
||||
"""
|
||||
if not looks_frozen(unchanged_s, commanded_w, max_w, self.cfg):
|
||||
if not looks_frozen(unchanged_s, commanded_w, max_w, self.cfg,
|
||||
dev_min=dev_min, dev_max=dev_max):
|
||||
self.active = False
|
||||
self.since = None
|
||||
self.reason = ""
|
||||
return False
|
||||
|
||||
# ⚠️ SAFETY-20. THE REASON QUOTES THE CEILING IT ACTUALLY USED, not
|
||||
# `max_w`. The old line said "at the 5000 W rail (... command over
|
||||
# 4750 W)" on an install whose device stopped at 4700 W, i.e. it named
|
||||
# a threshold the command could not reach - the same untruth the status
|
||||
# page was telling, printed into the log and the HA notification where
|
||||
# it would outlive the page.
|
||||
ceiling = rail_ceiling_w(max_w, dev_min=dev_min, dev_max=dev_max)
|
||||
capped = ("" if ceiling >= abs(float(max_w))
|
||||
else f", capped from max_w {float(max_w):.0f} W by the "
|
||||
f"setpoint device's own rating")
|
||||
self.reason = (
|
||||
f"METER_FROZEN: the meter has answered {float(unchanged_s):.0f} s "
|
||||
f"without its measurement changing while the command stands at "
|
||||
f"{float(commanded_w):+.0f} W, at the {float(max_w):.0f} W rail "
|
||||
f"{float(commanded_w):+.0f} W, at the {ceiling:.0f} W rail{capped} "
|
||||
f"(limits: unchanged over {self.cfg.hold_s:.0f} s, command over "
|
||||
f"{rail_w(max_w):.0f} W)")
|
||||
f"{rail_w(max_w, dev_min=dev_min, dev_max=dev_max):.0f} W)")
|
||||
if self.active:
|
||||
return False
|
||||
self.active = True
|
||||
|
||||
+154
-28
@@ -42,7 +42,7 @@ from .clamp import (
|
||||
is_commandable,
|
||||
)
|
||||
from .freeze import (
|
||||
FreezeWatchdog, FreezeWatchdogConfig, looks_frozen, rail_w,
|
||||
FreezeWatchdog, FreezeWatchdogConfig, looks_frozen, rail_unreachable, rail_w,
|
||||
)
|
||||
from .hass import HomeAssistant
|
||||
from .maintenance import IDLE, MaintConfig, Maintenance
|
||||
@@ -131,19 +131,16 @@ class Controller:
|
||||
integrator_max_w=(float(opts["integrator_max_w"])
|
||||
if opts.get("integrator_max_w") else None),
|
||||
)
|
||||
self.maint = Maintenance(
|
||||
MaintConfig(
|
||||
enabled=bool(opts.get("maintenance_enabled", False)),
|
||||
interval_days=int(opts.get("maintenance_interval_days", 28)),
|
||||
start_hour=int(opts.get("maintenance_start_hour", 10)),
|
||||
discharge_w=float(opts.get("maintenance_discharge_w", 2500)),
|
||||
charge_w=float(opts.get("maintenance_charge_w", 2500)),
|
||||
soc_floor=float(opts.get("maintenance_soc_floor", 11)),
|
||||
soc_target=float(opts.get("maintenance_soc_target", 99)),
|
||||
hold_min=int(opts.get("maintenance_hold_min", 120)),
|
||||
),
|
||||
store,
|
||||
)
|
||||
# ⚠️ CFG-03. EIGHT `opts.get(key, <literal>)` CALLS USED TO LIVE HERE,
|
||||
# and two of those literals disagreed with config.yaml - 2500 against a
|
||||
# shipped 2000, which is a config validate.py refuses. The read now
|
||||
# belongs to `MaintConfig.from_options()`, next to the one in-code
|
||||
# mirror of config.yaml it falls back to, so this file states no opinion
|
||||
# at all about what a missing maintenance key means. Read
|
||||
# maintenance.MAINT_OPTION_DEFAULTS before adding a ninth key: it goes
|
||||
# in config.yaml's `options:` and `schema:` blocks and in that dict, and
|
||||
# nowhere else.
|
||||
self.maint = Maintenance(MaintConfig.from_options(opts), store)
|
||||
|
||||
# SAFETY-02. One instance, one actuator, one cadence - see watchdog.py.
|
||||
#
|
||||
@@ -240,10 +237,14 @@ class Controller:
|
||||
# knows, and refusing one set below the pack's own cut-out means knowing
|
||||
# that cut-out too. So this card adds exactly two keys and reads their
|
||||
# defaults from `peakguard.PEAK_OPTION_DEFAULTS` - TARIFF-02's mirror
|
||||
# pattern - rather than typing literals here. THAT is what keeps CFG-03
|
||||
# at three places: the divergence validate.py's rule 6 documents
|
||||
# (`maintenance_charge_w` 2000 there, 2500 here) is exactly what a
|
||||
# literal in this file would repeat.
|
||||
# pattern - rather than typing literals here. THAT is what kept this
|
||||
# card from widening: the divergence validate.py's rule 6 used to
|
||||
# document (`maintenance_charge_w` 2000 in config.yaml, 2500 in this
|
||||
# file) is exactly what a literal here would have repeated. CFG-03 has
|
||||
# since closed that one too - `maintenance.MAINT_OPTION_DEFAULTS`,
|
||||
# read through `MaintConfig.from_options()` - so the rule now holds for
|
||||
# every option family this file builds: no numeric fallback in main.py
|
||||
# that config.yaml has not shipped.
|
||||
self.peak_guard = None
|
||||
self._peak_engaged = False
|
||||
self._peak_saturated = False
|
||||
@@ -557,8 +558,14 @@ class Controller:
|
||||
"peak_soc_floor",
|
||||
peakguard.PEAK_OPTION_DEFAULTS["peak_soc_floor"])),
|
||||
max_hold_s=self.p1.averager.max_hold_s,
|
||||
# ⚠️ SAFETY-20. The device range goes in TOO, and this call site is
|
||||
# the one that needed it most: `standing` is `last_write`, i.e. the
|
||||
# value AFTER `clamp_to_rating()` applied `[dev_min, dev_max]`, so
|
||||
# grading it against a rail derived from bare `max_w` compares a
|
||||
# device-clipped number to a ceiling the device cannot reach.
|
||||
frozen=looks_frozen(getattr(self.p1_source, "unchanged_s", None),
|
||||
standing, max_w, self.freeze_wd.cfg),
|
||||
standing, max_w, self.freeze_wd.cfg,
|
||||
dev_min=self.dev_min, dev_max=self.dev_max),
|
||||
)
|
||||
peak_claim = (peakguard.claim(self.peak_guard)
|
||||
if self.peak_guard is not None else None)
|
||||
@@ -686,8 +693,16 @@ class Controller:
|
||||
hi = 0.0
|
||||
reason = "charge-only"
|
||||
if self.cheap:
|
||||
# ⚠️ CFG-03. `self.maint.cfg.charge_w`, NOT A SECOND READ
|
||||
# OF `self.o`. This line used to re-open the options dict
|
||||
# with its own literal fallback, so the rate the shaping
|
||||
# asked for and the rate the state machine drained at could
|
||||
# be different numbers from the same install - and, with the
|
||||
# key absent, they were. The Controller already parsed this
|
||||
# once in __init__; asking the object that owns it cannot
|
||||
# drift from it.
|
||||
floor = maintenance_charge_floor(
|
||||
float(self.o.get("maintenance_charge_w", 2500)),
|
||||
self.maint.cfg.charge_w,
|
||||
self.peak_fc, float(self.o.get("peak_cap_w", 3500)))
|
||||
if floor > 0:
|
||||
hi, reason = -floor, "cheap-window charge"
|
||||
@@ -776,6 +791,12 @@ class Controller:
|
||||
# `self.target`, which is assigned further up - see check_output_clamp()
|
||||
# and check_meter_frozen() for each. Two guards, two orderings, adjacent
|
||||
# lines: do not "tidy" them into one rule.
|
||||
#
|
||||
# Moving it BELOW the other guards is harmless - nothing between here and
|
||||
# the end of cycle() writes `self.clamp_last`. Moving it above the write
|
||||
# is not, and test_clamp.py part 6 fails on exactly that: it grades the
|
||||
# evidence, not the line number, so a rename or a move into a helper that
|
||||
# still runs after the write keeps it green. (TEST-11.)
|
||||
await self.check_output_clamp()
|
||||
|
||||
# --- SAFETY-18, and its boundary is the ASSIGNMENT --------------------
|
||||
@@ -979,6 +1000,16 @@ class Controller:
|
||||
They cannot both be true: peakguard.decide()'s floor-limited branch
|
||||
returns before the `achievable_w` clamp that sets `saturated`.
|
||||
|
||||
⚠️ SAFETY-25 - AND THE MESSAGE SAYS WHAT THE FLOOR IS NOT. Read on its
|
||||
own, "the capacity-peak guard has run out of battery" invites exactly
|
||||
one wrong inference: that the pack is now being held at
|
||||
`peak_soc_floor`. It is not. `peak_soc_floor` bounds THIS GUARD only;
|
||||
the grid-following loop has no SoC floor at all and, on the committed
|
||||
2026-08-20 replay, is being granted discharge in EVERY cycle that raises
|
||||
this notification. An operator who reads the alarm and relaxes because
|
||||
"the EMS has a 20 % reserve" has been misled by us, so the alarm carries
|
||||
the correction itself rather than leaving it to DOCS.md.
|
||||
|
||||
Edge-triggered, and de-asserting arms it again - FreezeWatchdog's shape,
|
||||
for FreezeWatchdog's reason: one notification per episode, not one per
|
||||
cycle for a quarter of an hour.
|
||||
@@ -1004,6 +1035,13 @@ class Controller:
|
||||
# energy floor is not a saturated inverter and is not a frozen meter,
|
||||
# and an operator who has to dismiss three identical-looking cards
|
||||
# learns to dismiss the one that mattered.
|
||||
# ⚠️ SAFETY-25's sentence must render on the unreadable-SoC branch too,
|
||||
# where `soc_floor` is a number but naming it would invite the reader to
|
||||
# think the pack is AT it. `decide()` guards its own reason string the
|
||||
# same way; a f-string that formats a None here would turn the one
|
||||
# notification that matters into a traceback.
|
||||
_at_floor = ("at the floor" if g.soc_floor is None
|
||||
else f"at {float(g.soc_floor):.0f} %")
|
||||
await self.hass.call("persistent_notification", "create", {
|
||||
"notification_id": "goodwe_peak_soc_floor",
|
||||
"title": "GoodWe: the capacity-peak guard has run out of battery",
|
||||
@@ -1017,7 +1055,13 @@ class Controller:
|
||||
f"deliberately above the pack's own BMS cut-out. Charging stays "
|
||||
f"blocked. Shedding load is the only thing that changes the bill "
|
||||
f"now; if this pack can afford a deeper discharge, lower "
|
||||
f"peak_soc_floor."),
|
||||
f"peak_soc_floor.\n\nSAFETY-25 - WHAT THIS FLOOR IS NOT: "
|
||||
f"peak_soc_floor bounds THE PEAK GUARD ONLY. It is not a "
|
||||
f"pack-wide reserve, and the battery is NOT being held "
|
||||
f"{_at_floor} - ordinary self-consumption has no SoC "
|
||||
f"floor at all and will go on discharging past it, down to the "
|
||||
f"pack's own BMS cut-out. What has stopped is the guard buying "
|
||||
f"you a lower bill, not the pack being spent."),
|
||||
})
|
||||
|
||||
async def check_meter_frozen(self) -> None:
|
||||
@@ -1035,7 +1079,9 @@ class Controller:
|
||||
unchanged = getattr(self.p1_source, "unchanged_s", None)
|
||||
fired = self.freeze_wd.evaluate(unchanged, self.target,
|
||||
float(self.o.get("max_w", 2000)),
|
||||
datetime.now(timezone.utc))
|
||||
datetime.now(timezone.utc),
|
||||
dev_min=self.dev_min,
|
||||
dev_max=self.dev_max)
|
||||
if not fired:
|
||||
return
|
||||
self.log_event("METER FROZEN? " + self.freeze_wd.reason)
|
||||
@@ -1270,7 +1316,20 @@ class Controller:
|
||||
self.mqtt.close()
|
||||
|
||||
# -- UI ------------------------------------------------------------------
|
||||
def checks(self) -> list:
|
||||
def checks(self, when: datetime | None = None) -> list:
|
||||
"""The status rows. `when` is the reference time for anything billed by
|
||||
the calendar - today's month when it is None, which is what the live
|
||||
page means; `status_payload()` calls this with no argument.
|
||||
|
||||
⚠️ IT EXISTS SO THE PEAK ROW CAN BE GRADED (TEST-17). Every other peak
|
||||
query already takes it - `PeakStore.peak()`, `PeakTracker.peak()`,
|
||||
`headroom_w()`, `warning_frac()` - and the row built from them was the
|
||||
one thing that could only be read against `datetime.now()`. A suite
|
||||
that banks an August quarter then asks this page what the peak is goes
|
||||
green in August and red in September, which is what happened at 00:00
|
||||
on 2026-09-01: TARIFF-01's own section 10, red on a calendar boundary,
|
||||
on a commit nobody had touched for a day.
|
||||
"""
|
||||
o = self.o
|
||||
out = []
|
||||
if self.p1_enabled:
|
||||
@@ -1319,26 +1378,60 @@ class Controller:
|
||||
f"meter_source {o.get('meter_source')} - only "
|
||||
f"homewizard_local sees whether the meter's own "
|
||||
f"document changes"})
|
||||
elif rail_unreachable(o.get("max_w", 2000),
|
||||
dev_min=self.dev_min, dev_max=self.dev_max):
|
||||
# SAFETY-20, and THE SECOND REASON TO USE THIS ROW RATHER THAN A
|
||||
# NEW MECHANISM. The transport case above and this one are the
|
||||
# same statement - "the conjunction cannot be evaluated here" -
|
||||
# and an operator does not need to learn two vocabularies for
|
||||
# it. What differs is only which term is missing: there,
|
||||
# `unchanged_s`; here, a rail the command could ever stand at.
|
||||
out.append({"ok": False, "warn": True,
|
||||
"text": f"freeze detector: NOT COVERED - "
|
||||
+ rail_unreachable(
|
||||
o.get("max_w", 2000),
|
||||
dev_min=self.dev_min,
|
||||
dev_max=self.dev_max)})
|
||||
else:
|
||||
# ⚠️ SAFETY-20. THE RAIL PRINTED HERE IS THE RAIL THE PREDICATE
|
||||
# USES, device range included. This row used to interpolate
|
||||
# `rail_w(max_w)` while `looks_frozen()` graded a command the
|
||||
# device had already clipped below it, so on any install whose
|
||||
# inverter is smaller than its configured ceiling the page named
|
||||
# a number the command could never reach and called it `armed`.
|
||||
# Both the row and the predicate now read the same three inputs.
|
||||
_rail = rail_w(o.get("max_w", 2000),
|
||||
dev_min=self.dev_min, dev_max=self.dev_max)
|
||||
# And when the device is what set that number, SAY SO - the
|
||||
# operator configured `max_w` and is owed the reason the guard
|
||||
# is armed somewhere else.
|
||||
# ⚠️ Either bound may be None on its own - `hass.limits()`
|
||||
# reads `min` and `max` independently and returns None for
|
||||
# whichever attribute is missing or unparseable - so this
|
||||
# renders whatever is there rather than formatting a None.
|
||||
_cap = ("" if _rail >= rail_w(o.get("max_w", 2000))
|
||||
else f" - below max_w because "
|
||||
f"{o.get('setpoint_entity') or 'the setpoint device'}"
|
||||
f" accepts only {self.dev_min}...{self.dev_max} W")
|
||||
out.append({"ok": True, "warn": False,
|
||||
"text": f"freeze detector: armed (alerts after "
|
||||
f"{self.freeze_wd.cfg.hold_s:.0f} s unchanged "
|
||||
f"while the command is over "
|
||||
f"{rail_w(self.o.get('max_w', 2000)):.0f} W)"})
|
||||
f"{_rail:.0f} W{_cap})"})
|
||||
|
||||
# TARIFF-01. The month's billed peak, and - the load-bearing half -
|
||||
# a DIFFERENT row when the store could not answer. "no peak yet" is
|
||||
# a normal state on the 1st; "unreadable" is a broken instrument, and
|
||||
# a status page that spelled them the same way would let a 0 W read
|
||||
# look like a quiet month right up until SAFETY-07 shaved nothing.
|
||||
_pk = self.peak.peak()
|
||||
_pk = self.peak.peak(when)
|
||||
if _pk.is_unreadable:
|
||||
out.append({"ok": False, "warn": True,
|
||||
"text": "capacity-tariff peak: " + _pk.explain()})
|
||||
else:
|
||||
# §9.1's "warning entity at 80 %", as a status row rather than
|
||||
# a second entity - see the constructor on not doubling up.
|
||||
_frac = self.peak.warning_frac() or 0.0
|
||||
_frac = self.peak.warning_frac(when) or 0.0
|
||||
_ok = _frac < 0.8
|
||||
out.append({"ok": _ok, "warn": not _ok,
|
||||
"text": _pk.explain()
|
||||
@@ -1366,8 +1459,35 @@ class Controller:
|
||||
# is going to be spent and a human is the only actuator left. A
|
||||
# separate row from saturation because the two ask for opposite
|
||||
# things - see check_peak_floor_limited().
|
||||
#
|
||||
# ⚠️ SAFETY-25. THE SCOPE SENTENCE IS PART OF THE ROW, NOT A
|
||||
# DOCS FOOTNOTE. This is the one line an operator reads at the
|
||||
# exact moment the guard stops discharging, and read alone it
|
||||
# says "the battery is being held at peak_soc_floor" - which is
|
||||
# false, and measurably so: on the committed evening replay the
|
||||
# loop goes on discharging in EVERY cycle this row is showing.
|
||||
# A floor that binds one consumer and not the other is worse
|
||||
# than no floor if the page does not say which.
|
||||
#
|
||||
# ⚠️ AND IT CARRIES ITS OWN `banner`. status_payload() renders
|
||||
# the FIRST not-ok/not-warn row as the page's headline, so
|
||||
# without this the loudest element on the page would be a
|
||||
# 550-character paragraph that the row three lines below
|
||||
# repeats verbatim. The banner is the short form; the row keeps
|
||||
# the whole sentence, because the row is where an operator
|
||||
# reads what the floor does and does not bound. Shortening the
|
||||
# ROW instead would be weakening AC 3.
|
||||
out.append({"ok": False, "warn": False,
|
||||
"text": _pg.explain()})
|
||||
"banner": _pg.explain()
|
||||
+ " - and peak_soc_floor bounds THE PEAK "
|
||||
"GUARD ONLY (SAFETY-25, see below)",
|
||||
"text": _pg.explain()
|
||||
+ ". NOTE: peak_soc_floor bounds THE PEAK "
|
||||
"GUARD ONLY - it is not a pack-wide "
|
||||
"reserve, and ordinary self-consumption "
|
||||
"has no SoC floor, so the battery may "
|
||||
"keep discharging below this level down "
|
||||
"to the BMS cut-out (SAFETY-25)"})
|
||||
elif _pg.blind:
|
||||
out.append({"ok": False, "warn": True, "text": _pg.explain()})
|
||||
else:
|
||||
@@ -1473,7 +1593,13 @@ class Controller:
|
||||
level, banner = "bad", ("FAILSAFE — the command opposed the meter. "
|
||||
"Inverter held at 0 W.")
|
||||
elif bad:
|
||||
level, banner = "bad", f"NOT READY — {bad[0]['text']}"
|
||||
# ⚠️ `banner` IF THE ROW OFFERS ONE, `text` OTHERWISE. A row may
|
||||
# need to say more to an operator reading the checks list than fits
|
||||
# in the one line at the top of the page - SAFETY-25's floor-limited
|
||||
# row is the case that forced this - and a headline that is a full
|
||||
# paragraph, repeated verbatim by the row underneath it, is a
|
||||
# headline nobody reads. Rows without the key are unaffected.
|
||||
level, banner = "bad", f"NOT READY — {bad[0].get('banner') or bad[0]['text']}"
|
||||
elif not self.auto:
|
||||
level, banner = "warn", "Stopped — inverter commanded to 0 W"
|
||||
elif self.maint.phase != IDLE:
|
||||
|
||||
@@ -38,17 +38,112 @@ CHARGE_TIMEOUT_MIN = 2160
|
||||
# After an abort, do not immediately re-trigger in the same start hour.
|
||||
RESTART_COOLDOWN_MIN = 90
|
||||
|
||||
# ⚠️ CFG-03. THE ONE IN-CODE MIRROR OF config.yaml FOR EVERY `maintenance_*`
|
||||
# OPTION, and the only place in the add-on where one of these numbers is typed.
|
||||
#
|
||||
# WHAT WENT WRONG WITHOUT IT. Until this card each default was written down
|
||||
# three times - config.yaml's `options:` block, an `opts.get(key, <literal>)`
|
||||
# fallback in main.py, and this dataclass - and MAINT-04 proved they had already
|
||||
# drifted: config.yaml said 2000, the other two said 2500. An options dict with
|
||||
# `maintenance_charge_w` ABSENT was therefore ACCEPTED by validate.py's rule 6
|
||||
# (which read 2000) and then BUILT by main.py at 2500, against a 2000 W ceiling
|
||||
# - the exact `lo > hi` contradiction rule 6 exists to refuse, resolving to 0 W
|
||||
# with `contradiction=True`. Unreachable through the Supervisor, which always
|
||||
# supplies every key; fully reachable from sim/inject.py and from the test
|
||||
# suite, which is where anyone debugging maintenance actually is.
|
||||
#
|
||||
# WHERE THE SINGLE SOURCE ACTUALLY IS: config.yaml's `options:` block. It is
|
||||
# what the Supervisor reads and what the operator edits, so it wins by
|
||||
# definition. This dict is a MIRROR of it and not a second opinion:
|
||||
# test_maintenance.py pins every entry by READING the shipped file, so a drift
|
||||
# goes red in CI instead of shipping. That is TARIFF-02's `PRICE_OPTION_DEFAULTS`
|
||||
# and SAFETY-24's `PEAK_OPTION_DEFAULTS` pattern, now applied to the family that
|
||||
# named the card. A mirror rather than a runtime read because the Dockerfile
|
||||
# copies `app/` and `run.sh` into the image and NOT config.yaml - the add-on
|
||||
# cannot open the file it is configured by, so there is nothing to read at 03:00
|
||||
# on a client's Pi, and a parser that could fail at import is a new way for the
|
||||
# add-on not to start.
|
||||
#
|
||||
# ⚠️ DEFAULTS ONLY. NO BOUNDS LIVE HERE, and that is a decision, not an
|
||||
# omission. The RANGE of each key (`maintenance_charge_w: int(500,5000)`) lives
|
||||
# in config.yaml's `schema:` block and nowhere else, because the Supervisor is
|
||||
# what enforces it and the Supervisor reads only that file. What this module
|
||||
# would gain by mirroring the bounds too is a fifth place to disagree with.
|
||||
# validate.py's rule 6 is NOT a range and does not belong here either: it is a
|
||||
# relation BETWEEN TWO KEYS (`maintenance_charge_w` against `max_w`) that the
|
||||
# schema grammar cannot express at all, which is the whole reason that rule is
|
||||
# written in Python.
|
||||
#
|
||||
# ⚠️ KEYED BY THE OPTION NAME, not by the MaintConfig field name. The dict is
|
||||
# what `from_options()` indexes while reading the operator's dict, so the two
|
||||
# strings have to be the same string; a `charge_w` key here would reintroduce a
|
||||
# transcription step between config.yaml and the reader.
|
||||
MAINT_OPTION_DEFAULTS = {
|
||||
"maintenance_enabled": False,
|
||||
"maintenance_interval_days": 28,
|
||||
"maintenance_start_hour": 10,
|
||||
# ⚠️ 2000, NOT THE 2500 THIS SHIPPED AS, and config.yaml carries the
|
||||
# argument: both rates must stay at or below `max_w` (2000) or the
|
||||
# cheap-window charge shaping asks the arbiter for `hi = -charge_w` against
|
||||
# a supervised `lo = -max_w` and contradicts itself into 0 W. Raising max_w
|
||||
# is what unlocks a faster cycle - raise it FIRST, then these.
|
||||
"maintenance_discharge_w": 2000,
|
||||
"maintenance_charge_w": 2000,
|
||||
"maintenance_soc_floor": 11,
|
||||
"maintenance_soc_target": 99,
|
||||
"maintenance_hold_min": 120,
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MaintConfig:
|
||||
enabled: bool = False
|
||||
interval_days: int = 28
|
||||
start_hour: int = 10
|
||||
discharge_w: float = 2500.0
|
||||
charge_w: float = 2500.0
|
||||
soc_floor: float = 11.0
|
||||
soc_target: float = 99.0
|
||||
hold_min: int = 120
|
||||
"""The maintenance cycle's settings, already parsed.
|
||||
|
||||
⚠️ EVERY DEFAULT IS READ OUT OF `MAINT_OPTION_DEFAULTS`, never typed. A
|
||||
literal in this class is what made `MaintConfig()` a THIRD opinion about
|
||||
what a missing key means - see the block above - so `MaintConfig()` and
|
||||
`MaintConfig.from_options({})` and validate.py's fallback are now
|
||||
arithmetically the same number by construction rather than by vigilance.
|
||||
"""
|
||||
|
||||
enabled: bool = bool(MAINT_OPTION_DEFAULTS["maintenance_enabled"])
|
||||
interval_days: int = int(MAINT_OPTION_DEFAULTS["maintenance_interval_days"])
|
||||
start_hour: int = int(MAINT_OPTION_DEFAULTS["maintenance_start_hour"])
|
||||
discharge_w: float = float(MAINT_OPTION_DEFAULTS["maintenance_discharge_w"])
|
||||
charge_w: float = float(MAINT_OPTION_DEFAULTS["maintenance_charge_w"])
|
||||
soc_floor: float = float(MAINT_OPTION_DEFAULTS["maintenance_soc_floor"])
|
||||
soc_target: float = float(MAINT_OPTION_DEFAULTS["maintenance_soc_target"])
|
||||
hold_min: int = int(MAINT_OPTION_DEFAULTS["maintenance_hold_min"])
|
||||
|
||||
@classmethod
|
||||
def from_options(cls, opts: dict) -> "MaintConfig":
|
||||
"""Build from an add-on options dict.
|
||||
|
||||
⚠️ THE ONLY PLACE IN THE ADD-ON THAT READS A `maintenance_*` OPTION.
|
||||
main.py used to do this inline as eight `opts.get(key, <literal>)`
|
||||
calls, which is eight opportunities to type a number that config.yaml
|
||||
does not ship - and one of them had already been taken. Moving the read
|
||||
next to the mirror means the fallback cannot be anything but the mirror,
|
||||
because there is no dict literal in sight of it to disagree with.
|
||||
|
||||
⚠️ `key in opts`, not `opts.get(key) or ...`. A shipped `false` and a
|
||||
shipped `0` are values an operator can legitimately set, and the truthy
|
||||
form would quietly replace both with the default - which is this card's
|
||||
own bug wearing a different hat.
|
||||
"""
|
||||
def _opt(key):
|
||||
return opts[key] if key in opts else MAINT_OPTION_DEFAULTS[key]
|
||||
|
||||
return cls(
|
||||
enabled=bool(_opt("maintenance_enabled")),
|
||||
interval_days=int(_opt("maintenance_interval_days")),
|
||||
start_hour=int(_opt("maintenance_start_hour")),
|
||||
discharge_w=float(_opt("maintenance_discharge_w")),
|
||||
charge_w=float(_opt("maintenance_charge_w")),
|
||||
soc_floor=float(_opt("maintenance_soc_floor")),
|
||||
soc_target=float(_opt("maintenance_soc_target")),
|
||||
hold_min=int(_opt("maintenance_hold_min")),
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
|
||||
@@ -286,6 +286,25 @@ the one place the question is answered. Four things about the shape of it:
|
||||
discharge, which is the thing SAFETY-07 introduced. A loop-side SoC guard
|
||||
is a different lever with a different right value.
|
||||
|
||||
⚠️ SAFETY-25 MEASURED HOW FAR PAST, so this is no longer a caveat that has
|
||||
to be taken on trust. On the committed 2026-08-20 capture, 19:00-22:00 UTC
|
||||
- three hours of house load after the sun has gone, 830 W mean, zero export
|
||||
- the 13.8 kWh reference pack started one point ABOVE `peak_soc_floor`
|
||||
ends the evening at 10.0 %, i.e. at `bms_soc_floor`, having delivered
|
||||
1525 Wh; 343 of 587 control cycles deliver discharge with the pack already
|
||||
under this floor, and the guard files no floor at all on any of them. The
|
||||
same replay at `peak_soc_floor` = 5, 11, 20 and 60 ends at the SAME 10.0 %,
|
||||
which is the finding stated as sharply as it can be: THE EXPOSURE IS A
|
||||
PROPERTY OF THE CONTROL LAW, NOT A VALUE ANYONE CAN CONFIGURE. And on the
|
||||
same day's high-load block the two states coexist - 49 cycles reporting
|
||||
PEAK GUARD FLOOR-LIMITED while the arbiter grants the loop up to 2000 W of
|
||||
discharge in every one of them. test_peakguard.py part 10 is the replay;
|
||||
DECISIONS/SAFETY-25-loop-soc-floor.md carries the options and the
|
||||
recommendation, and the product owner DECIDED it on 2026-09-02: Option A,
|
||||
the BMS stays the only backstop for demand-driven discharge, with a
|
||||
loop-side reserve DEFERRED to ALLOC-01. This floor's scope is therefore
|
||||
settled rather than provisional - it bounds the peak guard, on purpose.
|
||||
|
||||
3. IT IS GRADED ONLY WHERE IT IS NOT DEGENERATE. The SoC question is asked
|
||||
AFTER `wanted > 0` is established - i.e. only where a forced discharge is
|
||||
actually being asked for. Asked earlier it would grade a quantity that
|
||||
@@ -373,6 +392,12 @@ CEILING_MONTH_PEAK = "the month's banked peak"
|
||||
# notification all have to say WHICH, and "floor-limited" alone is unactionable.
|
||||
FLOOR_SOC_UNREADABLE = ("the battery state of charge was not measured this "
|
||||
"cycle, and an unreadable SoC is not a full battery")
|
||||
# ⚠️ SAFETY-25. "the peak guard's SoC floor", not "the SoC floor", and the
|
||||
# possessive is load-bearing: this string is what the status page, the action log
|
||||
# and the operator notification all print, and `peak_soc_floor` bounds THIS GUARD
|
||||
# ONLY. Widening it to "the SoC floor" would make the one sentence an operator
|
||||
# reads at the moment the battery stops shaving into a claim about the pack that
|
||||
# the grid-following loop is at that instant disproving.
|
||||
FLOOR_AT_SOC_FLOOR = "state of charge is at or below the peak guard's SoC floor"
|
||||
|
||||
SOURCE = "peak"
|
||||
|
||||
@@ -170,6 +170,29 @@ WHAT IS DELIBERATELY *NOT* REFUSED, because it is untidy rather than unsafe:
|
||||
- `maintenance_discharge_w` above `max_w`. Clamped, not contradicted, and the
|
||||
clamp names itself in the arbiter's explain() - see rule 6. Warned about,
|
||||
not refused.
|
||||
- A device rating that makes SAFETY-18's freeze rail unreachable. SAFETY-20's
|
||||
AC 4, decided here rather than left implicit: **NO NEW RULE, and rule 2 is
|
||||
the reason.** The configuration the ticket is about is `max_w` above the
|
||||
setpoint device's rating, which is rule 2 EXACTLY - already refused, on the
|
||||
identical predicate, since CFG-01, and re-run by `run_control()` once
|
||||
ESPHome is up and the real rating is known. A second rule phrased as
|
||||
"`RAIL_FRAC * max_w` exceeds the device rating" would fire on a strict
|
||||
subset of the configurations rule 2 already refuses (`0.95 * max_w > dev_max`
|
||||
implies `max_w > dev_max`), so it could never be the rule that stopped a
|
||||
start, and its whole visible effect would be a second entry in a refusal
|
||||
list that already names the problem.
|
||||
|
||||
⚠️ AND IT WOULD NOT COVER THE CASE THAT REMAINS, WHICH IS WHY THE STATUS ROW
|
||||
IS NOT A CONSOLATION PRIZE. The residue after rule 2 is the state where
|
||||
`hass.limits()` answered `(None, None)` - ESPHome not up when the add-on
|
||||
booted - so the range checks were SKIPPED rather than guessed at, and the
|
||||
rating is never re-read afterwards. There is nothing to refuse at startup in
|
||||
that state, by construction: the number a refusal would need does not exist
|
||||
yet. That is a runtime coverage question, and the runtime surface -
|
||||
`freeze.rail_unreachable()` and the NOT COVERED row it feeds - is where it
|
||||
is answered. Compare rule 5, which CAN be settled at startup because both
|
||||
`sign_disagree_w` and `max_w` are config and are both known at boot.
|
||||
|
||||
- `peak_soc_floor` below `maintenance_soc_floor`, or above it. They are
|
||||
DIFFERENT QUANTITIES (SAFETY-24: a drain target versus a spend limit) and
|
||||
every ordering of the two is a legitimate site configuration. Refusing on
|
||||
@@ -179,6 +202,7 @@ WHAT IS DELIBERATELY *NOT* REFUSED, because it is untidy rather than unsafe:
|
||||
import logging
|
||||
|
||||
from .arbitrage import enabled as arbitrage_on
|
||||
from .maintenance import MAINT_OPTION_DEFAULTS
|
||||
from .p1 import is_enabled, validate_meter_options
|
||||
from .peakguard import PEAK_OPTION_DEFAULTS
|
||||
from .price import PRICE_OPTION_DEFAULTS, PROVIDERS
|
||||
@@ -356,26 +380,23 @@ def validate_startup_config(opts: dict, dev_min=None, dev_max=None) -> list[str]
|
||||
# leave the trap armed for the one operator action - ticking
|
||||
# maintenance_enabled - that cannot possibly be expected to change what a
|
||||
# charge rate means.
|
||||
# ⚠️ THE FALLBACK IS config.yaml's SHIPPED VALUE, and it has to be kept
|
||||
# equal to it - that is the whole point of AC3. It is reachable only when a
|
||||
# caller hands over a dict with the key missing (sim/inject.py, a test); the
|
||||
# Supervisor always supplies every key from config.yaml, so on a real
|
||||
# install the argument is always present.
|
||||
#
|
||||
# ⚠️ KNOWN MISMATCH, LEFT DELIBERATELY AND FLAGGED RATHER THAN FIXED HERE:
|
||||
# `main.py` still falls back to 2500 in two places
|
||||
# (`opts.get("maintenance_charge_w", 2500)`), as does maintenance.py's
|
||||
# MaintConfig dataclass. So a dict with the key ABSENT is accepted by this
|
||||
# rule at 2000 and then built by main.py at 2500 - the contradiction this
|
||||
# rule exists to catch, in the one case it cannot see. It is unreachable on
|
||||
# a Supervisor install and those files are another ticket's right now.
|
||||
# THE REAL FIX is one source of truth for option defaults; until then the
|
||||
# divergence is PINNED BY A CHECK rather than by this comment - see
|
||||
# test_validate.py, "the KNOWN cross-file default divergence". It asserts
|
||||
# the mismatch as it stands and goes red if EITHER side moves, including
|
||||
# when somebody closes it in main.py, at which point this block and that
|
||||
# check both get deleted.
|
||||
charge_w = _number(opts, "maintenance_charge_w", 2000.0)
|
||||
# ⚠️ THE FALLBACK IS config.yaml's SHIPPED VALUE, READ RATHER THAN TYPED
|
||||
# (CFG-03). It is reachable only when a caller hands over a dict with the
|
||||
# key missing (sim/inject.py, a test); the Supervisor always supplies every
|
||||
# key from config.yaml, so on a real install the argument is always present
|
||||
# and this default is dead code. That is precisely why it went stale
|
||||
# unnoticed for a whole card: MAINT-04 moved config.yaml to 2000 while
|
||||
# main.py and MaintConfig still said 2500, so a dict with the key ABSENT was
|
||||
# accepted here at 2000 and then built by main.py at 2500 - the
|
||||
# contradiction this rule exists to catch, in the one case it could not see.
|
||||
# The KNOWN MISMATCH block that used to stand here, and the tripwire in
|
||||
# test_validate.py that pinned it, are both DELETED: the divergence is
|
||||
# closed rather than recorded. `maintenance.MAINT_OPTION_DEFAULTS` is now
|
||||
# the one in-code mirror of config.yaml for this family - the same move
|
||||
# rule 8 below already makes with `PEAK_OPTION_DEFAULTS` - and
|
||||
# test_maintenance.py pins it by reading the shipped file.
|
||||
charge_w = _number(opts, "maintenance_charge_w",
|
||||
float(MAINT_OPTION_DEFAULTS["maintenance_charge_w"]))
|
||||
if charge_w is None:
|
||||
problems.append(
|
||||
f"maintenance_charge_w {opts.get('maintenance_charge_w')!r} is not a number")
|
||||
@@ -397,10 +418,12 @@ def validate_startup_config(opts: dict, dev_min=None, dev_max=None) -> list[str]
|
||||
# --- 8. an EMS energy floor the BMS does not already enforce -------------
|
||||
# ⚠️ THE FALLBACKS ARE peakguard.PEAK_OPTION_DEFAULTS, NOT LITERALS, and
|
||||
# that is CFG-03 read as a rule rather than as a complaint. Rule 6's own
|
||||
# comment documents a LIVE divergence in this repo caused by typing 2000
|
||||
# here and 2500 in main.py; this card refuses to add a second instance of
|
||||
# it. The dict is the single in-code mirror, pinned to config.yaml by
|
||||
# test_peakguard.py, and main.py reads the same one.
|
||||
# comment used to document a LIVE divergence in this repo caused by typing
|
||||
# 2000 here and 2500 in main.py; SAFETY-24 refused to add a second instance
|
||||
# of it, and CFG-03 has since closed the first. The dict is the single
|
||||
# in-code mirror, pinned to config.yaml by test_peakguard.py, and main.py
|
||||
# reads the same one - exactly as maintenance.MAINT_OPTION_DEFAULTS now is
|
||||
# for the `maintenance_*` family.
|
||||
soc_floor = _number(opts, "peak_soc_floor",
|
||||
PEAK_OPTION_DEFAULTS["peak_soc_floor"])
|
||||
bms_floor = _number(opts, "bms_soc_floor",
|
||||
@@ -442,7 +465,13 @@ def validate_startup_config(opts: dict, dev_min=None, dev_max=None) -> list[str]
|
||||
# words on the status page every cycle, and the cycle still completes -
|
||||
# slower, and eating into maintenance.DRAIN_TIMEOUT_MIN. Loud and it moves
|
||||
# energy, so it is neither (a) nor (b): warned, not refused.
|
||||
disch_w = _number(opts, "maintenance_discharge_w", 2000.0)
|
||||
# ⚠️ AND THE FALLBACK COMES FROM THE SAME MIRROR AS RULE 6's. CFG-03's PM
|
||||
# proofread caught this one: `maintenance_discharge_w` had the IDENTICAL
|
||||
# three-way divergence (config.yaml 2000, MaintConfig 2500) and the card
|
||||
# named only the charge side. Closing one key and leaving its twin is how a
|
||||
# single-source fix gets reproduced as a single-source bug one line down.
|
||||
disch_w = _number(opts, "maintenance_discharge_w",
|
||||
float(MAINT_OPTION_DEFAULTS["maintenance_discharge_w"]))
|
||||
if disch_w is not None and max_w is not None and max_w > 0 and disch_w > max_w:
|
||||
_LOG.warning(
|
||||
"maintenance_discharge_w %.0f W is above max_w %.0f W. Not refused - "
|
||||
|
||||
@@ -97,15 +97,17 @@ Four gates, and each one exists to exclude a specific thing that is NOT a fault:
|
||||
caller says whether the grid-following loop actually won the arbitration this
|
||||
cycle, and the timer only accumulates when it did.
|
||||
|
||||
⚠️ 1500 W, NOT THE DEFAULT 2500 W, AND THE REASON IS NOT COSMETIC. At the
|
||||
shipped defaults `maintenance_charge_w` is 2500 and `max_w` is 2000, so the
|
||||
cheap-window claim is `hi = -2500` against a supervised `lo = -2000`: lo > hi,
|
||||
which arbiter.py resolves as a CONTRADICTION and 0 W, not as a -2500 W charge.
|
||||
The example above is written at 1500 W because that is a combination the
|
||||
schema and the arbiter both actually produce. (The contradiction at the
|
||||
defaults is a real pre-existing bug - a default maintenance charge silently
|
||||
never happens in a cheap window - but it is maintenance's, not this module's,
|
||||
and it is filed separately. Do not "fix" it here.)
|
||||
⚠️ 1500 W, NOT 2500 W, AND THE REASON IS NOT COSMETIC. The example has to be
|
||||
a charge the arbiter actually produces. When this was written the shipped
|
||||
`maintenance_charge_w` was 2500 against a `max_w` of 2000, so the cheap-window
|
||||
claim was `hi = -2500` against a supervised `lo = -2000`: lo > hi, which
|
||||
arbiter.py resolves as a CONTRADICTION and 0 W, not as a -2500 W charge - a
|
||||
default maintenance charge that silently never happened. MAINT-04 refused that
|
||||
pair in validate.py and moved the shipped rate to 2000; CFG-03 gave the
|
||||
default one source of truth so main.py and MaintConfig could not go on
|
||||
answering 2500 to a dict that had never said so. The number here stays 1500
|
||||
because the point of the example is a charge STRICTLY INSIDE the ceiling, not
|
||||
one that happens to sit exactly on it.
|
||||
|
||||
2. The strict `< 0` product. "Opposed" and "neither side is zero" in one
|
||||
expression.
|
||||
|
||||
@@ -135,6 +135,21 @@ options:
|
||||
meter_freeze_s: 300
|
||||
|
||||
# --- maintenance -----------------------------------------------------------
|
||||
# ⚠️ CFG-03. THESE EIGHT LINES ARE THE SOURCE OF TRUTH FOR THE MAINTENANCE
|
||||
# DEFAULTS. The Supervisor reads this file and the operator edits this file,
|
||||
# so nothing else in the add-on gets an opinion about what a missing
|
||||
# `maintenance_*` key means. There is exactly ONE in-code copy -
|
||||
# `app/maintenance.py`'s `MAINT_OPTION_DEFAULTS` - because the Dockerfile does
|
||||
# not put this file in the image and the running add-on therefore cannot read
|
||||
# it; test_maintenance.py pins that copy by READING these lines, so a drift
|
||||
# goes red in CI rather than shipping. main.py and validate.py both read the
|
||||
# mirror and type no number of their own.
|
||||
#
|
||||
# Before this card the same defaults were written down three times and had
|
||||
# already disagreed: this block said 2000 while main.py and MaintConfig said
|
||||
# 2500, so an options dict with the key ABSENT passed validation at 2000 and
|
||||
# then ran at 2500 against a 2000 W ceiling - a silent 0 W arbiter
|
||||
# contradiction. Changing one of these numbers now moves every consumer.
|
||||
maintenance_enabled: false
|
||||
maintenance_interval_days: 28
|
||||
maintenance_start_hour: 10
|
||||
@@ -186,6 +201,26 @@ options:
|
||||
# worst modelled guard day is 878 Wh, i.e. 6.4 % - so 10 points above the
|
||||
# pack's own cut-out leaves the guard ~1.6 of its worst observed days of room
|
||||
# and still never reaches the BMS.
|
||||
#
|
||||
# ⚠️⚠️ SAFETY-25 - WHAT THIS DOES NOT BOUND, AND IT IS THE HALF THE NAME HIDES.
|
||||
# peak_soc_floor BOUNDS THE PEAK GUARD ONLY. IT IS NOT A PACK-WIDE RESERVE.
|
||||
# Ordinary self-consumption - the grid-following loop that holds the meter at
|
||||
# zero - has no SoC floor of any kind, so on a sustained-load evening it will
|
||||
# discharge STRAIGHT PAST this number and go on until the pack's own BMS
|
||||
# cut-out (bms_soc_floor) stops it. Replayed on the committed 2026-08-20
|
||||
# capture, 19:00-22:00 UTC: a 13.8 kWh pack starting at 21 % ends the evening
|
||||
# at 10.0 %, and 343 of 587 control cycles deliver discharge with the pack
|
||||
# already below this floor. Setting this key higher does not change that by
|
||||
# one tenth of a percent - the same replay at every value the schema accepts
|
||||
# (5..60) ends at the same 10.0 %.
|
||||
#
|
||||
# The reason is structural, not an oversight: the peak guard files a `lo`
|
||||
# limit (a LOWER bound on the setpoint), which is what makes it provably
|
||||
# unable to cap a discharge or contradict the arbiter - and therefore also
|
||||
# unable to stop one the loop itself wants. See peakguard.py's module note and
|
||||
# DECISIONS/SAFETY-25-loop-soc-floor.md, which records the options for a
|
||||
# loop-side reserve and is waiting on the product owner. Until that is
|
||||
# answered, the BMS is the only floor under self-consumption.
|
||||
peak_soc_floor: 20
|
||||
# The pack's OWN cut-out percent - what the BMS enforces whatever is set
|
||||
# above. Register 0x0560 reads 10 on the reference GW5000S-BP, consistent with
|
||||
@@ -363,6 +398,16 @@ schema:
|
||||
# app/freeze.py.
|
||||
meter_freeze_s: int(60,3600)
|
||||
|
||||
# ⚠️ CFG-03 - THIS IS WHERE A RANGE LIVES, AND THE ONLY PLACE IT LIVES. The
|
||||
# `options:` block above holds the DEFAULT; this block holds the BOUNDS, and
|
||||
# `MAINT_OPTION_DEFAULTS` deliberately mirrors the former and not the latter -
|
||||
# the Supervisor is what enforces a range and the Supervisor reads only this
|
||||
# file, so a second copy of `int(500,5000)` in Python would be a place to
|
||||
# disagree and nothing else. What is NOT expressible here is a relation
|
||||
# BETWEEN keys: `maintenance_charge_w` must also stay at or below `max_w`, the
|
||||
# schema grammar has no way to say so, and that is why validate.py's rule 6 is
|
||||
# written in code instead. Add a ninth maintenance option in three places -
|
||||
# options:, schema:, MAINT_OPTION_DEFAULTS - and in no fourth.
|
||||
maintenance_enabled: bool
|
||||
maintenance_interval_days: int(1,90)
|
||||
maintenance_start_hour: int(0,23)
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,551 @@
|
||||
#!/usr/bin/env python3
|
||||
"""DATA-02: fetch 12 months of EPEX BE day-ahead prices, in §9.3's shape.
|
||||
|
||||
python3 scenarios/fetch_epex_be.py --start 2025-09-01 --end 2026-09-01 \
|
||||
--out scenarios/epex-be-dayahead-2025-09-01_2026-09-01.json
|
||||
|
||||
Run from `goodwe_controller/`. Rewrites the output file from scratch; the
|
||||
committed dataset is exactly what this produces, and `--verify` re-derives every
|
||||
claim the file makes about itself without going to the network.
|
||||
|
||||
|
||||
WHAT THIS IS NOT
|
||||
================
|
||||
NOT wired into the add-on, and it must never be. `price.py`'s `GenericDayAhead`
|
||||
is the live path and it has its own egress check; this is a one-shot archival
|
||||
fetch that produces a file for REPLAY, run by hand by a developer. Nothing under
|
||||
`app/` imports it.
|
||||
|
||||
|
||||
THE SOURCE, AND WHY THIS ONE
|
||||
============================
|
||||
`https://api.energy-charts.info/price?bzn=BE` - Fraunhofer ISE's Energy-Charts
|
||||
API. No key, no registration.
|
||||
|
||||
⚠️ THE LICENCE WAS CHECKED BEFORE ANY DATA WAS COMMITTED, because for this
|
||||
source it is NOT uniform across bidding zones. The API's own OpenAPI document
|
||||
(`https://api.energy-charts.info/openapi.json`, /price) splits the zones in two:
|
||||
|
||||
"The data for the following bidding zones is licensed as CC BY 4.0 from
|
||||
Bundesnetzagentur | SMARD.de and is published without changes:
|
||||
AT, BE (Belgium), CH, CZ, DE-LU, ..."
|
||||
|
||||
"The data for the other bidding zones is for private and internal use only.
|
||||
The utilization of any data, whether in its raw or derived form, for
|
||||
external or commercial purposes is expressly prohibited. Should you require
|
||||
licensing for market-related data, please direct your inquiries to the
|
||||
original data providers, including but not limited to EPEX SPOT SE."
|
||||
|
||||
BE is in the FIRST list, so redistribution is permitted with attribution and the
|
||||
dataset is committed rather than left as a fetch script and a checksum. Every
|
||||
response also carries the licence per-response in `license_info`, and this
|
||||
script REFUSES to write a file if that field ever stops saying CC BY 4.0 - a
|
||||
licence checked once by a human and assumed forever is a licence that changes
|
||||
silently. Had BE been in the second list, the correct output of this card would
|
||||
have been this script and a checksum and no data.
|
||||
|
||||
Attribution, carried in the dataset's own `provenance` block and reproduced
|
||||
here: data CC BY 4.0, Bundesnetzagentur | SMARD.de, retrieved via Energy-Charts
|
||||
(Fraunhofer ISE), https://energy-charts.info, published without changes.
|
||||
|
||||
Cross-checked against the upstream on 2026-08-31: SMARD's own chart_data series
|
||||
`4996/DE` over 2026-04-10 matched this API's BE series on all 96 quarter-hours
|
||||
with a maximum absolute difference of 0.00 EUR/MWh. "Published without changes"
|
||||
is a claim worth checking once; `--verify` does not repeat it, because it is a
|
||||
claim about the SOURCE and not about the file.
|
||||
|
||||
|
||||
RAW WHOLESALE, AND THE ASSUMPTION THAT IS NOT BAKED IN
|
||||
======================================================
|
||||
⚠️ WHAT COMES BACK IS RAW WHOLESALE, EUR/MWh, DAY-AHEAD AUCTION CLEARING PRICE.
|
||||
It is NOT all-in: no supplier markup, no distribution or transmission tariff, no
|
||||
levies, no VAT. §9.3's canonical point is all-in, and TARIFF-02's whole trap is
|
||||
a figure that already contains a component being handed to something that adds
|
||||
it again.
|
||||
|
||||
So this file does NOT add one. `eur_per_kwh` in the output is the wholesale
|
||||
figure converted from EUR/MWh, `provenance.all_in` is `false` beside it, and the
|
||||
markup/tax assumption a consumer needs lives in `provenance.all_in_assumption`
|
||||
as NUMBERS TO APPLY rather than numbers already applied. test_arbitrage.py
|
||||
section 7 applies them where a reader can watch it happen.
|
||||
|
||||
The assumption's SHAPE is the part that is not arbitrary, and it decides which
|
||||
conclusions depend on the guessed numbers at all:
|
||||
|
||||
all_in(h) = (wholesale(h) + markup + network_and_levies) * (1 + vat)
|
||||
|
||||
* The two ADDITIVE terms cancel out of a spread: max - min is unchanged by
|
||||
them. So how often a day clears `cycle_cost_threshold_eur` does NOT depend
|
||||
on the markup guess - only on the VAT multiplier.
|
||||
* They do NOT cancel out of §17's negative-price guard, which compares ONE
|
||||
hour's all-in price against zero. A wholesale hour at -0.02 EUR/kWh is
|
||||
comfortably positive all-in once ~0.12 of fixed charges is added.
|
||||
|
||||
Both are asserted arithmetically in section 7 rather than believed, and the
|
||||
trade count is reported on the raw spread as well, so a reader can see exactly
|
||||
how much of the answer rests on the guess.
|
||||
|
||||
The numbers themselves (2026 Belgian residential dynamic contract, order of
|
||||
magnitude) are a STATED GUESS, labelled as one everywhere they appear. They are
|
||||
not a measurement and this card had nothing to measure them with.
|
||||
|
||||
|
||||
HOURS, QUARTER-HOURS, AND THE SEAM IN THE MIDDLE OF THE YEAR
|
||||
============================================================
|
||||
⚠️ THE SOURCE CHANGES RESOLUTION PART-WAY THROUGH ANY RECENT 12 MONTHS. EPEX
|
||||
day-ahead moved to a 15-minute market time unit in October 2025 and the feed
|
||||
follows: 2025-09-10 comes back as 24 hourly points, 2025-12-10 as 96
|
||||
quarter-hourly ones. An importer that assumed either one silently loses three
|
||||
quarters of the year, or reads a quarter as an hour.
|
||||
|
||||
The canonical format is hourly, so quarter-hours are aggregated: an hour's price
|
||||
is the unweighted mean of its four quarters. That is a STATED APPROXIMATION of
|
||||
the hourly product, not the hourly product, and it errs in the direction that
|
||||
matters here - averaging discards intra-hour variation, so the observed spread
|
||||
is a LOWER bound on what a 15-minute strategy would see.
|
||||
`provenance.resolution` records how many hours came from each source shape.
|
||||
|
||||
⚠️ AND A PARTIAL HOUR IS DROPPED, NOT AVERAGED OVER WHAT ARRIVED. An hour with
|
||||
three of four quarters is an hour nobody published a complete price for; the
|
||||
mean of three would be an invented number carrying no flag. Dropped hours are
|
||||
listed in `provenance.gaps` with their timestamps, because a missing hour in a
|
||||
feed is not a zero price, and a zero price is exactly the value that would make
|
||||
everything look free.
|
||||
|
||||
|
||||
SIZE: WHY THIS IS PLAIN JSON AND NOT A `.gz`, MEASURED
|
||||
======================================================
|
||||
The directory's existing captures are gzipped, so the default would have been to
|
||||
gzip this too. Measured on the committed file instead of assumed:
|
||||
|
||||
working tree, plain JSON 893 171 bytes
|
||||
what GIT actually stores for it (zlib, loose object) 74 590 bytes
|
||||
what git would store for a committed `.json.gz` 56 504 bytes
|
||||
|
||||
⚠️ GIT ALREADY COMPRESSES BLOBS, so gzipping buys 18 KB - 24 % of an object
|
||||
that is already 75 KB, in a repository whose three existing P1 captures cost
|
||||
27 KB, 136 KB and 140 KB. Eighteen kilobytes is not worth making the provenance
|
||||
block unreadable in a pull request, and the licence claim in that block is
|
||||
precisely the thing a reviewer of this card has to read and check. Plain JSON
|
||||
also greps, diffs line-by-line when a future refetch changes something, and is
|
||||
what `--verify` opens. `load()` still handles `.gz` for a future dataset large
|
||||
enough to want it; this one is not.
|
||||
|
||||
The P1 captures are gzipped for the opposite reason and it is not an
|
||||
inconsistency: they are hundreds of thousands of telegram lines that no human
|
||||
reads, and there is no metadata in them to review.
|
||||
|
||||
|
||||
TIME
|
||||
====
|
||||
Every instant is carried as UTC and rendered with `app.price.brussels()`, the
|
||||
module that already owns the EU DST rule without a tz database. There is no
|
||||
second answer to that question here and there must not be: the point of
|
||||
`brussels()` is that the 02:00-03:00 hour which happens twice in October is two
|
||||
instants, and a 24-slot local-hour importer collapses them.
|
||||
|
||||
So a year is 8760 hours only if it contains no transition, or contains both and
|
||||
they cancel - 25 in October, 23 in March. `--verify` therefore asserts the
|
||||
PER-DAY counts, not the total, because the total is exactly the number a broken
|
||||
importer also produces.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import gzip
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from collections import Counter, defaultdict
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from app.price import brussels # noqa: E402
|
||||
|
||||
API = "https://api.energy-charts.info/price"
|
||||
BZN = "BE"
|
||||
LICENCE_MUST_CONTAIN = "CC BY 4.0"
|
||||
UTC = timezone.utc
|
||||
|
||||
ATTRIBUTION = ("Data licensed CC BY 4.0 by Bundesnetzagentur | SMARD.de, "
|
||||
"retrieved via the Energy-Charts API (Fraunhofer ISE), "
|
||||
"https://energy-charts.info. Published without changes.")
|
||||
|
||||
# ⚠️ A GUESS, LABELLED AS ONE, AND APPLIED BY THE CONSUMER - NOT HERE.
|
||||
# Order-of-magnitude 2026 Belgian residential dynamic contract. Nothing in this
|
||||
# repository measured any part of it.
|
||||
ALL_IN_ASSUMPTION = {
|
||||
"form": "all_in = (wholesale + markup + network_and_levies) * (1 + vat)",
|
||||
"markup_eur_per_kwh": 0.020,
|
||||
"network_and_levies_eur_per_kwh": 0.100,
|
||||
"vat_fraction": 0.06,
|
||||
"status": "ASSUMPTION, NOT MEASURED. Stated so a consumer applies it "
|
||||
"deliberately; the committed eur_per_kwh has none of it applied.",
|
||||
"note": "The two additive terms cancel out of any spread, so an arbitrage "
|
||||
"trade count depends on vat_fraction only. They do NOT cancel out "
|
||||
"of the negative-price guard (17), which compares one hour's "
|
||||
"all-in price against zero.",
|
||||
}
|
||||
|
||||
|
||||
PACE_S = 3.0 # between chunks, unconditionally
|
||||
RETRIES = 6
|
||||
|
||||
|
||||
def _get(url: str) -> dict:
|
||||
"""One GET, backing off on 429 and 5xx.
|
||||
|
||||
⚠️ THIS IS A FREE PUBLIC SERVICE AND IT RATE-LIMITS. The first run of this
|
||||
script was refused with 429 on its fifth chunk. Backing off is the polite
|
||||
behaviour; it is also the correct one, because the alternative - catching
|
||||
the error and carrying on - would produce a file that is silently missing a
|
||||
month and says nothing about it. A refused request is not an empty month.
|
||||
"""
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
headers={"User-Agent": "goodwe-addon/DATA-02 (one-shot archival fetch)"})
|
||||
wait = 5.0
|
||||
for attempt in range(1, RETRIES + 1):
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=90) as r:
|
||||
return json.loads(r.read().decode("utf-8"))
|
||||
except urllib.error.HTTPError as e:
|
||||
if e.code not in (429, 500, 502, 503, 504) or attempt == RETRIES:
|
||||
raise
|
||||
print(f" HTTP {e.code}; backing off {wait:.0f}s "
|
||||
f"(attempt {attempt}/{RETRIES})", file=sys.stderr)
|
||||
time.sleep(wait)
|
||||
wait *= 2
|
||||
raise SystemExit(f"unreachable: {url}")
|
||||
|
||||
|
||||
def local_midnight_utc(day: str) -> datetime:
|
||||
"""The INSTANT at which Brussels midnight begins on `day` (YYYY-MM-DD).
|
||||
|
||||
⚠️ THE WINDOW IS LOCAL, NOT UTC, AND THE FIRST RUN OF THIS SCRIPT PROVED WHY.
|
||||
Bounding it at 00:00 UTC starts the year at 02:00 CEST, which makes the first
|
||||
Brussels day 22 hours long - and 22 is not one of the two lengths a
|
||||
transition produces, so `report()` refused the file. A dataset whose first
|
||||
day is short is a dataset whose "days per year" arithmetic is quietly wrong
|
||||
everywhere downstream.
|
||||
|
||||
Derived from `brussels()` by trying the only two offsets Belgium has and
|
||||
keeping the one that round-trips, rather than by restating the EU rule here.
|
||||
"""
|
||||
for hours in (1, 2):
|
||||
guess = datetime.fromisoformat(f"{day}T00:00:00").replace(
|
||||
tzinfo=timezone(timedelta(hours=hours))).astimezone(UTC)
|
||||
if brussels(guess).isoformat() == f"{day}T00:00:00+0{hours}:00":
|
||||
return guess
|
||||
raise SystemExit(f"no Brussels midnight for {day!r} - brussels() disagrees "
|
||||
f"with itself, which is a bug in price.py, not here.")
|
||||
|
||||
|
||||
def _months(start: datetime, end: datetime):
|
||||
"""[start, end) in month-sized chunks, so a bad chunk names its own window."""
|
||||
a = start
|
||||
while a < end:
|
||||
b = min(end, (a.replace(day=1) + timedelta(days=32)).replace(day=1))
|
||||
yield a, b
|
||||
a = b
|
||||
|
||||
|
||||
def fetch(start: datetime, end: datetime):
|
||||
"""Raw {unix_second: EUR/MWh} over [start, end), deduplicated.
|
||||
|
||||
⚠️ A `null` price is DROPPED, never coerced. The API returns null for an
|
||||
interval it holds no result for, and `or 0.0` is the version of this line
|
||||
that ships a year of free electricity.
|
||||
"""
|
||||
seen, licences, nulls = {}, Counter(), 0
|
||||
for a, b in _months(start, end):
|
||||
# ⚠️ THE API'S `end` IS AN INCLUSIVE LOCAL DAY, AND THE WINDOW'S IS AN
|
||||
# EXCLUSIVE INSTANT. Ask for the day containing the LAST hour of the
|
||||
# chunk, derived from the instant rather than by subtracting a calendar
|
||||
# day from the bound: `b - 1 day` drops the final local day whenever the
|
||||
# window ends at local midnight, which is exactly how this window ends.
|
||||
# The first run lost 2026-08-31 that way, silently - 8736 points instead
|
||||
# of 8760 - and the points-plus-gaps accounting in report() is what
|
||||
# noticed. A day nobody asked for is not a day with no prices.
|
||||
first = brussels(a).date().isoformat()
|
||||
last = brussels(b - timedelta(hours=1)).date().isoformat()
|
||||
url = f"{API}?bzn={BZN}&start={first}&end={last}"
|
||||
d = _get(url)
|
||||
lic = str(d.get("license_info", ""))
|
||||
licences[lic] += 1
|
||||
if LICENCE_MUST_CONTAIN not in lic:
|
||||
raise SystemExit(
|
||||
f"REFUSING TO WRITE. {url} came back under licence {lic!r}, "
|
||||
f"which does not say {LICENCE_MUST_CONTAIN!r}. The BE zone was "
|
||||
f"redistributable when this card ran; if that has changed, the "
|
||||
f"right output is this script and a checksum, not the data.")
|
||||
unit = str(d.get("unit", ""))
|
||||
if "MWh" not in unit:
|
||||
raise SystemExit(
|
||||
f"REFUSING TO WRITE. {url} reports unit {unit!r}, not EUR/MWh. "
|
||||
f"A silent unit change is a factor of 1000 on every price.")
|
||||
for t, p in zip(d["unix_seconds"], d["price"]):
|
||||
if p is None:
|
||||
nulls += 1
|
||||
continue
|
||||
if start.timestamp() <= t < end.timestamp():
|
||||
seen[int(t)] = float(p)
|
||||
print(f" {a.date()} .. {b.date()} {len(d['price']):5d} intervals",
|
||||
file=sys.stderr)
|
||||
time.sleep(PACE_S)
|
||||
return seen, licences, nulls
|
||||
|
||||
|
||||
def to_hourly(raw: dict):
|
||||
"""Hourly means keyed by UTC hour. Returns (hours, gaps, shape_counts).
|
||||
|
||||
An hour is emitted only when every interval the source used for it arrived:
|
||||
1 of 1 where the source was hourly, 4 of 4 where it was quarter-hourly.
|
||||
Anything else is a gap and is named as one.
|
||||
"""
|
||||
buckets = defaultdict(dict)
|
||||
for t, p in raw.items():
|
||||
buckets[t - (t % 3600)][t % 3600] = p
|
||||
|
||||
hours, gaps, shapes = {}, [], Counter()
|
||||
for h in sorted(buckets):
|
||||
got = buckets[h]
|
||||
if set(got) == {0}:
|
||||
shapes["hourly"] += 1
|
||||
hours[h] = got[0]
|
||||
elif set(got) == {0, 900, 1800, 2700}:
|
||||
shapes["quarter_hourly_mean"] += 1
|
||||
hours[h] = sum(got.values()) / 4.0
|
||||
else:
|
||||
gaps.append({
|
||||
"hour_utc": datetime.fromtimestamp(h, UTC).isoformat(),
|
||||
"intervals_present": sorted(got),
|
||||
"why": "incomplete hour - dropped rather than averaged over "
|
||||
"what arrived; a partial read is not an observation",
|
||||
})
|
||||
return hours, gaps, shapes
|
||||
|
||||
|
||||
def canonical(hours: dict) -> list:
|
||||
"""9.3 points. THREE FIELDS, rendered at the Brussels offset for the instant."""
|
||||
return [{"start": brussels(datetime.fromtimestamp(h, UTC)).isoformat(),
|
||||
"eur_per_kwh": round(hours[h] / 1000.0, 6) + 0.0,
|
||||
"provisional": False}
|
||||
for h in sorted(hours)]
|
||||
|
||||
|
||||
def expected_hours(start: datetime, end: datetime) -> int:
|
||||
"""Whole hours in the window. Derived, rather than 8760 typed in."""
|
||||
return int((end - start).total_seconds() // 3600)
|
||||
|
||||
|
||||
def per_local_day(points) -> Counter:
|
||||
"""Points per BRUSSELS calendar day - the count that exposes a DST bug."""
|
||||
n = Counter()
|
||||
for p in points:
|
||||
n[p["start"][:10]] += 1
|
||||
return n
|
||||
|
||||
|
||||
def digest(points) -> str:
|
||||
"""A checksum over the POINTS, so reformatting the envelope does not move it."""
|
||||
h = hashlib.sha256()
|
||||
for p in points:
|
||||
h.update(f"{p['start']}|{p['eur_per_kwh']:.6f}|{int(p['provisional'])}\n"
|
||||
.encode())
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def load(path: str) -> dict:
|
||||
op = gzip.open if path.endswith(".gz") else open
|
||||
with op(path, "rt", encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
|
||||
|
||||
def report(doc, *, start=None, end=None) -> int:
|
||||
"""Re-derive every claim the file makes about itself. Returns failures."""
|
||||
pts = doc["prices"]
|
||||
prov = doc["provenance"]
|
||||
bad = 0
|
||||
|
||||
def ck(name, cond):
|
||||
nonlocal bad
|
||||
print(f" {'ok ' if cond else 'FAIL'} {name}")
|
||||
if not cond:
|
||||
bad += 1
|
||||
|
||||
ck(f"the checksum over the {len(pts)} points matches the recorded one "
|
||||
f"({prov['sha256_of_points'][:16]}...)",
|
||||
digest(pts) == prov["sha256_of_points"])
|
||||
ck("every point has exactly the three canonical fields and nothing else",
|
||||
all(set(p) == {"start", "eur_per_kwh", "provisional"} for p in pts))
|
||||
ck("every start carries a UTC offset, and it is +01:00 or +02:00 - a naive "
|
||||
"timestamp here is a wall clock plus an assumption",
|
||||
bool(pts) and all(p["start"][-6:] in ("+01:00", "+02:00") for p in pts))
|
||||
ck("the series is strictly increasing in time, so no instant is duplicated",
|
||||
all(datetime.fromisoformat(a["start"]) < datetime.fromisoformat(b["start"])
|
||||
for a, b in zip(pts, pts[1:])))
|
||||
ck("consecutive points are exactly one hour apart AS INSTANTS, so the two "
|
||||
"02:00s of the October day are two hours rather than one",
|
||||
all((datetime.fromisoformat(b["start"])
|
||||
- datetime.fromisoformat(a["start"])) == timedelta(hours=1)
|
||||
for a, b in zip(pts, pts[1:])))
|
||||
|
||||
days = per_local_day(pts)
|
||||
odd = {d: n for d, n in days.items() if n != 24}
|
||||
ck(f"exactly two Brussels days are not 24 hours long, and they are the "
|
||||
f"transitions: {sorted(odd.items())}",
|
||||
sorted(odd.values()) == [23, 25] and len(odd) == 2)
|
||||
spring = [d for d, n in odd.items() if n == 23]
|
||||
autumn = [d for d, n in odd.items() if n == 25]
|
||||
ck(f"the 23-hour day {spring} is in March and the 25-hour day {autumn} is "
|
||||
f"in October, which is the direction the EU rule actually runs",
|
||||
len(spring) == 1 and len(autumn) == 1
|
||||
and spring[0][5:7] == "03" and autumn[0][5:7] == "10")
|
||||
if autumn:
|
||||
twice = [p["start"] for p in pts
|
||||
if p["start"].startswith(autumn[0] + "T02")]
|
||||
ck(f"...and 02:00 on {autumn[0]} occurs TWICE at two different offsets "
|
||||
f"{twice} - exactly the case a 24-slot local-hour array collapses",
|
||||
len(twice) == 2 and twice[0][-6:] == "+02:00"
|
||||
and twice[1][-6:] == "+01:00")
|
||||
ck(f"...and the two carry DIFFERENT prices, so the 25th hour is a real "
|
||||
f"observation and not the same one written down twice",
|
||||
len({p["eur_per_kwh"] for p in pts
|
||||
if p["start"].startswith(autumn[0] + "T02")}) == 2)
|
||||
if spring:
|
||||
ck(f"...and 02:00 on {spring[0]} does not occur at all, because that "
|
||||
f"wall clock reading never happened in Belgium",
|
||||
not any(p["start"].startswith(spring[0] + "T02") for p in pts))
|
||||
|
||||
if start and end:
|
||||
want = expected_hours(start, end)
|
||||
ck(f"{len(pts)} points for a window of {want} whole hours, and the "
|
||||
f"{len(prov['gaps'])} recorded gaps account for the difference "
|
||||
f"exactly", len(pts) + len(prov["gaps"]) == want)
|
||||
|
||||
# ⚠️ A ZERO IS NOT AUTOMATICALLY A DEFECT HERE, AND SAYING IT WAS WOULD BE
|
||||
# THE WRONG LESSON. The Belgian market really does clear at 0.00 EUR/MWh in
|
||||
# solar-glut hours; this window contains such hours. What must be impossible
|
||||
# is a zero that arrived by COERCION - a dropped read turned into a free
|
||||
# hour. That is excluded structurally rather than by outlawing the value:
|
||||
# nulls are dropped, incomplete hours become gaps, and the accounting above
|
||||
# shows points + gaps covering every hour of the window, so every emitted
|
||||
# point stands for intervals the source actually published.
|
||||
zeros = [p["start"] for p in pts if p["eur_per_kwh"] == 0.0]
|
||||
ck(f"the {len(zeros)} hours priced at exactly zero match the count recorded "
|
||||
f"at build time, so no zero appeared between the fetch and the file",
|
||||
len(zeros) == prov["exact_zero_hours"])
|
||||
ck("...and none of them is a coerced read: every emitted hour is backed by "
|
||||
"published intervals, which is what the points-plus-gaps accounting "
|
||||
"above establishes",
|
||||
len(prov["gaps"]) == 0 or all("intervals_present" in g
|
||||
for g in prov["gaps"]))
|
||||
ck("the figures are declared RAW WHOLESALE, and the all-in assumption is "
|
||||
"recorded as an assumption rather than applied",
|
||||
prov["all_in"] is False
|
||||
and "ASSUMPTION" in prov["all_in_assumption"]["status"])
|
||||
return bad
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
ap.add_argument("--start", default="2025-09-01")
|
||||
ap.add_argument("--end", default="2026-09-01",
|
||||
help="exclusive; both bounds are BRUSSELS-local midnights")
|
||||
ap.add_argument("--out", default=None)
|
||||
ap.add_argument("--verify", default=None,
|
||||
help="re-derive the claims of an existing file; no network")
|
||||
a = ap.parse_args()
|
||||
|
||||
if a.verify:
|
||||
doc = load(a.verify)
|
||||
print(f"verifying {a.verify}")
|
||||
s = datetime.fromisoformat(doc["provenance"]["window_utc"]["start"])
|
||||
e = datetime.fromisoformat(doc["provenance"]["window_utc"]["end"])
|
||||
bad = report(doc, start=s, end=e)
|
||||
print("OK" if not bad else f"{bad} FAILED")
|
||||
return 1 if bad else 0
|
||||
|
||||
start = local_midnight_utc(a.start)
|
||||
end = local_midnight_utc(a.end)
|
||||
out = a.out or f"scenarios/epex-be-dayahead-{a.start}_{a.end}.json"
|
||||
|
||||
print(f"fetching {BZN} day-ahead {start.date()} .. {end.date()}",
|
||||
file=sys.stderr)
|
||||
raw, licences, nulls = fetch(start, end)
|
||||
hours, gaps, shapes = to_hourly(raw)
|
||||
pts = canonical(hours)
|
||||
|
||||
doc = {
|
||||
"provenance": {
|
||||
"card": "DATA-02",
|
||||
"what": "EPEX BE day-ahead auction clearing prices, hourly",
|
||||
"source": f"{API}?bzn={BZN} (Energy-Charts API, Fraunhofer ISE)",
|
||||
"upstream": "Bundesnetzagentur | SMARD.de",
|
||||
"licence": "CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/)",
|
||||
"licence_checked": "before committing anything; the API's OpenAPI "
|
||||
"document lists BE among the CC BY 4.0 zones and "
|
||||
"the remaining zones as private/internal use "
|
||||
"only, so redistribution of THIS zone is "
|
||||
"permitted with attribution",
|
||||
"licence_as_returned": sorted(licences),
|
||||
"attribution": ATTRIBUTION,
|
||||
"cross_check": "SMARD chart_data 4996/DE over 2026-04-10 matched "
|
||||
"this feed on all 96 quarter-hours, max abs "
|
||||
"difference 0.00 EUR/MWh (2026-08-31)",
|
||||
"retrieved_utc": datetime.now(UTC).replace(microsecond=0).isoformat(),
|
||||
"fetched_by": "scenarios/fetch_epex_be.py",
|
||||
"window_utc": {"start": start.isoformat(), "end": end.isoformat()},
|
||||
"unit": "EUR per kWh (source publishes EUR/MWh; divided by 1000)",
|
||||
"all_in": False,
|
||||
"all_in_note": "RAW WHOLESALE. No supplier markup, no network or "
|
||||
"transmission tariff, no levies, no VAT. 9.3's "
|
||||
"canonical point is all-in and this is NOT; the "
|
||||
"consumer applies the assumption below, visibly.",
|
||||
"all_in_assumption": ALL_IN_ASSUMPTION,
|
||||
"resolution": {
|
||||
"note": "EPEX day-ahead moved to a 15-minute market time unit "
|
||||
"in Oct 2025, part-way through this window.",
|
||||
"hours_from_hourly_source": shapes["hourly"],
|
||||
"hours_from_quarter_hourly_mean": shapes["quarter_hourly_mean"],
|
||||
"aggregation": "unweighted mean of the four quarters; a stated "
|
||||
"approximation of the hourly product, and a "
|
||||
"LOWER bound on the spread a 15-minute strategy "
|
||||
"would have seen",
|
||||
},
|
||||
"timezone": "starts rendered at the Brussels offset by "
|
||||
"app.price.brussels(); instants carried in UTC, so the "
|
||||
"transition days come out 23 and 25 points by "
|
||||
"construction rather than by a special case",
|
||||
"nulls_dropped": nulls,
|
||||
"gaps": gaps,
|
||||
"gaps_note": "hours the source did not publish completely. Dropped, "
|
||||
"never zero-filled: a missing hour is not a free hour.",
|
||||
"points": len(pts),
|
||||
"exact_zero_hours": sum(1 for p in pts if p["eur_per_kwh"] == 0.0),
|
||||
"negative_hours": sum(1 for p in pts if p["eur_per_kwh"] < 0),
|
||||
"zero_note": "REAL CLEARINGS AT 0.00 EUR/MWh, not dropped reads. "
|
||||
"Nulls are dropped and incomplete hours become gaps, "
|
||||
"so points + gaps == hours in the window and no point "
|
||||
"stands in for something that failed to arrive.",
|
||||
"sha256_of_points": digest(pts),
|
||||
},
|
||||
"prices": pts,
|
||||
}
|
||||
|
||||
with open(out, "w", encoding="utf-8", newline="\n") as f:
|
||||
json.dump(doc, f, indent=1, ensure_ascii=False)
|
||||
f.write("\n")
|
||||
print(f"wrote {out} {len(pts)} points {os.path.getsize(out)} bytes",
|
||||
file=sys.stderr)
|
||||
print(f"verifying {out}")
|
||||
return 1 if report(doc, start=start, end=end) else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,167 @@
|
||||
# 30 days of P1 net power — 2026-08-01 … 2026-08-30
|
||||
|
||||
`sensor.p1_meter_active_power` out of Home Assistant's recorder, one gzipped
|
||||
JSONL file per **local** day (Europe/Brussels), same schema as the two files one
|
||||
directory up:
|
||||
|
||||
{"t": "2026-08-22T22:00:00+00:00", "w": -25.0}
|
||||
|
||||
**485,841 samples, 30/30 days read, 0 days failed, 4.13 MB gzipped.**
|
||||
Produced by `tools/export_p1_history.py`; `manifest.json` here carries the
|
||||
per-day counts, sha256 of every file, and every gap.
|
||||
|
||||
python3 tools/export_p1_history.py --days 30 --end-date 2026-08-30 \
|
||||
--out-dir scenarios/p1-net-30d-2026-08
|
||||
|
||||
## Why this exists
|
||||
|
||||
[[TARIFF-01]] AC 3 and [[SAFETY-07]] AC 3 both ask for *"monthly peak held under
|
||||
the soft limit in >= 95 % of intervals over a 30-day simulation replay"*, and
|
||||
both were merged with the criterion honestly unmet because only two days of
|
||||
capture existed. `test_tariff.py`'s docstring still recorded the reason as
|
||||
"nothing longer was ever captured" — which was true about the past and was
|
||||
quietly read as a statement about the future. It was not one. Probed on
|
||||
2026-08-31, HA's recorder answered a 20-minute window with 230 samples at 30
|
||||
days back and 0 at 45, so the whole month was still there and was exported the
|
||||
same day. **The window rolls: 2026-08-01 leaves the recorder around 2026-09-15.**
|
||||
|
||||
## The size decision — COMMITTED, deliberately, at 4.13 MB
|
||||
|
||||
Three options were on the table. This one was taken and the cost is stated
|
||||
rather than absorbed, and it is measured rather than estimated - a
|
||||
`git bundle` of the whole history before and after this commit:
|
||||
|
||||
release/1.0 @ 86c43eb 1.58 MB
|
||||
DATA-01 5.28 MB +3.70 MB, x3.3
|
||||
|
||||
A full clone of this repository therefore more than triples, and a Home
|
||||
Assistant supervisor clones it on every add-on install and update. That is the
|
||||
price; the paragraphs below are why it was judged worth paying rather than
|
||||
avoided by making the data worse or making it disappear.
|
||||
|
||||
* **Downsampling is not available.** It is not a matter of taste: the shipped
|
||||
`meter_max_age_s` is **30 s**, which is the age past which the controller's
|
||||
own ingest stops counting a held reading as coverage. Any resample coarser
|
||||
than 30 s therefore converts real coverage into modelled meter-gap and changes
|
||||
the very number AC 3 measures. Resampling at or under 30 s saves almost
|
||||
nothing against a 5 s cadence.
|
||||
* **"Outside the repo with a pointer" is what already happened, and it is why
|
||||
this card exists.** The two committed days came from the infra repo's private
|
||||
`sim/scenarios/`, the one-off export script was thrown away, and three cards
|
||||
then deferred an acceptance criterion on the belief that the data could not be
|
||||
produced again. `test_tariff.py` states the general rule verbatim: *a
|
||||
regression fixture CI cannot see is not a regression fixture.* CI's token is
|
||||
minted for this repository only.
|
||||
* **So: committed** — but in a SUBDIRECTORY, which is load-bearing. Both
|
||||
`test_tariff.py` part 9 and `test_peakguard.py` part 6 do
|
||||
`(HERE / "scenarios").glob("p1-net-*.jsonl.gz")`, which does not recurse. Drop
|
||||
these thirty files beside the two and CI grows sixty full-day
|
||||
replays - about 50 s of pure compute - on every PR forever, `test_tariff.py`'s
|
||||
`check(... replay_days < 30)` starts failing, and both files' honesty notes
|
||||
become false. In `p1-net-30d-2026-08/` they are visible to CI, invisible to
|
||||
the globs, and the two committed days keep their job as the small fixtures the
|
||||
suites grade against.
|
||||
|
||||
They are also written once and never edited, so git stores one already-deflated
|
||||
blob per day with no delta churn.
|
||||
|
||||
## Gaps are visible, never interpolated
|
||||
|
||||
Nothing is filled, carried forward or resampled. A hole in the recorder is a
|
||||
hole here — consecutive `t` values further apart than the cadence — which is
|
||||
exactly what the controller's freshness rule already reads as *no coverage*, so
|
||||
a missing hour replays as a missing hour rather than as an hour of whatever the
|
||||
last sample said.
|
||||
|
||||
**13 gaps over 30 s, 1291 s in total: 99.950 % of the month is covered.**
|
||||
All of them are listed in `manifest.json` and by
|
||||
`python3 tools/replay_ac3.py <dir> --report-gaps`. The longest is 263 s on
|
||||
2026-08-11.
|
||||
|
||||
Three samples in the month carried the state `unavailable` rather than a number
|
||||
(2026-08-18 02:03:54Z and 04:10:41Z, 2026-08-25 01:52:02Z). There is no float to
|
||||
write and the committed schema has no slot for a non-number, so they are absent
|
||||
from the series and recorded individually in `manifest.json` under
|
||||
`non_numeric_states`. Each one sits inside a gap that is already listed, which
|
||||
is the honest rendering: the meter was not reporting a power then.
|
||||
|
||||
**A failed read is never an empty hour.** If a day's read fails, the exporter
|
||||
writes NO FILE, records `"read": "FAILED"` with the error, and exits non-zero —
|
||||
so a missing day is unreadable-and-known rather than silently zero. The entity
|
||||
is also proved to exist through `/api/states` before any day is trusted, because
|
||||
a typo would otherwise answer `200 []` thirty times and produce a beautifully
|
||||
consistent dataset of nothing. On this run: 30 read, 0 failed, 0 empty.
|
||||
|
||||
## AC 3, measured
|
||||
|
||||
cd goodwe_controller
|
||||
python3 tools/replay_ac3.py scenarios/p1-net-30d-2026-08
|
||||
|
||||
485841 samples, 2879 closed quarters (30.0 days' worth)
|
||||
month 2026-08: peak 5029.8 W uncontrolled -> 4107.3 W guarded
|
||||
|
||||
TARIFF-01 AC 3 (UNCONTROLLED): 2847/2879 = 98.89 % of quarters at or under 3500 W
|
||||
SAFETY-07 AC 3 (GUARDED): 2850/2879 = 98.99 %
|
||||
guard cycles 143810, engaged on the measurement 1542, blind 195,
|
||||
saturated 0, modelled discharge 8060 Wh
|
||||
|
||||
2879 rather than 2880 quarters: the last quarter of 2026-08-30 closes only when
|
||||
a telegram past its boundary arrives, and that telegram is 2026-08-31's.
|
||||
|
||||
### What the numbers actually say — three findings, not a pass
|
||||
|
||||
1. **AC 3 is met on the ">= 95 % of intervals" reading, and the criterion turns
|
||||
out to be nearly insensitive.** The UNCONTROLLED month — no controller, no
|
||||
peak shaving, nothing running — already scores 98.89 %. A criterion that a
|
||||
house passes by doing nothing does not discriminate between a working guard
|
||||
and an absent one. That is a finding about the acceptance criterion, and it
|
||||
is reported rather than filed as a win.
|
||||
2. **On the other reading of the same sentence, AC 3 is NOT met.** "Monthly peak
|
||||
held under the soft limit" taken as *the peak itself* fails: the guard pulls
|
||||
August's peak from **5029.8 W to 4107.3 W** (-922.5 W, -18.3 %), which is
|
||||
real money on a Belgian capacity tariff, but 4107.3 W is still over the
|
||||
3500 W soft limit. Both readings are printed by the tool; neither is hidden.
|
||||
3. **The guard stops defending the soft limit once the month's peak is set, and
|
||||
that is by design.** `quarter_ceiling_w` uses `CEILING_MONTH_PEAK`: the
|
||||
billed quantity is the month's maximum, so a quarter under an
|
||||
already-recorded peak costs nothing extra and the guard does not spend the
|
||||
battery on it. The month's 32 over-cap quarters fall on four nights
|
||||
(2026-08-17, -18, -20, -21); **31 of them are pulled down** — 7494 W of
|
||||
quarter-average removed in total, 8060 Wh of modelled discharge — but only
|
||||
**3 land under 3500 W**, because by then the ceiling being defended is the
|
||||
running month peak (~4107 W), not the soft limit. The single untouched
|
||||
quarter, 2026-08-18T08:15Z at 4039.7 W, is the same rule seen from the other
|
||||
side: the running peak was already 4833 W, so 4039.7 W added nothing to the
|
||||
bill and the guard correctly stayed out. AC 3's wording asks the guard for
|
||||
something its own tariff logic deliberately does not optimise.
|
||||
|
||||
Also worth an eye: **195 blind engagements** over 143,810 cycles — the guard
|
||||
acting on a projection it could not fully cover. On the two committed days that
|
||||
count was 5. It scales with the gaps above.
|
||||
|
||||
## Verification of the exporter
|
||||
|
||||
`tools/export_p1_history.py --verify` re-fetches a committed day by the exact
|
||||
route used here and diffs it against the file:
|
||||
|
||||
python3 tools/export_p1_history.py \
|
||||
--verify scenarios/p1-net-2026-08-20.jsonl.gz \
|
||||
scenarios/p1-net-2026-08-23.jsonl.gz
|
||||
|
||||
Both days come back **byte-identical after decompression** — 865,024 B /
|
||||
15,600 samples and 894,387 B / 16,351 samples — and the copies of those two days
|
||||
inside this directory are byte-identical to the committed ones too. The gzip
|
||||
CONTAINERS differ by design: a gzip header carries an mtime and a stored
|
||||
filename, and this exporter writes mtime 0 so its own output is reproducible,
|
||||
where the 2026-08-25 one-off wrote a wall-clock mtime. Content equality is the
|
||||
claim; container equality would only assert that two files were written at the
|
||||
same second.
|
||||
|
||||
`tools/replay_ac3.py` is checked the same way rather than trusted: pointed at
|
||||
`scenarios/` it must reproduce `test_peakguard.py` part 6's published totals,
|
||||
and `--expect` makes it a hard check.
|
||||
|
||||
python3 tools/replay_ac3.py scenarios --expect 189/190
|
||||
|
||||
reproduces 189/190 quarters, the 5029.8 W billed quarter, the 3485.3 W guarded
|
||||
result and the 878 Wh of modelled discharge that part 6 prints.
|
||||
@@ -0,0 +1,767 @@
|
||||
{
|
||||
"generated": "2026-08-31T08:42:40.614548+00:00",
|
||||
"generator": "tools/export_p1_history.py",
|
||||
"source": "http://192.168.2.158:8123/api/history/period",
|
||||
"entity": "sensor.p1_meter_active_power",
|
||||
"timezone": "Europe/Brussels",
|
||||
"gap_threshold_s": 30.0,
|
||||
"format": "{\"t\": <ISO-8601 UTC>, \"w\": <float watts>} per line, gzip",
|
||||
"days": [
|
||||
{
|
||||
"date": "2026-08-01",
|
||||
"window": [
|
||||
"2026-08-01T00:00:00+02:00",
|
||||
"2026-08-02T00:00:00+02:00"
|
||||
],
|
||||
"read": "OK",
|
||||
"http_bytes": 1128060,
|
||||
"attempts": 1,
|
||||
"samples": 16511,
|
||||
"non_numeric_states": [],
|
||||
"first": "2026-07-31T22:00:00+00:00",
|
||||
"last": "2026-08-01T21:59:56.268499+00:00",
|
||||
"gaps": [],
|
||||
"covered_span_s": 86396.3,
|
||||
"mean_cadence_s": 5.233,
|
||||
"file": "p1-net-2026-08-01.jsonl.gz",
|
||||
"bytes_gz": 140531,
|
||||
"bytes_raw": 913203,
|
||||
"sha256_raw": "120de2a0b7eb552281dac4bc1f8fd76d947ba72d1f5b426d9dcdd85ec103bd06",
|
||||
"sha256_gz": "e09bdee349dd3668a073b7fd77974e639c269ec37e73e81a9706cadde083f064"
|
||||
},
|
||||
{
|
||||
"date": "2026-08-02",
|
||||
"window": [
|
||||
"2026-08-02T00:00:00+02:00",
|
||||
"2026-08-03T00:00:00+02:00"
|
||||
],
|
||||
"read": "OK",
|
||||
"http_bytes": 1115387,
|
||||
"attempts": 1,
|
||||
"samples": 16303,
|
||||
"non_numeric_states": [],
|
||||
"first": "2026-08-01T22:00:00+00:00",
|
||||
"last": "2026-08-02T21:59:55.191360+00:00",
|
||||
"gaps": [],
|
||||
"covered_span_s": 86395.2,
|
||||
"mean_cadence_s": 5.3,
|
||||
"file": "p1-net-2026-08-02.jsonl.gz",
|
||||
"bytes_gz": 141404,
|
||||
"bytes_raw": 903234,
|
||||
"sha256_raw": "9ab4891c0abf9d621fa528848fc3a874687843804768e8aeab6a88f7bb04b679",
|
||||
"sha256_gz": "94774139b3e19d04bcda3ac5ea988dd4d645e99004f90b917c6b0bf3fbac21cb"
|
||||
},
|
||||
{
|
||||
"date": "2026-08-03",
|
||||
"window": [
|
||||
"2026-08-03T00:00:00+02:00",
|
||||
"2026-08-04T00:00:00+02:00"
|
||||
],
|
||||
"read": "OK",
|
||||
"http_bytes": 1123668,
|
||||
"attempts": 1,
|
||||
"samples": 16424,
|
||||
"non_numeric_states": [],
|
||||
"first": "2026-08-02T22:00:00+00:00",
|
||||
"last": "2026-08-03T21:59:55.255808+00:00",
|
||||
"gaps": [],
|
||||
"covered_span_s": 86395.3,
|
||||
"mean_cadence_s": 5.261,
|
||||
"file": "p1-net-2026-08-03.jsonl.gz",
|
||||
"bytes_gz": 144202,
|
||||
"bytes_raw": 909942,
|
||||
"sha256_raw": "13f8dd904a31b5b67fcfde04f6afc49c34c3a9504617278d79d87516fcd6441f",
|
||||
"sha256_gz": "e1bc0cb0e271cbc8d896aee97aa0f5c18e49e78905d1aaf137904a768047c7bc"
|
||||
},
|
||||
{
|
||||
"date": "2026-08-04",
|
||||
"window": [
|
||||
"2026-08-04T00:00:00+02:00",
|
||||
"2026-08-05T00:00:00+02:00"
|
||||
],
|
||||
"read": "OK",
|
||||
"http_bytes": 1108582,
|
||||
"attempts": 1,
|
||||
"samples": 16286,
|
||||
"non_numeric_states": [],
|
||||
"first": "2026-08-03T22:00:00+00:00",
|
||||
"last": "2026-08-04T21:59:58.729138+00:00",
|
||||
"gaps": [],
|
||||
"covered_span_s": 86398.7,
|
||||
"mean_cadence_s": 5.305,
|
||||
"file": "p1-net-2026-08-04.jsonl.gz",
|
||||
"bytes_gz": 136505,
|
||||
"bytes_raw": 896650,
|
||||
"sha256_raw": "a65cd9d1ceda61e5a40043edb401c2154feea2b36bd3221710df808d778eabce",
|
||||
"sha256_gz": "c19b19ac890f4caad4140cb27d2fe6f3e972545f664127e5d9f457e711ad8c88"
|
||||
},
|
||||
{
|
||||
"date": "2026-08-05",
|
||||
"window": [
|
||||
"2026-08-05T00:00:00+02:00",
|
||||
"2026-08-06T00:00:00+02:00"
|
||||
],
|
||||
"read": "OK",
|
||||
"http_bytes": 1136556,
|
||||
"attempts": 1,
|
||||
"samples": 16655,
|
||||
"non_numeric_states": [],
|
||||
"first": "2026-08-04T22:00:00+00:00",
|
||||
"last": "2026-08-05T21:59:56.189152+00:00",
|
||||
"gaps": [],
|
||||
"covered_span_s": 86396.2,
|
||||
"mean_cadence_s": 5.188,
|
||||
"file": "p1-net-2026-08-05.jsonl.gz",
|
||||
"bytes_gz": 142561,
|
||||
"bytes_raw": 919827,
|
||||
"sha256_raw": "dd327685c6f322bfaa49bc5bf228301e790e5a96fd7c23c487b845e44a962db4",
|
||||
"sha256_gz": "5ff7a1336c49ba38b8058820181dd8ed9c2b8db41b5a3a52412a5a3d8c515332"
|
||||
},
|
||||
{
|
||||
"date": "2026-08-06",
|
||||
"window": [
|
||||
"2026-08-06T00:00:00+02:00",
|
||||
"2026-08-07T00:00:00+02:00"
|
||||
],
|
||||
"read": "OK",
|
||||
"http_bytes": 1124419,
|
||||
"attempts": 1,
|
||||
"samples": 16412,
|
||||
"non_numeric_states": [],
|
||||
"first": "2026-08-05T22:00:00+00:00",
|
||||
"last": "2026-08-06T21:59:57.192711+00:00",
|
||||
"gaps": [],
|
||||
"covered_span_s": 86397.2,
|
||||
"mean_cadence_s": 5.265,
|
||||
"file": "p1-net-2026-08-06.jsonl.gz",
|
||||
"bytes_gz": 142313,
|
||||
"bytes_raw": 910849,
|
||||
"sha256_raw": "7cd1fe8315e24dc6391693c49d6306b0c0cf9b6c3a478e457da921001cea930c",
|
||||
"sha256_gz": "9108f169d645b9da07d4ae310666a1365ea07275ff311cd60adad1b702edbf11"
|
||||
},
|
||||
{
|
||||
"date": "2026-08-07",
|
||||
"window": [
|
||||
"2026-08-07T00:00:00+02:00",
|
||||
"2026-08-08T00:00:00+02:00"
|
||||
],
|
||||
"read": "OK",
|
||||
"http_bytes": 1087531,
|
||||
"attempts": 1,
|
||||
"samples": 15952,
|
||||
"non_numeric_states": [],
|
||||
"first": "2026-08-06T22:00:00+00:00",
|
||||
"last": "2026-08-07T21:59:58.195053+00:00",
|
||||
"gaps": [],
|
||||
"covered_span_s": 86398.2,
|
||||
"mean_cadence_s": 5.416,
|
||||
"file": "p1-net-2026-08-07.jsonl.gz",
|
||||
"bytes_gz": 135979,
|
||||
"bytes_raw": 879941,
|
||||
"sha256_raw": "e0f67a9214980e2fd4893208cb402165065dadce2105ce1581c6b1d49952f39a",
|
||||
"sha256_gz": "b70b84f3743d1d84055c911bcd5589cb8f0371e8916bde741308c5bb50702c29"
|
||||
},
|
||||
{
|
||||
"date": "2026-08-08",
|
||||
"window": [
|
||||
"2026-08-08T00:00:00+02:00",
|
||||
"2026-08-09T00:00:00+02:00"
|
||||
],
|
||||
"read": "OK",
|
||||
"http_bytes": 1058569,
|
||||
"attempts": 1,
|
||||
"samples": 15468,
|
||||
"non_numeric_states": [],
|
||||
"first": "2026-08-07T22:00:00+00:00",
|
||||
"last": "2026-08-08T21:59:52.805887+00:00",
|
||||
"gaps": [],
|
||||
"covered_span_s": 86392.8,
|
||||
"mean_cadence_s": 5.586,
|
||||
"file": "p1-net-2026-08-08.jsonl.gz",
|
||||
"bytes_gz": 134025,
|
||||
"bytes_raw": 857271,
|
||||
"sha256_raw": "0be14ca7593b4c7d68570115cc26e24f6a26ab87fe3c168a8b942b167e8d4f68",
|
||||
"sha256_gz": "d93dcc8ca3eae03af13b9ae36acd5ab1eaa1e7ee93c237d386e8ded1c61f5906"
|
||||
},
|
||||
{
|
||||
"date": "2026-08-09",
|
||||
"window": [
|
||||
"2026-08-09T00:00:00+02:00",
|
||||
"2026-08-10T00:00:00+02:00"
|
||||
],
|
||||
"read": "OK",
|
||||
"http_bytes": 1059349,
|
||||
"attempts": 1,
|
||||
"samples": 15508,
|
||||
"non_numeric_states": [],
|
||||
"first": "2026-08-08T22:00:00+00:00",
|
||||
"last": "2026-08-09T21:59:58.178998+00:00",
|
||||
"gaps": [],
|
||||
"covered_span_s": 86398.2,
|
||||
"mean_cadence_s": 5.572,
|
||||
"file": "p1-net-2026-08-09.jsonl.gz",
|
||||
"bytes_gz": 135697,
|
||||
"bytes_raw": 857531,
|
||||
"sha256_raw": "f4793799173c502fcee5f78e2d9b0dcc984b5d2d8bd2fc0db0cd0f8d403733b3",
|
||||
"sha256_gz": "2fea6c5c8b1452d72ad5aa3b0ae9755bb2ea08071514c08b1a3b1155ef457cf1"
|
||||
},
|
||||
{
|
||||
"date": "2026-08-10",
|
||||
"window": [
|
||||
"2026-08-10T00:00:00+02:00",
|
||||
"2026-08-11T00:00:00+02:00"
|
||||
],
|
||||
"read": "OK",
|
||||
"http_bytes": 1066721,
|
||||
"attempts": 1,
|
||||
"samples": 15594,
|
||||
"non_numeric_states": [],
|
||||
"first": "2026-08-09T22:00:00+00:00",
|
||||
"last": "2026-08-10T21:59:59.170056+00:00",
|
||||
"gaps": [],
|
||||
"covered_span_s": 86399.2,
|
||||
"mean_cadence_s": 5.541,
|
||||
"file": "p1-net-2026-08-10.jsonl.gz",
|
||||
"bytes_gz": 136682,
|
||||
"bytes_raw": 863785,
|
||||
"sha256_raw": "ff5c3fa419505127a51acc56dfc13e8437e4ec2c13a11c8d8b2d6c3e20e2410e",
|
||||
"sha256_gz": "4fd30e495f4e6d1c8501d05c23f9891ac34364d86a9c55ac825d52b2ebb31023"
|
||||
},
|
||||
{
|
||||
"date": "2026-08-11",
|
||||
"window": [
|
||||
"2026-08-11T00:00:00+02:00",
|
||||
"2026-08-12T00:00:00+02:00"
|
||||
],
|
||||
"read": "OK",
|
||||
"http_bytes": 1056281,
|
||||
"attempts": 1,
|
||||
"samples": 15371,
|
||||
"non_numeric_states": [],
|
||||
"first": "2026-08-10T22:00:00+00:00",
|
||||
"last": "2026-08-11T21:59:58.608150+00:00",
|
||||
"gaps": [
|
||||
{
|
||||
"from": "2026-08-11T08:00:14.121653+00:00",
|
||||
"to": "2026-08-11T08:02:54.427007+00:00",
|
||||
"seconds": 160.305
|
||||
},
|
||||
{
|
||||
"from": "2026-08-11T17:04:18.517592+00:00",
|
||||
"to": "2026-08-11T17:08:41.759777+00:00",
|
||||
"seconds": 263.242
|
||||
}
|
||||
],
|
||||
"covered_span_s": 86398.6,
|
||||
"mean_cadence_s": 5.621,
|
||||
"file": "p1-net-2026-08-11.jsonl.gz",
|
||||
"bytes_gz": 133711,
|
||||
"bytes_raw": 856244,
|
||||
"sha256_raw": "67c2a740019f8908405b96b3436cd953af27baead2957acc7c1dcf10b37ac94e",
|
||||
"sha256_gz": "4f8c553edc9051644bd7baa659f6f92a8b5f5ce12a0410c8b5235d1e6c3084c9"
|
||||
},
|
||||
{
|
||||
"date": "2026-08-12",
|
||||
"window": [
|
||||
"2026-08-12T00:00:00+02:00",
|
||||
"2026-08-13T00:00:00+02:00"
|
||||
],
|
||||
"read": "OK",
|
||||
"http_bytes": 1124945,
|
||||
"attempts": 1,
|
||||
"samples": 16432,
|
||||
"non_numeric_states": [],
|
||||
"first": "2026-08-11T22:00:00+00:00",
|
||||
"last": "2026-08-12T21:59:58.648966+00:00",
|
||||
"gaps": [],
|
||||
"covered_span_s": 86398.6,
|
||||
"mean_cadence_s": 5.258,
|
||||
"file": "p1-net-2026-08-12.jsonl.gz",
|
||||
"bytes_gz": 136903,
|
||||
"bytes_raw": 911115,
|
||||
"sha256_raw": "73c8a1626640226ddffb32d564557d1cbe57a15367ea1ba3632934e15a1413dc",
|
||||
"sha256_gz": "acec87065b7de2c605db00504ec5a9b3c99584620dfb3b67194e2cf9464d6a5f"
|
||||
},
|
||||
{
|
||||
"date": "2026-08-13",
|
||||
"window": [
|
||||
"2026-08-13T00:00:00+02:00",
|
||||
"2026-08-14T00:00:00+02:00"
|
||||
],
|
||||
"read": "OK",
|
||||
"http_bytes": 1126742,
|
||||
"attempts": 1,
|
||||
"samples": 16473,
|
||||
"non_numeric_states": [],
|
||||
"first": "2026-08-12T22:00:00+00:00",
|
||||
"last": "2026-08-13T21:59:57.562043+00:00",
|
||||
"gaps": [],
|
||||
"covered_span_s": 86397.6,
|
||||
"mean_cadence_s": 5.245,
|
||||
"file": "p1-net-2026-08-13.jsonl.gz",
|
||||
"bytes_gz": 136221,
|
||||
"bytes_raw": 912379,
|
||||
"sha256_raw": "1d9a16c529174bd8c74625a742c46d98de4acf7a045f83df8bdbac22fa86e8e7",
|
||||
"sha256_gz": "adfef36f629decf54c625f2dbfe6b4dab9441218c42557c90ac7f6d331943a59"
|
||||
},
|
||||
{
|
||||
"date": "2026-08-14",
|
||||
"window": [
|
||||
"2026-08-14T00:00:00+02:00",
|
||||
"2026-08-15T00:00:00+02:00"
|
||||
],
|
||||
"read": "OK",
|
||||
"http_bytes": 1124413,
|
||||
"attempts": 1,
|
||||
"samples": 16427,
|
||||
"non_numeric_states": [],
|
||||
"first": "2026-08-13T22:00:00+00:00",
|
||||
"last": "2026-08-14T21:59:55.611487+00:00",
|
||||
"gaps": [],
|
||||
"covered_span_s": 86395.6,
|
||||
"mean_cadence_s": 5.26,
|
||||
"file": "p1-net-2026-08-14.jsonl.gz",
|
||||
"bytes_gz": 135570,
|
||||
"bytes_raw": 910648,
|
||||
"sha256_raw": "dc1417881e54fe215e9fcd4ed643d2482a277d61f8f27f25e2ff1e2cba29f7a8",
|
||||
"sha256_gz": "d4eff781cd16a83fd1be9e643fee5bb5d5897e7d45bb9865972a7304d92c84a4"
|
||||
},
|
||||
{
|
||||
"date": "2026-08-15",
|
||||
"window": [
|
||||
"2026-08-15T00:00:00+02:00",
|
||||
"2026-08-16T00:00:00+02:00"
|
||||
],
|
||||
"read": "OK",
|
||||
"http_bytes": 1124461,
|
||||
"attempts": 1,
|
||||
"samples": 16516,
|
||||
"non_numeric_states": [],
|
||||
"first": "2026-08-14T22:00:00+00:00",
|
||||
"last": "2026-08-15T21:59:56.581991+00:00",
|
||||
"gaps": [],
|
||||
"covered_span_s": 86396.6,
|
||||
"mean_cadence_s": 5.231,
|
||||
"file": "p1-net-2026-08-15.jsonl.gz",
|
||||
"bytes_gz": 137670,
|
||||
"bytes_raw": 909539,
|
||||
"sha256_raw": "f07a242faed68313512e0363d914846522ff839315ad80b55689072ac74e8a69",
|
||||
"sha256_gz": "082314c6003c2208752acc4614b9809f06735d01e216b935ea94faf578c5598e"
|
||||
},
|
||||
{
|
||||
"date": "2026-08-16",
|
||||
"window": [
|
||||
"2026-08-16T00:00:00+02:00",
|
||||
"2026-08-17T00:00:00+02:00"
|
||||
],
|
||||
"read": "OK",
|
||||
"http_bytes": 1127871,
|
||||
"attempts": 1,
|
||||
"samples": 16552,
|
||||
"non_numeric_states": [],
|
||||
"first": "2026-08-15T22:00:00+00:00",
|
||||
"last": "2026-08-16T21:59:59.527710+00:00",
|
||||
"gaps": [],
|
||||
"covered_span_s": 86399.5,
|
||||
"mean_cadence_s": 5.22,
|
||||
"file": "p1-net-2026-08-16.jsonl.gz",
|
||||
"bytes_gz": 138347,
|
||||
"bytes_raw": 912481,
|
||||
"sha256_raw": "a44e5d961600a539ddf824d5d211ef319833666b7598e5939a6cdf2cb1e3581f",
|
||||
"sha256_gz": "8f6511e52f5be9187f422021abc93a5fa8b698b4c785877d69d15dd6de106fd8"
|
||||
},
|
||||
{
|
||||
"date": "2026-08-17",
|
||||
"window": [
|
||||
"2026-08-17T00:00:00+02:00",
|
||||
"2026-08-18T00:00:00+02:00"
|
||||
],
|
||||
"read": "OK",
|
||||
"http_bytes": 1133721,
|
||||
"attempts": 1,
|
||||
"samples": 16627,
|
||||
"non_numeric_states": [],
|
||||
"first": "2026-08-16T22:00:00+00:00",
|
||||
"last": "2026-08-17T21:59:59.685699+00:00",
|
||||
"gaps": [
|
||||
{
|
||||
"from": "2026-08-17T17:27:00.599126+00:00",
|
||||
"to": "2026-08-17T17:28:20.389628+00:00",
|
||||
"seconds": 79.791
|
||||
}
|
||||
],
|
||||
"covered_span_s": 86399.7,
|
||||
"mean_cadence_s": 5.197,
|
||||
"file": "p1-net-2026-08-17.jsonl.gz",
|
||||
"bytes_gz": 140214,
|
||||
"bytes_raw": 917356,
|
||||
"sha256_raw": "70cce79b3732f292f7f58f0b2655bdb4a00a20a6530f1f50dac62ef5f039788b",
|
||||
"sha256_gz": "e2f9b461c4db7902e1a3d30b439ebc11ebcd9618a72d12f10e5131f38fb437bf"
|
||||
},
|
||||
{
|
||||
"date": "2026-08-18",
|
||||
"window": [
|
||||
"2026-08-18T00:00:00+02:00",
|
||||
"2026-08-19T00:00:00+02:00"
|
||||
],
|
||||
"read": "OK",
|
||||
"http_bytes": 1074019,
|
||||
"attempts": 1,
|
||||
"samples": 15699,
|
||||
"non_numeric_states": [
|
||||
{
|
||||
"t": "2026-08-18T02:03:54.417106+00:00",
|
||||
"state": "unavailable"
|
||||
},
|
||||
{
|
||||
"t": "2026-08-18T04:10:41.786299+00:00",
|
||||
"state": "unavailable"
|
||||
}
|
||||
],
|
||||
"first": "2026-08-17T22:00:00+00:00",
|
||||
"last": "2026-08-18T21:59:54.501766+00:00",
|
||||
"gaps": [
|
||||
{
|
||||
"from": "2026-08-18T02:02:59.633845+00:00",
|
||||
"to": "2026-08-18T02:04:38.694366+00:00",
|
||||
"seconds": 99.061
|
||||
},
|
||||
{
|
||||
"from": "2026-08-18T04:09:54.292049+00:00",
|
||||
"to": "2026-08-18T04:11:38.500238+00:00",
|
||||
"seconds": 104.208
|
||||
}
|
||||
],
|
||||
"covered_span_s": 86394.5,
|
||||
"mean_cadence_s": 5.504,
|
||||
"file": "p1-net-2026-08-18.jsonl.gz",
|
||||
"bytes_gz": 135894,
|
||||
"bytes_raw": 869570,
|
||||
"sha256_raw": "68cd44ac56099ee38f0bba4c32d7d17d33b92d28a99d27419f53c22374491ca6",
|
||||
"sha256_gz": "d6c97508f805aff040d2b4ed4e06c0e7373db2ea6227c7d79ef24c8c79074115"
|
||||
},
|
||||
{
|
||||
"date": "2026-08-19",
|
||||
"window": [
|
||||
"2026-08-19T00:00:00+02:00",
|
||||
"2026-08-20T00:00:00+02:00"
|
||||
],
|
||||
"read": "OK",
|
||||
"http_bytes": 989720,
|
||||
"attempts": 1,
|
||||
"samples": 14549,
|
||||
"non_numeric_states": [],
|
||||
"first": "2026-08-18T22:00:00+00:00",
|
||||
"last": "2026-08-19T21:59:56.556610+00:00",
|
||||
"gaps": [
|
||||
{
|
||||
"from": "2026-08-19T01:33:29.599224+00:00",
|
||||
"to": "2026-08-19T01:34:01.653383+00:00",
|
||||
"seconds": 32.054
|
||||
}
|
||||
],
|
||||
"covered_span_s": 86396.6,
|
||||
"mean_cadence_s": 5.939,
|
||||
"file": "p1-net-2026-08-19.jsonl.gz",
|
||||
"bytes_gz": 126345,
|
||||
"bytes_raw": 800369,
|
||||
"sha256_raw": "0f11ce0cee43cbd7bdb08dc48b202e58c442157ac08b2cda5b64bbab9bd56300",
|
||||
"sha256_gz": "13d61b7da903877c8ae7813b833cb5836ec04a1cf1efd0e1fa87e916bef95fd5"
|
||||
},
|
||||
{
|
||||
"date": "2026-08-20",
|
||||
"window": [
|
||||
"2026-08-20T00:00:00+02:00",
|
||||
"2026-08-21T00:00:00+02:00"
|
||||
],
|
||||
"read": "OK",
|
||||
"http_bytes": 1068038,
|
||||
"attempts": 1,
|
||||
"samples": 15600,
|
||||
"non_numeric_states": [],
|
||||
"first": "2026-08-19T22:00:00+00:00",
|
||||
"last": "2026-08-20T21:59:56.742604+00:00",
|
||||
"gaps": [
|
||||
{
|
||||
"from": "2026-08-20T02:11:56.607373+00:00",
|
||||
"to": "2026-08-20T02:12:38.840458+00:00",
|
||||
"seconds": 42.233
|
||||
},
|
||||
{
|
||||
"from": "2026-08-20T20:42:04.623102+00:00",
|
||||
"to": "2026-08-20T20:43:41.666543+00:00",
|
||||
"seconds": 97.043
|
||||
}
|
||||
],
|
||||
"covered_span_s": 86396.7,
|
||||
"mean_cadence_s": 5.539,
|
||||
"file": "p1-net-2026-08-20.jsonl.gz",
|
||||
"bytes_gz": 139693,
|
||||
"bytes_raw": 865024,
|
||||
"sha256_raw": "2612153963951dd13fe310ad7fbb5bec2e195db56fd99fd963134c8badae25ba",
|
||||
"sha256_gz": "362f2ee3d9d7f23f9051ba78993c5af7443dabb3b5f16339efc673444720c892"
|
||||
},
|
||||
{
|
||||
"date": "2026-08-21",
|
||||
"window": [
|
||||
"2026-08-21T00:00:00+02:00",
|
||||
"2026-08-22T00:00:00+02:00"
|
||||
],
|
||||
"read": "OK",
|
||||
"http_bytes": 1118002,
|
||||
"attempts": 1,
|
||||
"samples": 16383,
|
||||
"non_numeric_states": [],
|
||||
"first": "2026-08-20T22:00:00+00:00",
|
||||
"last": "2026-08-21T21:59:57.771588+00:00",
|
||||
"gaps": [],
|
||||
"covered_span_s": 86397.8,
|
||||
"mean_cadence_s": 5.274,
|
||||
"file": "p1-net-2026-08-21.jsonl.gz",
|
||||
"bytes_gz": 139105,
|
||||
"bytes_raw": 904809,
|
||||
"sha256_raw": "933d9a6899f59c128d0d9b84d6944cea63b1ad58dc57ac52e3e476f9c616f07b",
|
||||
"sha256_gz": "a563581a9a3338af173abb99a200db32881ddaf893d2458f5d8de59b5ec6041f"
|
||||
},
|
||||
{
|
||||
"date": "2026-08-22",
|
||||
"window": [
|
||||
"2026-08-22T00:00:00+02:00",
|
||||
"2026-08-23T00:00:00+02:00"
|
||||
],
|
||||
"read": "OK",
|
||||
"http_bytes": 1129094,
|
||||
"attempts": 1,
|
||||
"samples": 16520,
|
||||
"non_numeric_states": [],
|
||||
"first": "2026-08-21T22:00:00+00:00",
|
||||
"last": "2026-08-22T21:59:56.913786+00:00",
|
||||
"gaps": [
|
||||
{
|
||||
"from": "2026-08-21T23:05:20.035692+00:00",
|
||||
"to": "2026-08-21T23:07:51.147719+00:00",
|
||||
"seconds": 151.112
|
||||
},
|
||||
{
|
||||
"from": "2026-08-21T23:07:56.966604+00:00",
|
||||
"to": "2026-08-21T23:08:27.695101+00:00",
|
||||
"seconds": 30.728
|
||||
}
|
||||
],
|
||||
"covered_span_s": 86396.9,
|
||||
"mean_cadence_s": 5.23,
|
||||
"file": "p1-net-2026-08-22.jsonl.gz",
|
||||
"bytes_gz": 141564,
|
||||
"bytes_raw": 914120,
|
||||
"sha256_raw": "39ccdf67c806344490f791648822cd2cd14d73ea7cc0b6e8572a1e15e8f74641",
|
||||
"sha256_gz": "5c46f1879a723f9986d521124200cab839af2a4722b76bc97c6f6f59d0df65a2"
|
||||
},
|
||||
{
|
||||
"date": "2026-08-23",
|
||||
"window": [
|
||||
"2026-08-23T00:00:00+02:00",
|
||||
"2026-08-24T00:00:00+02:00"
|
||||
],
|
||||
"read": "OK",
|
||||
"http_bytes": 1107164,
|
||||
"attempts": 1,
|
||||
"samples": 16351,
|
||||
"non_numeric_states": [],
|
||||
"first": "2026-08-22T22:00:00+00:00",
|
||||
"last": "2026-08-23T21:59:56.921115+00:00",
|
||||
"gaps": [],
|
||||
"covered_span_s": 86396.9,
|
||||
"mean_cadence_s": 5.284,
|
||||
"file": "p1-net-2026-08-23.jsonl.gz",
|
||||
"bytes_gz": 136277,
|
||||
"bytes_raw": 894387,
|
||||
"sha256_raw": "ffb15367bf3c98eff8a5600e4858ac99778b597c03d0a4f6154e6971b8f98a44",
|
||||
"sha256_gz": "3fa76981758a468ba0aa68b50fe68d5bdb1ef38cd7faec2b6ffdb61c9ddb2db2"
|
||||
},
|
||||
{
|
||||
"date": "2026-08-24",
|
||||
"window": [
|
||||
"2026-08-24T00:00:00+02:00",
|
||||
"2026-08-25T00:00:00+02:00"
|
||||
],
|
||||
"read": "OK",
|
||||
"http_bytes": 1122175,
|
||||
"attempts": 1,
|
||||
"samples": 16584,
|
||||
"non_numeric_states": [],
|
||||
"first": "2026-08-23T22:00:00+00:00",
|
||||
"last": "2026-08-24T21:59:57.940474+00:00",
|
||||
"gaps": [],
|
||||
"covered_span_s": 86397.9,
|
||||
"mean_cadence_s": 5.21,
|
||||
"file": "p1-net-2026-08-24.jsonl.gz",
|
||||
"bytes_gz": 136834,
|
||||
"bytes_raw": 906369,
|
||||
"sha256_raw": "30465d5ff51220201b4a79341e5da7bfc3d88290465b1c9d886ba94eee8dd234",
|
||||
"sha256_gz": "5103088e047bfcbd9b3f55521f431b01cd27de10c2642e00281a13faa762bdd9"
|
||||
},
|
||||
{
|
||||
"date": "2026-08-25",
|
||||
"window": [
|
||||
"2026-08-25T00:00:00+02:00",
|
||||
"2026-08-26T00:00:00+02:00"
|
||||
],
|
||||
"read": "OK",
|
||||
"http_bytes": 1110567,
|
||||
"attempts": 1,
|
||||
"samples": 16451,
|
||||
"non_numeric_states": [
|
||||
{
|
||||
"t": "2026-08-25T01:52:02.104225+00:00",
|
||||
"state": "unavailable"
|
||||
}
|
||||
],
|
||||
"first": "2026-08-24T22:00:00+00:00",
|
||||
"last": "2026-08-25T21:59:56.883744+00:00",
|
||||
"gaps": [
|
||||
{
|
||||
"from": "2026-08-25T01:51:25.942719+00:00",
|
||||
"to": "2026-08-25T01:52:53.203963+00:00",
|
||||
"seconds": 87.261
|
||||
}
|
||||
],
|
||||
"covered_span_s": 86396.9,
|
||||
"mean_cadence_s": 5.252,
|
||||
"file": "p1-net-2026-08-25.jsonl.gz",
|
||||
"bytes_gz": 135890,
|
||||
"bytes_raw": 896416,
|
||||
"sha256_raw": "0e7c86b2b74f2108bc7f5f5d2de2627caaafe473ca4ae18515534dff10526e26",
|
||||
"sha256_gz": "2a5411c10d8d3b271f133c62c04bd722279b48b08d7376084fbad6cc6dd66d76"
|
||||
},
|
||||
{
|
||||
"date": "2026-08-26",
|
||||
"window": [
|
||||
"2026-08-26T00:00:00+02:00",
|
||||
"2026-08-27T00:00:00+02:00"
|
||||
],
|
||||
"read": "OK",
|
||||
"http_bytes": 1123610,
|
||||
"attempts": 1,
|
||||
"samples": 16542,
|
||||
"non_numeric_states": [],
|
||||
"first": "2026-08-25T22:00:00+00:00",
|
||||
"last": "2026-08-26T21:59:58.915457+00:00",
|
||||
"gaps": [],
|
||||
"covered_span_s": 86398.9,
|
||||
"mean_cadence_s": 5.223,
|
||||
"file": "p1-net-2026-08-26.jsonl.gz",
|
||||
"bytes_gz": 139301,
|
||||
"bytes_raw": 908350,
|
||||
"sha256_raw": "88d72c1b9f51707d62e744f40402de4260a04617875b85c65d2df6079c6c84ca",
|
||||
"sha256_gz": "0661588fbc0c6c42825b67d483c8818c070405c1002424b3f1d61d8fdadb6370"
|
||||
},
|
||||
{
|
||||
"date": "2026-08-27",
|
||||
"window": [
|
||||
"2026-08-27T00:00:00+02:00",
|
||||
"2026-08-28T00:00:00+02:00"
|
||||
],
|
||||
"read": "OK",
|
||||
"http_bytes": 1122433,
|
||||
"attempts": 1,
|
||||
"samples": 16573,
|
||||
"non_numeric_states": [],
|
||||
"first": "2026-08-26T22:00:00+00:00",
|
||||
"last": "2026-08-27T21:59:58.538446+00:00",
|
||||
"gaps": [
|
||||
{
|
||||
"from": "2026-08-27T18:50:29.030586+00:00",
|
||||
"to": "2026-08-27T18:52:22.938470+00:00",
|
||||
"seconds": 113.908
|
||||
}
|
||||
],
|
||||
"covered_span_s": 86398.5,
|
||||
"mean_cadence_s": 5.214,
|
||||
"file": "p1-net-2026-08-27.jsonl.gz",
|
||||
"bytes_gz": 138009,
|
||||
"bytes_raw": 906770,
|
||||
"sha256_raw": "528ab8ee10a46275d2e91d56ef2ed847e5932fae76a1752e6f2e9828dbfa9865",
|
||||
"sha256_gz": "5cacc8c5788f43d6e6e2f569445fa82d9edc5a63b1f082f9a1d6a3bb0b404260"
|
||||
},
|
||||
{
|
||||
"date": "2026-08-28",
|
||||
"window": [
|
||||
"2026-08-28T00:00:00+02:00",
|
||||
"2026-08-29T00:00:00+02:00"
|
||||
],
|
||||
"read": "OK",
|
||||
"http_bytes": 1114796,
|
||||
"attempts": 1,
|
||||
"samples": 16456,
|
||||
"non_numeric_states": [],
|
||||
"first": "2026-08-27T22:00:00+00:00",
|
||||
"last": "2026-08-28T21:59:58.515555+00:00",
|
||||
"gaps": [],
|
||||
"covered_span_s": 86398.5,
|
||||
"mean_cadence_s": 5.251,
|
||||
"file": "p1-net-2026-08-28.jsonl.gz",
|
||||
"bytes_gz": 135917,
|
||||
"bytes_raw": 900654,
|
||||
"sha256_raw": "f89838bc9f61af074c17817e4a6eab037318f38fa3c65dad3edfa2106abbc9fb",
|
||||
"sha256_gz": "97090b605f67dcc1f84dea2c51d4832dfe1c2af497a4f4cfe50ecb51024d9b4c"
|
||||
},
|
||||
{
|
||||
"date": "2026-08-29",
|
||||
"window": [
|
||||
"2026-08-29T00:00:00+02:00",
|
||||
"2026-08-30T00:00:00+02:00"
|
||||
],
|
||||
"read": "OK",
|
||||
"http_bytes": 1092983,
|
||||
"attempts": 1,
|
||||
"samples": 16132,
|
||||
"non_numeric_states": [],
|
||||
"first": "2026-08-28T22:00:00+00:00",
|
||||
"last": "2026-08-29T21:59:57.574524+00:00",
|
||||
"gaps": [
|
||||
{
|
||||
"from": "2026-08-29T00:03:20.539844+00:00",
|
||||
"to": "2026-08-29T00:03:50.569581+00:00",
|
||||
"seconds": 30.03
|
||||
}
|
||||
],
|
||||
"covered_span_s": 86397.6,
|
||||
"mean_cadence_s": 5.356,
|
||||
"file": "p1-net-2026-08-29.jsonl.gz",
|
||||
"bytes_gz": 134210,
|
||||
"bytes_raw": 883053,
|
||||
"sha256_raw": "896d4c9d660be4faabc5a088323e246e257877d5ff6bd0ec084b785480d76e12",
|
||||
"sha256_gz": "b6f264cd3afba63209123a27490e7e1c3ae70a86731d7ea05ae67f88917f136f"
|
||||
},
|
||||
{
|
||||
"date": "2026-08-30",
|
||||
"window": [
|
||||
"2026-08-30T00:00:00+02:00",
|
||||
"2026-08-31T00:00:00+02:00"
|
||||
],
|
||||
"read": "OK",
|
||||
"http_bytes": 1118895,
|
||||
"attempts": 1,
|
||||
"samples": 16490,
|
||||
"non_numeric_states": [],
|
||||
"first": "2026-08-29T22:00:00+00:00",
|
||||
"last": "2026-08-30T21:59:58.533323+00:00",
|
||||
"gaps": [],
|
||||
"covered_span_s": 86398.5,
|
||||
"mean_cadence_s": 5.24,
|
||||
"file": "p1-net-2026-08-30.jsonl.gz",
|
||||
"bytes_gz": 138429,
|
||||
"bytes_raw": 904311,
|
||||
"sha256_raw": "e704818efb58bb6c505791bc9eab2e9476bf48ff8911d0e79b401fd35b529fa0",
|
||||
"sha256_gz": "9052fead2418bff3083bec3ae8ce64d6b9f6224b668f4bb510c79775f66c5b79"
|
||||
}
|
||||
],
|
||||
"summary": {
|
||||
"days_requested": 30,
|
||||
"days_read": 30,
|
||||
"days_failed": 0,
|
||||
"samples": 485841,
|
||||
"bytes_gz": 4126003,
|
||||
"empty_days": []
|
||||
}
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -3,6 +3,13 @@
|
||||
Each assertion is a precedence question someone will eventually ask in the
|
||||
field: "why did it charge during a peak?", "why did it discharge while the
|
||||
maintenance cycle was charging?", "what happens if two things disagree?".
|
||||
|
||||
⚠️ MUTATING THE MODULE THIS FILE GRADES? PURGE `__pycache__` FIRST - or run
|
||||
`tools/mutation_run.sh`, which does. `python3 -B` alone does NOT save you: it
|
||||
stops bytecode being WRITTEN, not a stale one being READ, and a size-preserving
|
||||
edit reverted inside one second is invisible to CPython's staleness test. That
|
||||
is TEST-15, and it has already turned one live mutation into a false survivor.
|
||||
Read MUTATION.md before you report a survivor.
|
||||
"""
|
||||
|
||||
import sys
|
||||
|
||||
@@ -20,12 +20,15 @@ WHAT THIS FILE IS DEFENDING, in the order the card's acceptance criteria name it
|
||||
exist - static_tariff's required `peak_guard_active` interlock and
|
||||
arbiter.py's clause 2 - both driven end to end, plus the third state
|
||||
(the guard never ran) that neither of them can express on its own.
|
||||
AC4 NET-POSITIVE ACROSS 12 MONTHS OF REPLAYED PRICES. ⚠️ SEE SECTION 7. THIS
|
||||
REPOSITORY HOLDS NO PRICE HISTORY AT ALL - `scenarios/` carries two days
|
||||
of real METER data and nothing else - so the criterion as written cannot
|
||||
be met, and it is NOT redefined here into something that can be. What
|
||||
section 7 does instead is stated there in full, and what it cannot say is
|
||||
stated with it.
|
||||
AC4 NET-POSITIVE ACROSS 12 MONTHS OF REPLAYED PRICES. ⚠️ MET AS OF DATA-02,
|
||||
AND SECTIONS 7 AND 7B DO DIFFERENT HALVES OF IT. 7B replays twelve months
|
||||
of REAL EPEX BE day-ahead prices - `scenarios/epex-be-dayahead-*.json`,
|
||||
8760 hours, public data under CC BY 4.0 - through the shipped `decide()`,
|
||||
and reports the euro figure at the shipped threshold. Section 7 keeps the
|
||||
SYNTHETIC year, because the real one turns out to be unable to grade §17
|
||||
at all: not one of its 365 days has a negative DEAREST hour, so a count
|
||||
of zero negative-price discharges over it grades nothing. 7B asserts that
|
||||
degeneracy rather than quietly reporting the zero.
|
||||
|
||||
THREE RULES THIS FILE HOLDS ITSELF TO, because the reviewer will:
|
||||
|
||||
@@ -59,6 +62,13 @@ THREE RULES THIS FILE HOLDS ITSELF TO, because the reviewer will:
|
||||
aged out, an hour the series does not cover, an unread state of charge and a
|
||||
peak guard that never ran are five DIFFERENT reasons - and none of them is
|
||||
an answer. Section 5 drives all five and asserts they are distinguishable.
|
||||
|
||||
⚠️ MUTATING THE MODULE THIS FILE GRADES? PURGE `__pycache__` FIRST - or run
|
||||
`tools/mutation_run.sh`, which does. `python3 -B` alone does NOT save you: it
|
||||
stops bytecode being WRITTEN, not a stale one being READ, and a size-preserving
|
||||
edit reverted inside one second is invisible to CPython's staleness test. That
|
||||
is TEST-15, and it has already turned one live mutation into a false survivor.
|
||||
Read MUTATION.md before you report a survivor.
|
||||
"""
|
||||
|
||||
import ast
|
||||
@@ -378,7 +388,11 @@ check("BUYING in a negative-price hour is still permitted - §17 forbids "
|
||||
"refusing to be paid to charge",
|
||||
act(NEG_PLAN, NEG.index(min(NEG)), thresh=_shipped,
|
||||
unc=NO_WEATHER).action == CHARGE)
|
||||
# A zero price is the boundary and it is NOT negative.
|
||||
# A zero price is the boundary and it is NOT negative. ⚠️ KEEP THIS PROBE. It
|
||||
# pins the boundary from ABOVE - it is what catches a guard written `<= 0` - and
|
||||
# the SAFETY-26 block below pins it from BELOW. Neither replaces the other, and
|
||||
# the whole defect that card exists to close is that only one of the two sides
|
||||
# was ever stated.
|
||||
ZERO = list(POS)
|
||||
ZERO[DEAR_H] = 0.0
|
||||
check("a sell hour priced at exactly ZERO is not a negative one, so the guard "
|
||||
@@ -387,6 +401,129 @@ check("a sell hour priced at exactly ZERO is not a negative one, so the guard "
|
||||
act(plan_of(ZERO), DEAR_H, thresh=_shipped, unc=NO_WEATHER).action
|
||||
== DISCHARGE)
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# SAFETY-26. THE OTHER SIDE OF THE SAME BOUNDARY, AND WHY IT HAD TO BE ADDED.
|
||||
#
|
||||
# OPT-04's reviewer mutated `if price < 0` to `if price < -0.001` and EVERY
|
||||
# SUITE STAYED GREEN, with a -0.0005 EUR/kWh sell hour discharging. The shipped
|
||||
# code was right the whole time; the CHECKS could not tell correct from
|
||||
# nearly-correct, because the only probe near the boundary sat at 0.0000. A
|
||||
# probe above the line catches `<=`. It says nothing at all about a tolerance
|
||||
# invented below the line, and a tolerance below the line IS §17's regression
|
||||
# case walking through with the suite passing.
|
||||
#
|
||||
# ⚠️ AND -0.0005 IS NOT AN EXOTIC INPUT. Belgian day-ahead prints small negative
|
||||
# hours regularly; an all-in price a twentieth of a cent below zero is an
|
||||
# ordinary day, not a fuzz value. That is what makes this a live regression
|
||||
# rather than a theoretical one.
|
||||
#
|
||||
# ⚠️ SO THE PROBE IS A SWEEP, NOT A POINT, and the sweep is the discriminating
|
||||
# part. One probe at -0.0005 closes `-0.001` and nothing else; a mutation
|
||||
# reaching for `-0.01` would survive it, which is the identical defect one
|
||||
# decimal place further out. The sweep spans four orders of magnitude down to
|
||||
# the last place the canonical six-decimal format can even express, so there is
|
||||
# no tolerance a guard can invent that some member of it does not straddle.
|
||||
# `_ROUNDING` asserts the smallest member SURVIVES the format rather than being
|
||||
# rounded to zero on the way in - a probe that silently became 0.0 would be the
|
||||
# `0.0000` check again, wearing a different name.
|
||||
TINY_NEG = (-0.05, -0.005, -0.0005, -0.00005, -0.000001)
|
||||
_ROUNDING = [round(p, 6) for p in TINY_NEG]
|
||||
check(f"every probe price survives the canonical 6-decimal rounding as a "
|
||||
f"STRICTLY negative number {_ROUNDING} - one that rounded to 0.0 would "
|
||||
f"be the check above again under another name",
|
||||
all(r < 0 for r in _ROUNDING) and len(set(_ROUNDING)) == len(TINY_NEG))
|
||||
check("...and they span four orders of magnitude, so no single invented "
|
||||
"tolerance can sit below all of them and above none",
|
||||
abs(min(TINY_NEG)) / abs(max(TINY_NEG)) > 10000)
|
||||
|
||||
|
||||
def tiny_neg_plan(price):
|
||||
"""The POS day with its DEAREST hour set to a small negative print."""
|
||||
day = list(POS)
|
||||
day[DEAR_H] = price
|
||||
return plan_of(day), day
|
||||
|
||||
|
||||
# The stimulus has to survive the rungs ABOVE §17 or it grades nothing: the
|
||||
# hour must still be the dearest, and the spread must still clear the widened
|
||||
# threshold, at every probe. Asserted first, for all of them, as its own check.
|
||||
_wellformed = [
|
||||
(p, day.index(max(day)) == DEAR_H,
|
||||
round(max(day) - min(day), 6) > required_spread(_shipped, NO_WEATHER))
|
||||
for p, (_pl, day) in ((p, tiny_neg_plan(p)) for p in TINY_NEG)]
|
||||
check(f"at every probe the negative hour is still the DEAREST one and the "
|
||||
f"spread still clears the threshold, so §17 is the only rung that can "
|
||||
f"refuse {_wellformed}",
|
||||
all(dearest and clears for _p, dearest, clears in _wellformed))
|
||||
_swept = [(p, act(tiny_neg_plan(p)[0], DEAR_H, thresh=_shipped,
|
||||
unc=NO_WEATHER).action) for p in TINY_NEG]
|
||||
check(f"SAFETY-26: a sell hour that is negative BY ANY MARGIN AT ALL refuses - "
|
||||
f"down to -0.000001 EUR/kWh, so the guard is `< 0` and not `< -epsilon` "
|
||||
f"for any epsilon {_swept}",
|
||||
all(a is None for _p, a in _swept))
|
||||
check("...and each refusal is §17's, not some other rung that happens to fire "
|
||||
"at small numbers",
|
||||
all("§17" in act(tiny_neg_plan(p)[0], DEAR_H, thresh=_shipped,
|
||||
unc=NO_WEATHER).reason for p in TINY_NEG))
|
||||
# The mirror image, one place above zero. Without this the sweep above would
|
||||
# pass for a guard that refused EVERYTHING, which grades §17 by nothing.
|
||||
_tiny_pos = [(-p, act(tiny_neg_plan(-p)[0], DEAR_H, thresh=_shipped,
|
||||
unc=NO_WEATHER).action) for p in TINY_NEG]
|
||||
check(f"...while THE SAME MAGNITUDES with the sign flipped all DISCHARGE, so "
|
||||
f"the sweep is a boundary at exactly zero rather than a refusal of small "
|
||||
f"numbers - which a guard that refused everything would also have passed "
|
||||
f"{_tiny_pos}",
|
||||
all(a == DISCHARGE for _p, a in _tiny_pos))
|
||||
|
||||
# SAFETY-26 AC4 - THE LOOK AT THE OTHER BOUNDARIES, NAMED RATHER THAN FIXED.
|
||||
#
|
||||
# The card asks whether the same one-sided pinning exists elsewhere. Every
|
||||
# price/quantity boundary in arbitrage.py and static_tariff.py was given the
|
||||
# tolerance mutation that survived on `price < 0`, in both directions where
|
||||
# both exist, under `-B` with a recursive purge. Two survived, BOTH in
|
||||
# static_tariff.py - TARIFF-03's file, and deliberately NOT touched here:
|
||||
#
|
||||
# D `spread == 0.0` (the flat-tariff rung) -> `spread <= 0.001` SURVIVES.
|
||||
# Measured, not reasoned: with it loosened, a series priced 0.20000 /
|
||||
# 0.20050 - a REAL 0.0005 spread - flips from ALLOWED to REFUSED at
|
||||
# min_spread_eur_kwh=0.0, which `arbitrage()`'s own docstring documents as
|
||||
# a supported value ("pass 0.0 to mean any positive spread, explicitly").
|
||||
# At a shipped threshold the OUTCOME is unchanged, but the operator's
|
||||
# reason becomes the false sentence "the tariff is flat - every one of the
|
||||
# 2 firm hours costs 0.2000 EUR/kWh" about a tariff that is not flat.
|
||||
# Same shape as §17's: the rung is only ever probed with an EXACTLY flat
|
||||
# series, so nothing pins the tiny-but-real side.
|
||||
#
|
||||
# F `len(firm) < 2` (§8.3's firm-pair rung) -> `< 1` SURVIVES, at +0 BYTES,
|
||||
# which is the delta TEST-15 names as the risky one. It is not live on its
|
||||
# own: a single firm hour has a spread of 0.0, so the flat rung refuses it
|
||||
# anyway - but the reason degrades from §8.3's honest "only 1 of 3 hours
|
||||
# carry a published price" to "the tariff is flat". THE FINDING THAT
|
||||
# MATTERS IS THE INTERACTION: D and F MASK EACH OTHER. Neither is
|
||||
# individually live because the other catches it, which is exactly the
|
||||
# arrangement in which a later edit to either one opens a hole nothing
|
||||
# reports.
|
||||
#
|
||||
# Everything else in arbitrage.py is pinned on BOTH sides and was verified so:
|
||||
# `price < 0` (this card), `soc <= floor_pct` and `soc >= ceiling_pct` are each
|
||||
# red under a +5 and a -5 tolerance; static_tariff's `spread < need` is red
|
||||
# under +/-0.001 and additionally bisected to 1e-6 in section 1; `cheap_now`'s
|
||||
# `price < mean` is red under a +0.001 tolerance in test_static_tariff.py.
|
||||
#
|
||||
# Not fixed here on purpose. D and F are TARIFF-03's rungs, they need probes in
|
||||
# test_static_tariff.py rather than in this file, and the card is explicit that
|
||||
# its fourth criterion is a look and not a refactor.
|
||||
#
|
||||
# ✅ CLOSED BY TEST-16, in test_static_tariff.py SECTION 9, and the two rows
|
||||
# above are kept as the diagnosis rather than as an open finding. D is pinned by
|
||||
# a sweep of small-but-real spreads down to 0.000001 EUR/kWh at
|
||||
# min_spread_eur_kwh=0.0; F is pinned by a ONE-FIRM-HOUR series graded on WHICH
|
||||
# RUNG'S SENTENCE came back, which is the only way it goes red without borrowing
|
||||
# the flat rung; and the masking is denied by a table that grades every stimulus
|
||||
# on its rung's attribution rather than on `kind`. Both are red on their own and
|
||||
# five checks are red with BOTH weakened at once. Ledger in that section's
|
||||
# header. Nothing in app/ changed - these rungs were correct all along.
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
print()
|
||||
@@ -669,34 +806,39 @@ check("...and it is still ARMED when arbitrage is idle and the loop wins, so "
|
||||
print()
|
||||
print("7. AC4 - 12 months of replayed prices, and what could NOT be measured")
|
||||
|
||||
# ⚠️ READ THIS BEFORE READING THE NUMBERS BELOW.
|
||||
# ⚠️ READ THIS BEFORE READING THE NUMBERS BELOW. THIS SECTION IS THE SYNTHETIC
|
||||
# YEAR, AND IT IS NOT AC4's EVIDENCE ANY MORE - SECTION 7B IS.
|
||||
#
|
||||
# The acceptance criterion is "net-positive across 12 months of replayed prices
|
||||
# in simulation". THIS REPOSITORY CONTAINS NO PRICE HISTORY. `scenarios/` holds
|
||||
# three gzipped captures and all three are P1 METER data - two days of net power
|
||||
# from the reference house plus one age capture. There is no EPEX archive, no
|
||||
# supplier export, and no CSV of a past year anywhere in the tree.
|
||||
# When OPT-04 shipped, this repository held no price history: `scenarios/`
|
||||
# carried three gzipped P1 METER captures and nothing else. AC4 was therefore
|
||||
# reported NOT MET rather than redefined into something passable, which is what
|
||||
# TARIFF-01 and SAFETY-07 had both been upheld for doing.
|
||||
#
|
||||
# TARIFF-01 and SAFETY-07 both hit an unmeetable criterion and both DECLINED to
|
||||
# redefine it into one they could pass, and both were upheld for it. So:
|
||||
# DATA-02 pointed out that the missing ingredient was never a capture. EPEX BE
|
||||
# day-ahead is PUBLIC DATA; the 30-day meter criterion it was being carried
|
||||
# beside genuinely needs waiting, and this one only ever needed a fetch. Section
|
||||
# 7B replays the real year and AC4 is met there.
|
||||
#
|
||||
# AC4 IS NOT MET, AND IT IS NOT RESTATED. What follows is not a replay of the
|
||||
# Belgian market; it is a replay of a SYNTHETIC year, and a euro figure from a
|
||||
# synthetic year grades the generator that produced it, not the strategy.
|
||||
# ⚠️ SO WHY IS THE SYNTHETIC YEAR STILL HERE? Because the real one cannot grade
|
||||
# §17, and 7B proves that rather than assuming it. Across all 365 real days, the
|
||||
# number whose DEAREST hour is priced below zero is ZERO - raw wholesale and
|
||||
# all-in alike - so "no discharges into a negative hour" over the real year is a
|
||||
# count of something that never had the chance to happen. Deleting the guard
|
||||
# would not change it. This section's generator drives a summer midday block
|
||||
# negative ON PURPOSE, and it is the only thing in this file that puts a
|
||||
# negative price where the strategy would otherwise sell.
|
||||
#
|
||||
# What the replay is FOR is the half of AC4 that does not need real prices. Net
|
||||
# positivity here is not an empirical outcome to be hoped for - it is a property
|
||||
# of the decision rule, and the replay's job is to demonstrate that the property
|
||||
# holds on every trade the strategy actually chose, over a year of varied days
|
||||
# including negative-price ones. Stated as an invariant:
|
||||
# What this section establishes is the half of AC4 that does not need real
|
||||
# prices, and it is a property of the decision rule rather than an outcome to be
|
||||
# hoped for:
|
||||
#
|
||||
# every executed round trip has (sell - buy) >= required >= threshold,
|
||||
# so its benefit net of the threshold is >= 0, on every day, always.
|
||||
#
|
||||
# That is asserted per trade below, over 365 days. What it does NOT establish -
|
||||
# and no synthetic series could - is how OFTEN a real Belgian year clears the
|
||||
# threshold, which is the actual open question and the reason the shipped
|
||||
# default is a product decision rather than a number this card picked.
|
||||
# That is asserted per trade below, over 365 varied days including negative ones.
|
||||
# HOW OFTEN a real Belgian year clears the threshold is the other question, it
|
||||
# is the one the product owner's open decision turns on, and section 7B is the
|
||||
# only place in this file that answers it.
|
||||
|
||||
def synth_day(n):
|
||||
"""A synthetic all-in day-ahead day. Deterministic, seeded by day number.
|
||||
@@ -803,12 +945,256 @@ check("the shipped threshold is strictly more selective than the loose one on "
|
||||
"the same year - the parameter does what it says, at whatever value the "
|
||||
"owner sets it to",
|
||||
len(_sh_trades) < len(_trades))
|
||||
check("AC4 IS REPORTED AS NOT MET rather than redefined: this file says so in "
|
||||
"section 7's preamble, and there is no price history in the repository "
|
||||
"to meet it with",
|
||||
not any(f.endswith((".csv", ".json.gz"))
|
||||
and "price" in f.lower()
|
||||
for f in os.listdir(os.path.join(HERE, "scenarios"))))
|
||||
check("...and the shipped default was NOT moved to make any of this look "
|
||||
"better: app/arbitrage.py reads the threshold through price_option() and "
|
||||
"names no number of its own",
|
||||
"0.10" not in open(os.path.join(HERE, "app", "arbitrage.py"),
|
||||
encoding="utf-8").read().split('"""', 2)[2])
|
||||
|
||||
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
print()
|
||||
print("7B. AC4 - twelve months of REAL EPEX BE prices, replayed")
|
||||
|
||||
# THE DATASET, AND WHAT IT IS NOT.
|
||||
#
|
||||
# `scenarios/epex-be-dayahead-2025-09-01_2026-09-01.json` - 8760 hourly Belgian
|
||||
# day-ahead auction prices, 2025-09-01 to 2026-09-01 Brussels-local, fetched by
|
||||
# `scenarios/fetch_epex_be.py` from Fraunhofer ISE's Energy-Charts API, which
|
||||
# publishes the BE zone under CC BY 4.0 from Bundesnetzagentur | SMARD.de. The
|
||||
# licence was checked BEFORE the data was committed, because the same API serves
|
||||
# other zones under private-use-only terms; the script refuses to write a file
|
||||
# whose per-response `license_info` stops saying CC BY 4.0. Provenance,
|
||||
# attribution and the DST accounting live in the file's own `provenance` block
|
||||
# and `fetch_epex_be.py --verify` re-derives every claim in it.
|
||||
#
|
||||
# ⚠️ THE FIGURES IN THAT FILE ARE RAW WHOLESALE, NOT ALL-IN, AND THIS SECTION IS
|
||||
# WHERE THE DIFFERENCE IS MADE VISIBLE. §9.3's canonical point is all-in; the
|
||||
# committed file says `"all_in": false` and carries the markup/tax assumption as
|
||||
# NUMBERS TO APPLY rather than numbers already applied - TARIFF-02's
|
||||
# double-counting trap, avoided by never baking the guess in. `_all_in()` below
|
||||
# applies it in one place where a reader can watch it happen, and both replays
|
||||
# are run, so exactly how much of the answer rests on the guess is reported
|
||||
# rather than hidden.
|
||||
|
||||
import json # noqa: E402
|
||||
from collections import defaultdict # noqa: E402
|
||||
|
||||
_DS_PATH = os.path.join(HERE, "scenarios",
|
||||
"epex-be-dayahead-2025-09-01_2026-09-01.json")
|
||||
_DS = derived(lambda: json.load(open(_DS_PATH, encoding="utf-8")))
|
||||
_ASSUME = _DS["provenance"]["all_in_assumption"]
|
||||
|
||||
|
||||
def _all_in(wholesale):
|
||||
"""The stated assumption, applied HERE and nowhere in the committed data.
|
||||
|
||||
all_in = (wholesale + markup + network_and_levies) * (1 + vat), with the
|
||||
coefficients read from the dataset's own provenance block rather than
|
||||
retyped - a second copy is a second thing to disagree with the file.
|
||||
"""
|
||||
return round((wholesale + _ASSUME["markup_eur_per_kwh"]
|
||||
+ _ASSUME["network_and_levies_eur_per_kwh"])
|
||||
* (1.0 + _ASSUME["vat_fraction"]), 6)
|
||||
|
||||
|
||||
def _days(price_of):
|
||||
"""The dataset as Brussels calendar days of `PricePoint`s, in order.
|
||||
|
||||
⚠️ GROUPED BY THE LOCAL DATE IN THE `start` STRING, NOT BY SLICING 24 AT A
|
||||
TIME. Two of these days are not 24 hours long, which is the whole DST check,
|
||||
and a fixed stride would put October's 25th hour into the next day and
|
||||
misalign every day after it.
|
||||
"""
|
||||
out = defaultdict(list)
|
||||
for p in _DS["prices"]:
|
||||
out[p["start"][:10]].append(
|
||||
PricePoint(start=datetime.fromisoformat(p["start"]),
|
||||
eur_per_kwh=price_of(p["eur_per_kwh"]),
|
||||
provisional=bool(p["provisional"])))
|
||||
return [out[k] for k in sorted(out)]
|
||||
|
||||
|
||||
_AI_DAYS = derived(lambda: _days(_all_in))
|
||||
_RAW_DAYS = derived(lambda: _days(lambda w: w))
|
||||
|
||||
# ---- the dataset is not degenerate, asserted BEFORE anything is graded ------
|
||||
_lens = [len(d) for d in _AI_DAYS]
|
||||
check(f"the replay has {len(_AI_DAYS)} Brussels days and {sum(_lens)} hourly "
|
||||
f"points, which is a full year rather than a fortnight repeated",
|
||||
len(_AI_DAYS) == 365 and sum(_lens) == 8760)
|
||||
check(f"...and the day lengths are {sorted(set(_lens))}, so BOTH DST days are "
|
||||
f"in it: an importer that produced 24 everywhere would have lost an hour "
|
||||
f"in October and invented one in March",
|
||||
sorted(set(_lens)) == [23, 24, 25]
|
||||
and _lens.count(23) == 1 and _lens.count(25) == 1)
|
||||
_dst_day = [d for d in _AI_DAYS if len(d) == 25][0]
|
||||
check("...and the 25-hour day's two 02:00 points are two different INSTANTS at "
|
||||
"two different offsets, which is what `at()` has to tell apart",
|
||||
len({p.start for p in _dst_day}) == 25
|
||||
and {p.start.utcoffset() for p in _dst_day}
|
||||
== {timedelta(hours=1), timedelta(hours=2)})
|
||||
|
||||
_ai_spreads = sorted(round(max(p.eur_per_kwh for p in d)
|
||||
- min(p.eur_per_kwh for p in d), 6)
|
||||
for d in _AI_DAYS)
|
||||
_raw_spreads = sorted(round(max(p.eur_per_kwh for p in d)
|
||||
- min(p.eur_per_kwh for p in d), 6)
|
||||
for d in _RAW_DAYS)
|
||||
_req_shipped = required_spread(_shipped, NO_WEATHER)
|
||||
_clears = [s for s in _ai_spreads if s > _req_shipped]
|
||||
check(f"...and the year's daily spreads STRADDLE the shipped requirement of "
|
||||
f"{_req_shipped:.4f} EUR/kWh - {len(_clears)} of {len(_ai_spreads)} days "
|
||||
f"clear it - so the threshold is grading something. A year in which every "
|
||||
f"day cleared, or none did, would grade nothing at any value",
|
||||
0 < len(_clears) < len(_ai_spreads))
|
||||
check(f"...and the spreads are not one repeated number: median "
|
||||
f"{_ai_spreads[len(_ai_spreads) // 2]:.4f}, min {_ai_spreads[0]:.4f}, "
|
||||
f"max {_ai_spreads[-1]:.4f}",
|
||||
len(set(_ai_spreads)) > 300 and _ai_spreads[-1] > 4 * _ai_spreads[0])
|
||||
|
||||
# ---- the assumption's arithmetic, asserted rather than asserted-about -------
|
||||
check("the ADDITIVE half of the all-in assumption cancels out of every daily "
|
||||
"spread, so the trade counts below do not depend on the markup guess at "
|
||||
"all - only on the VAT multiplier",
|
||||
all(near(a, r * (1.0 + _ASSUME["vat_fraction"]), 1e-6)
|
||||
for a, r in zip(_ai_spreads, _raw_spreads)))
|
||||
|
||||
# ---- ⚠️ THE DEGENERACY THAT KEEPS SECTION 7 ALIVE --------------------------
|
||||
_raw_neg_h = sum(1 for d in _RAW_DAYS for p in d if p.eur_per_kwh < 0)
|
||||
_ai_neg_h = sum(1 for d in _AI_DAYS for p in d if p.eur_per_kwh < 0)
|
||||
_raw_neg_dear = sum(1 for d in _RAW_DAYS if max(p.eur_per_kwh for p in d) < 0)
|
||||
_ai_neg_dear = sum(1 for d in _AI_DAYS if max(p.eur_per_kwh for p in d) < 0)
|
||||
check(f"the real year DOES contain negative hours - {_raw_neg_h} of them at "
|
||||
f"wholesale, {_ai_neg_h} still negative once the assumed markup and "
|
||||
f"charges are added - so §17 is a live case on this market and not a "
|
||||
f"hypothetical", _raw_neg_h > 100 and _ai_neg_h > 0)
|
||||
check(f"BUT NOT ONE OF THE 365 DAYS HAS A NEGATIVE DEAREST HOUR "
|
||||
f"({_raw_neg_dear} raw, {_ai_neg_dear} all-in), and the guard is on the "
|
||||
f"hour being SOLD INTO. So a count of zero negative-price discharges over "
|
||||
f"this year would be a count of something that could not happen, and "
|
||||
f"section 7's synthetic year stays because it is the only thing here that "
|
||||
f"puts a negative price where the strategy would sell",
|
||||
_raw_neg_dear == 0 and _ai_neg_dear == 0)
|
||||
|
||||
|
||||
def replay_real(days, threshold, unc, *, soc0=50.0, floor=20.0, ceiling=95.0):
|
||||
"""The shipped `decide()` over the real year. Returns the ledger, nothing else.
|
||||
|
||||
One `TariffPlan` per Brussels day, so "the cheapest hour" means the cheapest
|
||||
hour of that day - the same shape as section 7's replay, and the same shape
|
||||
a site with a day-ahead feed actually sees.
|
||||
"""
|
||||
soc = soc0
|
||||
trades, holdings, bad, neg_sells = [], [], [], 0
|
||||
for day in days:
|
||||
plan = TariffPlan(
|
||||
PriceRead.series(day, PriceProduct.DAY_AHEAD, "generic_dayahead",
|
||||
day[0].start), None, "provider")
|
||||
open_buy = None
|
||||
for p in day:
|
||||
d = decide(plan, p.start + timedelta(minutes=30),
|
||||
peak_guard_active=False, soc=soc,
|
||||
min_spread_eur_kwh=threshold, uncertainty=unc,
|
||||
charge_w=MAX_W, discharge_w=MAX_W,
|
||||
soc_floor_pct=floor, soc_ceiling_pct=ceiling)
|
||||
if d.action is None:
|
||||
continue
|
||||
if d.spread_eur_kwh is None or d.required_eur_kwh is None:
|
||||
bad.append(p.start)
|
||||
if d.action == CHARGE:
|
||||
soc = min(ceiling, soc + STEP_PCT)
|
||||
open_buy = (p.eur_per_kwh, d)
|
||||
else:
|
||||
if p.eur_per_kwh < 0:
|
||||
neg_sells += 1
|
||||
soc = max(floor, soc - STEP_PCT)
|
||||
if open_buy is not None:
|
||||
trades.append((open_buy[0], p.eur_per_kwh, d))
|
||||
open_buy = None
|
||||
else:
|
||||
holdings.append(p.start)
|
||||
return trades, holdings, bad, neg_sells
|
||||
|
||||
|
||||
# ⚠️ AT THE SHIPPED THRESHOLD, UNTOUCHED, AND WIDENED BY FCST-03's NO-WEATHER
|
||||
# FACTOR - the harsher of the two operating states, so the figure reported is
|
||||
# the conservative one.
|
||||
_r_trades, _r_held, _r_bad, _r_neg = derived(
|
||||
lambda: replay_real(_AI_DAYS, _shipped, NO_WEATHER)) or (None,) * 4
|
||||
_r_kwh = MAX_W / 1000.0
|
||||
_r_net = round(sum((s - b - _shipped) * _r_kwh for b, s, _ in _r_trades), 2)
|
||||
|
||||
check(f"the real year traded at the SHIPPED threshold: {len(_r_trades)} "
|
||||
f"completed round trips over 365 days of Belgian day-ahead prices - so "
|
||||
f"the criterion is being graded on trades that happened, not on an empty "
|
||||
f"ledger that is net-positive by vacuity", len(_r_trades) > 0)
|
||||
check("...and every one of them carries the spread and the widened requirement "
|
||||
"it cleared, so the ledger is auditable rather than a count", _r_bad == [])
|
||||
check(f"...and it did NOT trade every day ({len(_r_trades)} round trips over "
|
||||
f"365 days), so the threshold selected rather than waved everything "
|
||||
f"through", len(_r_trades) < 365)
|
||||
_r_losses = [(b, s) for b, s, _ in _r_trades if s - b < _shipped]
|
||||
check(f"AC4: every completed round trip on the REAL year cleared the shipped "
|
||||
f"{_shipped} EUR/kWh - {len(_r_losses)} exceptions of {len(_r_trades)}",
|
||||
_r_losses == [])
|
||||
_r_under = [d.spread_eur_kwh for _b, _s, d in _r_trades
|
||||
if d.spread_eur_kwh < d.required_eur_kwh]
|
||||
check(f"...and each cleared its own WIDENED requirement of "
|
||||
f"{_req_shipped:.4f} EUR/kWh, which is the stricter statement §8.3 asks "
|
||||
f"for", _r_under == [])
|
||||
check(f"AC4 IS MET: twelve months of REAL replayed EPEX BE prices are "
|
||||
f"NET-POSITIVE at the shipped default - {_r_net:+.2f} EUR of benefit net "
|
||||
f"of the cycle cost over {len(_r_trades)} round trips of {_r_kwh:.1f} kWh "
|
||||
f"each, accumulated from the trades the strategy actually chose",
|
||||
_r_net > 0)
|
||||
|
||||
# ---- what the owner's open decision actually turns on -----------------------
|
||||
# ⚠️ REPORTED, NOT SETTLED. `cycle_cost_threshold_eur` and FCST-03's 2.5/1.5 are
|
||||
# the product owner's decision. DATA-02 supplies the input and changes nothing:
|
||||
# every number below comes out of the same untouched `decide()`.
|
||||
_r_calm = derived(lambda: replay_real(_AI_DAYS, _shipped, frozenset())[0])
|
||||
_r_raw = derived(lambda: replay_real(_RAW_DAYS, _shipped, NO_WEATHER)[0])
|
||||
# The threshold at which the MEDIAN day of this year clears its widened
|
||||
# requirement. Derived from the observed spreads, not chosen.
|
||||
_median_spread = _ai_spreads[len(_ai_spreads) // 2]
|
||||
_suggested = round(_median_spread / widen_factor(NO_WEATHER), 4)
|
||||
_r_sugg, _, _, _ = derived(
|
||||
lambda: replay_real(_AI_DAYS, _suggested, NO_WEATHER)) or (None,) * 4
|
||||
_sugg_net = round(sum((s - b - _suggested) * _r_kwh for b, s, _ in _r_sugg), 2)
|
||||
print(f" [report] SHIPPED {_shipped} EUR/kWh, widened {widen_factor(NO_WEATHER)}x "
|
||||
f"to {_req_shipped:.4f}: {len(_r_trades)} round trips, {_r_net:+.2f} EUR "
|
||||
f"over the year. Unwidened (weather present): {len(_r_calm)} trips. On "
|
||||
f"RAW wholesale instead of the assumed all-in: {len(_r_raw)} trips, so "
|
||||
f"the markup/VAT guess moves the count by "
|
||||
f"{len(_r_trades) - len(_r_raw):+d}.")
|
||||
print(f" [report] the year's MEDIAN daily all-in spread is "
|
||||
f"{_median_spread:.4f} EUR/kWh, so the threshold at which a median day "
|
||||
f"clears its widened requirement is {_suggested} - and at that value the "
|
||||
f"same year completes {len(_r_sugg)} round trips for {_sugg_net:+.2f} "
|
||||
f"EUR. THE SHIPPED DEFAULT IS NOT CHANGED BY THIS CARD; both numbers are "
|
||||
f"reported so the owner can decide between them.")
|
||||
print(f" [report] and the four-developer finding stands unchanged: a STATIC "
|
||||
f"day/night spread of ~0.0840 EUR/kWh still does not clear "
|
||||
f"{_req_shipped:.4f}, so a static-tariff site never trades at the shipped "
|
||||
f"default. What this year adds is that a DYNAMIC site does - on "
|
||||
f"{len(_clears)} of its 365 days the spread was there to be taken.")
|
||||
check("the loose threshold is strictly less selective than the shipped one on "
|
||||
"the SAME real year - the parameter does what it says at whatever value "
|
||||
"the owner sets, and neither run tuned anything",
|
||||
len(_r_sugg) > len(_r_trades) > 0)
|
||||
check(f"§17 held over the real year too ({_r_neg} discharges into a negative "
|
||||
f"hour) - but see the degeneracy check above: on this data that zero is "
|
||||
f"structural, and section 7's synthetic year is what actually grades the "
|
||||
f"guard", _r_neg == 0)
|
||||
check("the dataset carries its own provenance, states it is NOT all-in, and "
|
||||
"keeps the markup/tax figures as an assumption rather than applying "
|
||||
"them - the TARIFF-02 trap, in data form",
|
||||
_DS["provenance"]["all_in"] is False
|
||||
and "ASSUMPTION" in _ASSUME["status"]
|
||||
and _DS["provenance"]["licence"].startswith("CC BY 4.0"))
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
@@ -0,0 +1,296 @@
|
||||
"""Runnable check for TEST-15 - the mutation harness's own honesty.
|
||||
`python3 test_bytecode.py`
|
||||
|
||||
Every other file in this directory grades the add-on. This one grades the thing
|
||||
that grades the add-on, because in this repository a mutation run IS the
|
||||
evidence: "I broke it, the suite went red, I put it back, the suite went green"
|
||||
is how nearly every safety claim here was established.
|
||||
|
||||
THE DEFECT, found by FCST-03's developer and reproduced below. CPython decides a
|
||||
cached `.pyc` is still good from two numbers: the source's SIZE, and its
|
||||
MTIME TRUNCATED TO WHOLE SECONDS. Reverting `self.provisional` to
|
||||
`here.provisional` moves neither - same length, same second - so the interpreter
|
||||
loaded the bytecode it already had. Confirmed then by disassembly: the source
|
||||
read `here`, the running code loaded `self`. The mutation was reported as a
|
||||
survivor when in truth it had never run.
|
||||
|
||||
WHICH DIRECTION IT LIES IN. A mutation that never took effect makes the suite
|
||||
stay GREEN, so it is reported as a survivor: stale bytecode MANUFACTURES
|
||||
SURVIVORS. The opposite - a revert that never took, leaving a red on correct
|
||||
source - is possible too but announces itself, because a developer chases an
|
||||
unexplained failure. That asymmetry is why the coverage-audit table in
|
||||
test_control.py is a lower bound rather than nonsense, and it is what the survey
|
||||
in MUTATION.md is scoped by.
|
||||
|
||||
WHAT THIS FILE PINS, in the order the card's acceptance criteria name it:
|
||||
|
||||
AC1 The defect reproduces (part 1), the two mitigations that DO NOT fix it
|
||||
are shown not to (part 2), the one that does is shown to (part 3), and
|
||||
the shipped harness is shown to close it end to end on a tree that would
|
||||
otherwise mis-grade (part 4). Executed, not reasoned: every part builds a
|
||||
real package, imports it in a real subprocess, and reads back which
|
||||
value the running code returned.
|
||||
AC2 The guarantee is where a developer writing a mutation reads it: part 5
|
||||
requires EVERY test_*.py in this directory to point at MUTATION.md. The
|
||||
list is derived from the tree, so a new suite that joins without the
|
||||
pointer is red - CI-01's rule, for CI-01's reason.
|
||||
AC4 Part 6 pins the two properties that make CI immune, on the workflow file
|
||||
itself.
|
||||
|
||||
⚠️ NOTHING HERE SLEEPS. One-second mtime resolution is the mechanism; a harness
|
||||
that waits out the clock would be slower on every run and would still only cover
|
||||
the edit somebody remembered to slow down. Part 1 REPRODUCES the collision
|
||||
deliberately (it retries until two writes land in the same second, which takes
|
||||
milliseconds) rather than avoiding it.
|
||||
|
||||
⚠️ This file writes only under a temporary directory. It must stay that way: CI
|
||||
mounts the checkout READ-ONLY, and a check that needs to write into the tree
|
||||
would fail there for a reason that has nothing to do with what it grades.
|
||||
|
||||
⚠️ MUTATING THE MODULE THIS FILE GRADES? PURGE `__pycache__` FIRST - or use
|
||||
`tools/mutation_run.sh`, which does. `python3 -B` alone does NOT save you: it
|
||||
stops bytecode being WRITTEN, not a stale one being READ. See MUTATION.md.
|
||||
"""
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
fails = []
|
||||
|
||||
|
||||
def check(name, cond):
|
||||
if cond:
|
||||
print(f" ok {name}")
|
||||
else:
|
||||
print(f" FAIL {name}")
|
||||
fails.append(name)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# The fixture. `who()` returns one of two names that are THE SAME LENGTH, so
|
||||
# swapping them leaves the file byte count identical - the first half of
|
||||
# CPython's staleness test. The second half is the whole-second mtime, which
|
||||
# part 1 arranges by writing both versions inside one second.
|
||||
#
|
||||
# It is deliberately not a copy of a shipped module: the property under test is
|
||||
# CPython's, and using real code here would make this file go red whenever that
|
||||
# module changed for unrelated reasons.
|
||||
# ---------------------------------------------------------------------------
|
||||
V_OLD = 'def who():\n self = "SELF"\n here = "HERE"\n return self\n'
|
||||
V_NEW = 'def who():\n self = "SELF"\n here = "HERE"\n return here\n'
|
||||
assert len(V_OLD) == len(V_NEW), "the fixture must be size-preserving or it grades nothing"
|
||||
|
||||
PROBE = "from app.m import who\nprint(who())\n"
|
||||
# The harness runs `test_*.py` files and grades them by exit status, so the
|
||||
# probe wears that shape in part 4: it FAILS when it sees the pre-mutation value.
|
||||
TEST_PROBE = (
|
||||
"from app.m import who\n"
|
||||
"v = who()\n"
|
||||
"print('RUNS:', v)\n"
|
||||
"raise SystemExit(0 if v == 'HERE' else 1)\n"
|
||||
)
|
||||
|
||||
|
||||
def run(tree, args, env_extra=None, script="probe.py"):
|
||||
env = dict(os.environ)
|
||||
env.pop("PYTHONDONTWRITEBYTECODE", None)
|
||||
if env_extra:
|
||||
env.update(env_extra)
|
||||
out = subprocess.run(
|
||||
[sys.executable] + args + [script],
|
||||
cwd=tree, env=env, capture_output=True, text=True,
|
||||
)
|
||||
return out.stdout.strip()
|
||||
|
||||
|
||||
def caches(tree):
|
||||
return sorted(str(p.relative_to(tree)) for p in Path(tree).rglob("__pycache__"))
|
||||
|
||||
|
||||
def seed(tree):
|
||||
"""Leave `tree` holding V_NEW on disk and V_OLD in its bytecode cache.
|
||||
|
||||
Returns True when the collision was actually arranged. Both writes must land
|
||||
in the same whole second; at a few milliseconds per cycle that is the normal
|
||||
case, and the caller retries rather than asserting on one attempt, because a
|
||||
machine that happens to cross a second boundary mid-cycle would otherwise
|
||||
report a defect in CPython instead of a slow disk.
|
||||
"""
|
||||
app = Path(tree) / "app"
|
||||
shutil.rmtree(app, ignore_errors=True)
|
||||
app.mkdir(parents=True)
|
||||
(app / "__init__.py").write_text("")
|
||||
(Path(tree) / "probe.py").write_text(PROBE)
|
||||
(Path(tree) / "test_probe.py").write_text(TEST_PROBE)
|
||||
|
||||
m = app / "m.py"
|
||||
m.write_text(V_OLD)
|
||||
t0 = m.stat().st_mtime
|
||||
run(tree, []) # compiles V_OLD, writes app/__pycache__
|
||||
m.write_text(V_NEW) # the "revert": same size, same second
|
||||
t1 = m.stat().st_mtime
|
||||
return int(t0) == int(t1) and caches(tree) != []
|
||||
|
||||
|
||||
def seeded_tree(stack):
|
||||
tree = tempfile.mkdtemp(prefix="test_bytecode.")
|
||||
stack.append(tree)
|
||||
for _ in range(40):
|
||||
if seed(tree):
|
||||
return tree
|
||||
return None
|
||||
|
||||
|
||||
tmpdirs = []
|
||||
print("stale bytecode (TEST-15)")
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
print("\n1. the defect: a same-size edit inside one second is not seen at all")
|
||||
# ---------------------------------------------------------------------------
|
||||
tree = seeded_tree(tmpdirs)
|
||||
check("the collision can be arranged at all (same size, same second)", tree is not None)
|
||||
if tree is None:
|
||||
print(" cannot continue - the fixture never landed two writes in one second")
|
||||
raise SystemExit(1)
|
||||
|
||||
src = (Path(tree) / "app" / "m.py").read_text()
|
||||
check("the source on disk says HERE", "return here" in src and "return self" not in src)
|
||||
check("...and a plain interpreter runs SELF anyway", run(tree, []) == "SELF")
|
||||
# Stated as its own check because this is the whole ticket in one line: what the
|
||||
# file says and what the process executes have come apart, with no error, no
|
||||
# warning, and a zero exit status.
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
print("\n2. the two mitigations that do NOT close it")
|
||||
# ---------------------------------------------------------------------------
|
||||
# ⚠️ READ THIS BEFORE 'FIXING' A HARNESS WITH -B ALONE. Both of these stop
|
||||
# bytecode being WRITTEN. Neither stops a stale one being READ, and a mutation
|
||||
# run always has one already: the previous run wrote it. The advice in
|
||||
# test_control.py's coverage audit said `-B` first and CLEAR the cache second;
|
||||
# the order is not a style choice, the clear is the half that works.
|
||||
check("`python3 -B` over an existing cache still runs SELF", run(tree, ["-B"]) == "SELF")
|
||||
check(
|
||||
"PYTHONDONTWRITEBYTECODE=1 over an existing cache still runs SELF",
|
||||
run(tree, [], {"PYTHONDONTWRITEBYTECODE": "1"}) == "SELF",
|
||||
)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
print("\n3. the purge closes it, and -B keeps the next run clean")
|
||||
# ---------------------------------------------------------------------------
|
||||
for p in Path(tree).rglob("__pycache__"):
|
||||
shutil.rmtree(p, ignore_errors=True)
|
||||
check("after the purge, the plain interpreter runs HERE", run(tree, []) == "HERE")
|
||||
check("...and it has written a fresh cache back", caches(tree) != [])
|
||||
|
||||
tree2 = seeded_tree(tmpdirs)
|
||||
check("second fixture seeded", tree2 is not None)
|
||||
if tree2:
|
||||
for p in Path(tree2).rglob("__pycache__"):
|
||||
shutil.rmtree(p, ignore_errors=True)
|
||||
check("purge + -B runs HERE", run(tree2, ["-B"]) == "HERE")
|
||||
check("...and leaves NO cache for the next mutation to inherit", caches(tree2) == [])
|
||||
# The second half is why the harness passes -B at all. Purging before a run
|
||||
# protects THIS run; not writing one protects the NEXT edit, which is the
|
||||
# one nobody is thinking about when they are three mutations into a batch.
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
print("\n4. the shipped harness, executed against a tree that would mis-grade")
|
||||
# ---------------------------------------------------------------------------
|
||||
harness = HERE / "tools" / "mutation_run.sh"
|
||||
check("tools/mutation_run.sh exists", harness.is_file())
|
||||
check("...and is executable", os.access(harness, os.X_OK))
|
||||
|
||||
tree3 = seeded_tree(tmpdirs)
|
||||
check("third fixture seeded", tree3 is not None)
|
||||
if tree3 and harness.is_file():
|
||||
# NON-VACUITY FIRST. If the naked run below were already green, the harness
|
||||
# run after it would prove nothing - it would be passing on a tree that
|
||||
# needed no help. This is the same trap test_peakguard.py part 7 documents:
|
||||
# a mutation harness that patches nothing passes beautifully.
|
||||
naked = subprocess.run(
|
||||
[sys.executable, "test_probe.py"], cwd=tree3, capture_output=True, text=True
|
||||
)
|
||||
check("without the harness the tree grades the STALE source (rc!=0)", naked.returncode != 0)
|
||||
check("...and says so: it saw SELF", "SELF" in naked.stdout)
|
||||
|
||||
got = subprocess.run(
|
||||
["sh", str(harness), tree3], cwd=tree3, capture_output=True, text=True
|
||||
)
|
||||
check("the harness grades the source on disk (rc==0)", got.returncode == 0)
|
||||
check("...having reported the purge", "no bytecode cache" in got.stdout)
|
||||
check("...and it leaves no cache behind", caches(tree3) == [])
|
||||
if got.returncode != 0:
|
||||
print(got.stdout[-2000:])
|
||||
print(got.stderr[-2000:])
|
||||
|
||||
# The harness must also refuse to report on nothing - CI-01's zero-file rule.
|
||||
empty = tempfile.mkdtemp(prefix="test_bytecode.empty.")
|
||||
tmpdirs.append(empty)
|
||||
none = subprocess.run(
|
||||
["sh", str(harness), empty], cwd=empty, capture_output=True, text=True
|
||||
)
|
||||
check("the harness refuses a tree with no test_*.py", none.returncode != 0)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
print("\n5. the guarantee is stated where a mutation gets written")
|
||||
# ---------------------------------------------------------------------------
|
||||
# ⚠️ THE LIST IS DERIVED FROM THE TREE. A hand-written one is how a new suite
|
||||
# joins this directory carrying no warning at all, which is the exact shape of
|
||||
# failure CI-01's file glob exists to prevent. If you add a test_*.py, put the
|
||||
# pointer in its docstring; that is the whole cost.
|
||||
doc = HERE / "MUTATION.md"
|
||||
check("MUTATION.md exists", doc.is_file())
|
||||
if doc.is_file():
|
||||
text = doc.read_text()
|
||||
check("...and it names the purge as the load-bearing half", "__pycache__" in text and "purge" in text.lower())
|
||||
check("...and warns that -B alone does not read fresh", "-B" in text)
|
||||
check("...and points at the harness", "mutation_run.sh" in text)
|
||||
|
||||
suites = sorted(p.name for p in HERE.glob("test_*.py"))
|
||||
check("there are test suites to survey at all", len(suites) >= 15)
|
||||
missing = [n for n in suites if "MUTATION.md" not in (HERE / n).read_text()]
|
||||
check(f"every one of the {len(suites)} suites points at MUTATION.md", missing == [])
|
||||
if missing:
|
||||
print(" missing the pointer:", ", ".join(missing))
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
print("\n6. CI cannot carry a stale artefact between jobs")
|
||||
# ---------------------------------------------------------------------------
|
||||
# ⚠️ THE FIRST TWO PROPERTIES ARE THE ONES THAT ACTUALLY DO THE WORK, AND THEY
|
||||
# PREDATE THIS CARD. Measured for TEST-15, not assumed: with the checkout bind
|
||||
# mounted READ-ONLY the interpreter writes no __pycache__ into the tree at all,
|
||||
# and it does so SILENTLY - no error, no warning, exit status 0. The workflow
|
||||
# also `rm -rf`s its workspace and clones afresh, so nothing survives from a
|
||||
# previous job even on the same runner. PYTHONDONTWRITEBYTECODE=1 is belt and
|
||||
# braces on top: it is what keeps this true if somebody ever needs to drop the
|
||||
# `:ro`, and dropping the `:ro` is a one-character edit that nothing else here
|
||||
# would notice.
|
||||
wf = HERE.parent / ".gitea" / "workflows" / "checks.yml"
|
||||
check("the workflow file is where this expects it", wf.is_file())
|
||||
if wf.is_file():
|
||||
y = wf.read_text()
|
||||
# ⚠️ GRADED ON THE COMMAND LINE, NOT ON THE FILE. A `in y` search over the
|
||||
# whole workflow passes on the PROSE around the step - this file's first
|
||||
# draft did exactly that, and stayed green after the `-e` flag and the `:ro`
|
||||
# were deleted, because the comment explaining them still named both.
|
||||
runs = [l for l in y.splitlines() if "docker run" in l and ":/w" in l]
|
||||
check("exactly one docker run mounts the checkout", len(runs) == 1)
|
||||
line = runs[0] if runs else ""
|
||||
check("the checkout is mounted read-only", ':/w:ro"' in line)
|
||||
check("PYTHONDONTWRITEBYTECODE=1 is set on that run", "-e PYTHONDONTWRITEBYTECODE=1" in line)
|
||||
check("the workspace is removed before each checkout", 'rm -rf "$WS"' in y)
|
||||
check("no sleep was introduced to dodge the mtime resolution", "sleep " not in y)
|
||||
|
||||
for d in tmpdirs:
|
||||
shutil.rmtree(d, ignore_errors=True)
|
||||
|
||||
print()
|
||||
if fails:
|
||||
print(f"{len(fails)} FAILED: " + "; ".join(fails))
|
||||
sys.exit(1)
|
||||
print("all checks passed")
|
||||
@@ -0,0 +1,407 @@
|
||||
"""Runnable check for CI-02 - what a green from `checks / unit` is a claim about.
|
||||
`python3 test_ci_gate.py`
|
||||
|
||||
test_bytecode.py grades the thing that grades the add-on. This file grades the
|
||||
thing that decides whether anything was graded at all.
|
||||
|
||||
THE DEFECT, and the correction the measurement forced. CI-02 was filed saying
|
||||
that a CONFLICTED pull request loses its merge ref, so that
|
||||
|
||||
git fetch -q --depth 1 origin "$GITHUB_REF" \
|
||||
|| git fetch -q --depth 1 origin "$GITHUB_SHA"
|
||||
|
||||
falls through to the second half and quietly grades the bare branch head. PR #14
|
||||
did report `checks / unit -> success` while `mergeable: false`, so the symptom
|
||||
was real. The mechanism was not. Measured on a deliberately conflicted throwaway
|
||||
pull request (#29, runs 558 and 559 - one question per STEP, because this
|
||||
Gitea's Actions log endpoints 404 and a step's conclusion is the only channel
|
||||
out of a job):
|
||||
|
||||
GITHUB_REF == refs/pull/<n>/head P01 passed
|
||||
GITHUB_REF != refs/pull/<n>/merge P02 failed
|
||||
GITHUB_SHA == the pull request head sha P03 passed
|
||||
fetching GITHUB_REF succeeds P04 passed <- even conflicted
|
||||
...and it lands on the bare head P05 passed
|
||||
refs/pull/<n>/merge does not exist P06 failed
|
||||
|
||||
`git ls-remote origin 'refs/pull/*'` on this server advertises only `/head`, for
|
||||
open and closed pull requests alike. THERE ARE NO MERGE REFS HERE. So the first
|
||||
half of the `||` always succeeded, the fallback never fired once, and both halves
|
||||
named the same commit anyway. The gate has never graded merged content on any
|
||||
pull request in this repository's history. Green has meant "this branch passed
|
||||
on its own" - which, on a base branch that has moved underneath it, is not the
|
||||
content that lands. `block_on_outdated_branch` is off on release/1.0, so the
|
||||
base usually has moved.
|
||||
|
||||
WHAT THIS FILE PINS.
|
||||
|
||||
Part 1 The context string branch protection requires is assembled from two
|
||||
tokens in checks.yml. Renaming either makes every open and future
|
||||
pull request unmergeable forever, silently, because Gitea waits on a
|
||||
context it will now never receive. This part is the tripwire on that.
|
||||
Part 2 The three absences in checks.yml that are load-bearing, each graded
|
||||
on the command lines rather than on the prose around them.
|
||||
Part 3 THE DEFECT, REPRODUCED. The old one-line checkout is run verbatim
|
||||
against a real conflicted pull request built here, and is shown to
|
||||
exit 0 having checked out content that cannot land.
|
||||
Part 4 THE FIX, EXECUTED. The checkout and merge steps are EXTRACTED FROM
|
||||
checks.yml AND RUN - the shipped commands, not a paraphrase - against
|
||||
a pull request that merges. The tree they leave behind is the merge,
|
||||
and is shown to differ from the head the old line would have graded.
|
||||
Part 5 The same two steps against a pull request that does NOT merge: the
|
||||
merge step exits non-zero, says nothing was tested, and never prints
|
||||
a GRADED line.
|
||||
Part 6 The gate announces which content it graded, on both paths, so that a
|
||||
reader can tell merged content from a bare ref (CI-02 AC2).
|
||||
|
||||
⚠️ THIS FILE RUNS THE WORKFLOW'S OWN SHELL. That is the point: a check that
|
||||
read those commands as a string and matched them against an expectation would
|
||||
be exactly the failure this repository keeps finding - a reading that never
|
||||
observed its subject. The extractor below is deliberately brittle about finding
|
||||
the step it wants: if checks.yml is restructured so that the step cannot be
|
||||
found, this file goes RED rather than quietly grading nothing.
|
||||
|
||||
⚠️ NEEDS `git`, which is why .gitea/ci/Dockerfile installs it. No network: the
|
||||
fixtures are local repositories built in a temp directory, and the workflow's
|
||||
`git remote add origin "$(echo "$URL" | sed "s#://#://x-access-token:...@#")"`
|
||||
is a no-op substitution on a path with no `://` in it, which is what lets the
|
||||
shipped line be used verbatim.
|
||||
|
||||
⚠️ This file writes only under a temporary directory. It must stay that way:
|
||||
CI mounts the checkout READ-ONLY.
|
||||
|
||||
⚠️ MUTATING THE MODULE THIS FILE GRADES? PURGE `__pycache__` FIRST - or use
|
||||
`tools/mutation_run.sh`, which does. See MUTATION.md. (There is no module here
|
||||
to mutate; the subject is checks.yml. Break a line of it and re-run this file
|
||||
expecting red - if it stays green, it was never watching.)
|
||||
"""
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
WF = HERE.parent / ".gitea" / "workflows" / "checks.yml"
|
||||
fails = []
|
||||
|
||||
|
||||
def check(name, cond):
|
||||
if cond:
|
||||
print(f" ok {name}")
|
||||
else:
|
||||
print(f" FAIL {name}")
|
||||
fails.append(name)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Reading checks.yml. There is no yaml module in the image the checks run in
|
||||
# (alpine py3-aiohttp py3-paho-mqtt, and adding a parser to grade five lines
|
||||
# would be a worse trade than a small parser that fails loudly), so the two
|
||||
# things this file needs are pulled out by hand:
|
||||
#
|
||||
# * the workflow name and the job keys, for part 1
|
||||
# * the `run:` block of a named step, verbatim, for parts 3 to 6
|
||||
#
|
||||
# COMMAND LINES ONLY WHERE IT MATTERS. test_bytecode.py's part 6 learned this
|
||||
# the hard way: an `in y` search over a whole workflow passes on the PROSE that
|
||||
# explains a flag, and stayed green after the flag itself was deleted. Every
|
||||
# absence checked in part 2 is checked against the file with its comment lines
|
||||
# stripped.
|
||||
# ---------------------------------------------------------------------------
|
||||
if not WF.is_file():
|
||||
print(f"cannot find the workflow at {WF} - nothing to grade")
|
||||
raise SystemExit(1)
|
||||
YAML = WF.read_text()
|
||||
CODE = "\n".join(l for l in YAML.splitlines() if not l.lstrip().startswith("#"))
|
||||
|
||||
|
||||
def workflow_name():
|
||||
for line in YAML.splitlines():
|
||||
if line.startswith("name:"):
|
||||
return line.split(":", 1)[1].strip()
|
||||
return None
|
||||
|
||||
|
||||
def job_keys():
|
||||
out, seen = [], False
|
||||
for line in YAML.splitlines():
|
||||
if line.startswith("jobs:"):
|
||||
seen = True
|
||||
continue
|
||||
if seen:
|
||||
if line and not line[0].isspace():
|
||||
break
|
||||
if line.startswith(" ") and not line.startswith(" ") and line.rstrip().endswith(":"):
|
||||
out.append(line.strip()[:-1])
|
||||
return out
|
||||
|
||||
|
||||
def step_script(name_prefix):
|
||||
"""Return the `run: |` body of the step whose name starts with name_prefix."""
|
||||
lines = YAML.splitlines()
|
||||
i = 0
|
||||
while i < len(lines):
|
||||
if lines[i].strip().startswith("- name:") and name_prefix in lines[i]:
|
||||
break
|
||||
i += 1
|
||||
else:
|
||||
return None
|
||||
if i >= len(lines):
|
||||
return None
|
||||
while i < len(lines) and lines[i].strip() != "run: |":
|
||||
# stop at the next step so a missing block cannot borrow the next one's
|
||||
if i > 0 and lines[i].strip().startswith("- name:") and name_prefix not in lines[i]:
|
||||
return None
|
||||
i += 1
|
||||
if i >= len(lines):
|
||||
return None
|
||||
body, i = [], i + 1
|
||||
while i < len(lines):
|
||||
l = lines[i]
|
||||
if l.strip() == "":
|
||||
body.append("")
|
||||
elif l.startswith(" " * 10):
|
||||
body.append(l[10:])
|
||||
else:
|
||||
break
|
||||
i += 1
|
||||
return "\n".join(body).strip("\n")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# The fixture: a real bare repository with a base branch and a refs/pull/N/head,
|
||||
# built to order. `conflict=True` makes the pull request touch the same lines
|
||||
# the base moved, which is how PR #29 was made unmergeable on the server.
|
||||
#
|
||||
# The shapes matter. In BOTH cases the pull request adds `from_pr.txt` and the
|
||||
# base adds `from_base.txt` AFTER the branch point, so the branch head is never
|
||||
# the content that lands even when it merges perfectly - that difference is what
|
||||
# part 4 measures, and it is the ordinary case, not the pathological one.
|
||||
# ---------------------------------------------------------------------------
|
||||
GIT = ["git", "-c", "user.email=fixture@localhost", "-c", "user.name=fixture",
|
||||
"-c", "init.defaultBranch=release/1.0", "-c", "commit.gpgsign=false"]
|
||||
PRNUM = "7"
|
||||
BASEREF = "release/1.0"
|
||||
|
||||
|
||||
def git(cwd, *args, check_rc=True):
|
||||
r = subprocess.run(GIT + list(args), cwd=cwd, capture_output=True, text=True)
|
||||
if check_rc and r.returncode != 0:
|
||||
raise RuntimeError(f"git {' '.join(args)} failed in {cwd}:\n{r.stderr}")
|
||||
return r.stdout.strip()
|
||||
|
||||
|
||||
def build_origin(stack, conflict):
|
||||
"""A bare repo carrying refs/heads/release/1.0 and refs/pull/7/head."""
|
||||
root = Path(tempfile.mkdtemp(prefix="test_ci_gate."))
|
||||
stack.append(str(root))
|
||||
work, bare = root / "work", root / "origin.git"
|
||||
work.mkdir()
|
||||
git(work, "init", "-q", ".")
|
||||
(work / "shared.txt").write_text("one\ntwo\nthree\n")
|
||||
git(work, "add", "-A")
|
||||
git(work, "commit", "-qm", "branch point")
|
||||
fork = git(work, "rev-parse", "HEAD")
|
||||
|
||||
# the base moves on
|
||||
(work / "from_base.txt").write_text("only the base has this\n")
|
||||
if conflict:
|
||||
(work / "shared.txt").write_text("one\nTWO FROM BASE\nthree\n")
|
||||
git(work, "add", "-A")
|
||||
git(work, "commit", "-qm", "the base branch moves on")
|
||||
base_sha = git(work, "rev-parse", "HEAD")
|
||||
|
||||
# the pull request branches from the fork point
|
||||
git(work, "checkout", "-q", "-b", "pr", fork)
|
||||
(work / "from_pr.txt").write_text("only the pull request has this\n")
|
||||
if conflict:
|
||||
(work / "shared.txt").write_text("one\nTWO FROM THE PULL REQUEST\nthree\n")
|
||||
git(work, "add", "-A")
|
||||
git(work, "commit", "-qm", "the pull request")
|
||||
pr_sha = git(work, "rev-parse", "HEAD")
|
||||
|
||||
git(root, "init", "-q", "--bare", str(bare))
|
||||
git(work, "remote", "add", "origin", str(bare))
|
||||
git(work, "push", "-q", "origin", f"{base_sha}:refs/heads/{BASEREF}")
|
||||
git(work, "push", "-q", "origin", f"{pr_sha}:refs/pull/{PRNUM}/head")
|
||||
return str(bare), base_sha, pr_sha, str(root)
|
||||
|
||||
|
||||
def run_script(script, ws, origin, pr_sha, extra=None):
|
||||
env = dict(os.environ)
|
||||
env.pop("PYTHONDONTWRITEBYTECODE", None)
|
||||
env.update(
|
||||
WS=ws, PRNUM=PRNUM, BASEREF=BASEREF, URL=origin, TOKEN="",
|
||||
GITHUB_REF=f"refs/pull/{PRNUM}/head", GITHUB_SHA=pr_sha,
|
||||
GIT_TERMINAL_PROMPT="0",
|
||||
)
|
||||
if extra:
|
||||
env.update(extra)
|
||||
return subprocess.run(["sh", "-c", script], env=env, capture_output=True, text=True)
|
||||
|
||||
|
||||
tmpdirs = []
|
||||
print("the gate's own honesty (CI-02)")
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
print("\n1. the required context string, from the two tokens that build it")
|
||||
# ---------------------------------------------------------------------------
|
||||
# ⚠️ READ BEFORE RENAMING ANYTHING IN checks.yml. Branch protection on
|
||||
# release/1.0 has `enable_status_check: true` and
|
||||
# `status_check_contexts: ['checks / unit (pull_request)']`. Gitea assembles
|
||||
# that string from `name:` at the top of the workflow and the job KEY under
|
||||
# `jobs:`. Change either and Gitea starts posting a context nobody is waiting
|
||||
# for, while the one branch protection requires never arrives - so it stays
|
||||
# `pending` forever, on every open pull request and every future one, and
|
||||
# admin override is blocked. There is no error message anywhere in that
|
||||
# sequence. This check is the only thing between a tidy-up and that.
|
||||
REQUIRED = "checks / unit (pull_request)"
|
||||
name, jobs = workflow_name(), job_keys()
|
||||
check("the workflow still has a name", name is not None)
|
||||
check("the workflow declares exactly one job", len(jobs) == 1)
|
||||
built = f"{name} / {jobs[0]} (pull_request)" if name and len(jobs) == 1 else "<unparseable>"
|
||||
check(f"the context it builds is exactly {REQUIRED!r}", built == REQUIRED)
|
||||
if built != REQUIRED:
|
||||
print(f" it now builds {built!r} - branch protection will wait forever for {REQUIRED!r}")
|
||||
check("the workflow still triggers on pull_request", "pull_request:" in CODE)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
print("\n2. the three absences that are load-bearing")
|
||||
# ---------------------------------------------------------------------------
|
||||
# `paths:` is CI-01's: a workflow that learns to sit a pull request out leaves
|
||||
# the required context pending forever, which is unmergeable forever.
|
||||
check("no paths: filter", not any(l.strip().startswith("paths:") or l.strip().startswith("paths-ignore:")
|
||||
for l in CODE.splitlines()))
|
||||
# `concurrency:` is CI-02's, and it was MEASURED rather than reasoned about, on
|
||||
# throwaway PR #29 with one run holding the single runner slot and two more
|
||||
# pushes behind it:
|
||||
# no block at all -> runs 561 and 562 both queued, both executed
|
||||
# group + cancel-in-progress: false
|
||||
# -> run 564 sat `Blocked by required conditions`
|
||||
# and was cancelled at 0s the moment 565 existed
|
||||
# A shared group cancels a run that has not started regardless of that flag, and
|
||||
# a cancelled run posts `failure` on the required context ("Canceled after 0s"),
|
||||
# which branch protection cannot tell from a real test failure. Runs 531 and 533
|
||||
# on PR #14 died exactly this way, each at the same second the next run was
|
||||
# created. Having no group is the only setting measured to leave a queued run
|
||||
# alive.
|
||||
check("no concurrency: group", not any(l.startswith("concurrency:") for l in CODE.splitlines()))
|
||||
check("no cancel-in-progress anywhere in the commands", "cancel-in-progress" not in CODE)
|
||||
# The fallback itself. Graded on the command lines: the prose above the step
|
||||
# quotes the old line on purpose, and an `in YAML` search would match that.
|
||||
check("the || $GITHUB_SHA fallback is gone from the commands",
|
||||
not any("||" in l and "GITHUB_SHA" in l for l in CODE.splitlines()))
|
||||
check("the checkout is no longer shallow (a merge needs the merge base)",
|
||||
"--depth 1" not in CODE)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
print("\n3. the defect, reproduced: the old line grades a conflicted head, happily")
|
||||
# ---------------------------------------------------------------------------
|
||||
# NON-VACUITY FOR EVERYTHING BELOW. If this part were already red - if the old
|
||||
# line refused a conflicted pull request on its own - then parts 4 and 5 would
|
||||
# be measuring nothing, and the ticket would have no subject.
|
||||
origin, base_sha, pr_sha, _root = build_origin(tmpdirs, conflict=True)
|
||||
ws = tempfile.mkdtemp(prefix="test_ci_gate.ws.")
|
||||
tmpdirs.append(ws)
|
||||
OLD = '''
|
||||
set -eu
|
||||
rm -rf "$WS" && mkdir -p "$WS/goodwe-addon" && cd "$WS/goodwe-addon"
|
||||
git init -q .
|
||||
git remote add origin "$(echo "$URL" | sed "s#://#://x-access-token:${TOKEN}@#")"
|
||||
git fetch -q --depth 1 origin "$GITHUB_REF" || git fetch -q --depth 1 origin "$GITHUB_SHA"
|
||||
git checkout -qf FETCH_HEAD
|
||||
echo "checked out $(git log --oneline -1)"
|
||||
'''
|
||||
old = run_script(OLD, ws, origin, pr_sha)
|
||||
check("the pull request genuinely does not merge (the fixture is not lying)",
|
||||
subprocess.run(GIT + ["merge-tree", "--write-tree", base_sha, pr_sha],
|
||||
cwd=origin, capture_output=True, text=True).returncode != 0)
|
||||
check("...and the old checkout exits 0 on it anyway", old.returncode == 0)
|
||||
tree = Path(ws) / "goodwe-addon"
|
||||
check("...having checked out the bare head", (tree / "from_pr.txt").is_file())
|
||||
check("...which is missing what the base branch added", not (tree / "from_base.txt").is_file())
|
||||
check("...and it says nothing about which of the two refs it used",
|
||||
"GRADED" not in old.stdout and "REFUSED" not in old.stdout)
|
||||
if old.returncode != 0:
|
||||
print(old.stdout[-800:], old.stderr[-800:])
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
print("\n4. the shipped steps, executed, on a pull request that MERGES")
|
||||
# ---------------------------------------------------------------------------
|
||||
CO = step_script("check out the base branch and the pull request head")
|
||||
MERGE = step_script("grade the merge, not the branch")
|
||||
check("the checkout step can be found in checks.yml", CO is not None)
|
||||
check("the merge/refuse step can be found in checks.yml", MERGE is not None)
|
||||
if CO is None or MERGE is None:
|
||||
print(" checks.yml has been restructured; this file grades nothing until it is updated")
|
||||
print()
|
||||
print(f"{len(fails)} FAILED")
|
||||
raise SystemExit(1)
|
||||
|
||||
origin2, base2, pr2, _r2 = build_origin(tmpdirs, conflict=False)
|
||||
ws2 = tempfile.mkdtemp(prefix="test_ci_gate.ws2.")
|
||||
tmpdirs.append(ws2)
|
||||
co = run_script(CO, ws2, origin2, pr2)
|
||||
mg = run_script(MERGE, ws2, origin2, pr2)
|
||||
check("the checkout step succeeds", co.returncode == 0)
|
||||
check("the merge step succeeds on a mergeable pull request", mg.returncode == 0)
|
||||
if co.returncode or mg.returncode:
|
||||
print(co.stdout[-600:], co.stderr[-600:], mg.stdout[-600:], mg.stderr[-600:])
|
||||
t2 = Path(ws2) / "goodwe-addon"
|
||||
check("what is left on disk carries the pull request's file", (t2 / "from_pr.txt").is_file())
|
||||
check("...AND the file the base branch added after the branch point", (t2 / "from_base.txt").is_file())
|
||||
# That second one is the whole difference. The old line graded a tree WITHOUT
|
||||
# from_base.txt - green about content that is not what lands - and nothing in
|
||||
# the run said so. This is the ordinary case: no conflict anywhere in it.
|
||||
check("the graded tree is exactly the tree of a real merge",
|
||||
git(t2, "rev-parse", "HEAD^{tree}") ==
|
||||
subprocess.run(GIT + ["merge-tree", "--write-tree", base2, pr2],
|
||||
cwd=origin2, capture_output=True, text=True).stdout.strip())
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
print("\n5. the same two steps on a pull request that does NOT merge")
|
||||
# ---------------------------------------------------------------------------
|
||||
ws3 = tempfile.mkdtemp(prefix="test_ci_gate.ws3.")
|
||||
tmpdirs.append(ws3)
|
||||
co3 = run_script(CO, ws3, origin, pr_sha)
|
||||
mg3 = run_script(MERGE, ws3, origin, pr_sha)
|
||||
check("the checkout step still succeeds - a conflict does not stop a fetch",
|
||||
co3.returncode == 0)
|
||||
# Stated as its own check because it is why the defect was invisible: nothing
|
||||
# about a conflicted pull request makes any git fetch fail on this server.
|
||||
check("the merge step REFUSES (non-zero)", mg3.returncode != 0)
|
||||
check("...and says nothing was tested, not that a test failed",
|
||||
"REFUSED" in mg3.stdout and "NOTHING HAS BEEN TESTED" in mg3.stdout)
|
||||
check("...and never claims to have graded anything", "GRADED:" not in mg3.stdout)
|
||||
check("...and leaves no half-merged tree behind for a later step to grade",
|
||||
not (Path(ws3) / "goodwe-addon" / "from_pr.txt").is_file()
|
||||
or git(Path(ws3) / "goodwe-addon", "rev-parse", "HEAD") == base_sha)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
print("\n6. the run says which content it graded (CI-02 AC2)")
|
||||
# ---------------------------------------------------------------------------
|
||||
check("the mergeable run announces the merge it graded", "GRADED:" in mg.stdout)
|
||||
check("...naming the base branch it merged into", BASEREF in mg.stdout)
|
||||
check("...and the tree, which is the only unambiguous name for content",
|
||||
"tree" in mg.stdout and git(t2, "rev-parse", "HEAD^{tree}")[:12] in mg.stdout)
|
||||
# The no-pull-request path (workflow_dispatch) keeps a fallback, because a
|
||||
# branch really can vanish between the dispatch and the fetch. It has to say so.
|
||||
disp = run_script(CO, tempfile.mkdtemp(prefix="test_ci_gate.ws4."), origin2, pr2,
|
||||
extra={"PRNUM": "", "GITHUB_REF": f"refs/heads/{BASEREF}"})
|
||||
check("the no-pull-request path still checks something out", disp.returncode == 0)
|
||||
check("...and announces that it is NOT merged content",
|
||||
"GRADED:" in disp.stdout and "NOT merged content" in disp.stdout)
|
||||
if disp.returncode != 0:
|
||||
print(disp.stdout[-600:], disp.stderr[-600:])
|
||||
|
||||
for d in tmpdirs:
|
||||
shutil.rmtree(d, ignore_errors=True)
|
||||
|
||||
print()
|
||||
if fails:
|
||||
print(f"{len(fails)} FAILED: " + "; ".join(fails))
|
||||
sys.exit(1)
|
||||
print("all checks passed")
|
||||
@@ -4,7 +4,8 @@
|
||||
|
||||
No framework, asserts only, same house style as test_freeze.py.
|
||||
|
||||
Five parts, and parts 3 and 4 are the ones that carry the acceptance criteria:
|
||||
Six parts, and parts 3 and 4 are the ones that carry SAFETY-03's own
|
||||
acceptance criteria; part 6 is TEST-11's:
|
||||
|
||||
1. THE CLAMP ARITHMETIC, on the shipped `clamp_to_rating()` - boundaries,
|
||||
symmetry, the device second stage, and the non-finite cases. Table driven.
|
||||
@@ -23,6 +24,13 @@ Five parts, and parts 3 and 4 are the ones that carry the acceptance criteria:
|
||||
5. NO PATH BYPASSES IT. write_setpoint() is the only route to the wire, so it
|
||||
is called directly with an out-of-range value the way the heartbeat and the
|
||||
operator's buttons call it.
|
||||
6. TEST-11. THE GUARD READS THE WRITE THAT JUST HAPPENED. `self.clamp_last`
|
||||
is assigned by `write_setpoint()` and by nothing else, so a
|
||||
`check_output_clamp()` moved above the write keeps its loop-side evidence
|
||||
and silently loses its write-side half. Graded as a CONSEQUENCE - what the
|
||||
watchdog could see when it was consulted - so that a rename or a helper
|
||||
does not trip it, and with the write-path half exercised on a stimulus of
|
||||
its own, because parts 3-5 never produce one through cycle().
|
||||
|
||||
------------------------------------------------------------------------------
|
||||
WHY PART 4 ALSO ASSERTS ON `Decision`'s BOOLEANS AND NOT ON `reason`
|
||||
@@ -47,6 +55,13 @@ WHAT THIS CHECK DOES NOT COVER
|
||||
asserted here over every value that reached `set_number()`, which is the last
|
||||
thing this process controls; proving it at the inverter needs the witness log
|
||||
and belongs with DRIVER-07.
|
||||
|
||||
⚠️ MUTATING THE MODULE THIS FILE GRADES? PURGE `__pycache__` FIRST - or run
|
||||
`tools/mutation_run.sh`, which does. `python3 -B` alone does NOT save you: it
|
||||
stops bytecode being WRITTEN, not a stale one being READ, and a size-preserving
|
||||
edit reverted inside one second is invisible to CPython's staleness test. That
|
||||
is TEST-15, and it has already turned one live mutation into a false survivor.
|
||||
Read MUTATION.md before you report a survivor.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
@@ -543,6 +558,240 @@ check("an in-range value is untouched", hass_d.writes[3] == 1500.0)
|
||||
check("every emitted frame satisfies |emitted| <= the rating",
|
||||
all(abs(w) <= 2000.0 for w in hass_d.writes))
|
||||
|
||||
# ==============================================================================
|
||||
print()
|
||||
print("6. TEST-11: the guard's evidence is THIS cycle's write, not the last one")
|
||||
|
||||
# WHY THIS PART EXISTS. `check_output_clamp()` sits one line below
|
||||
# `await self.write_setpoint(self.target)` in cycle(), and moving it above the
|
||||
# write left this file, test_freeze.py and test_loop.py ALL GREEN. That is not a
|
||||
# missing assertion about line numbers - it is a missing assertion about
|
||||
# EVIDENCE. The guard has two sources:
|
||||
#
|
||||
# * `self.loop_clamped`, set from the Decision well ABOVE the write. Still
|
||||
# seen wherever the call is put, which is why the move is nearly invisible:
|
||||
# on the §10.3 replay above, every engagement the alarm reports is this one.
|
||||
# * `self.clamp_last`, which ONLY `write_setpoint()` assigns (main.py) and
|
||||
# which is None until it has run. This half is what loses its evidence.
|
||||
#
|
||||
# So the check below does not pin the call's POSITION IN THE SOURCE, and must
|
||||
# not: the comment at that line warns against tidying SAFETY-03's ordering and
|
||||
# SAFETY-18's into one rule, and a check a rename breaks is worse than no check.
|
||||
# It pins the CONSEQUENCE - that when the guard is consulted, `self.clamp_last`
|
||||
# is the result of the write of THIS cycle - and part 6b runs the identical
|
||||
# assertions through a deliberately refactored controller to prove it.
|
||||
|
||||
|
||||
class _SpyWatchdog(ClampWatchdog):
|
||||
"""The shipped watchdog, plus a record of what the guard could SEE.
|
||||
|
||||
⚠️ IT HOOKS THE CONSUMER, NOT THE GUARD'S NAME. Wrapping
|
||||
`check_output_clamp` by name would make a rename - AC 2's legitimate
|
||||
refactor - look identical to the defect, and this ticket is explicitly not
|
||||
allowed to buy its check with a nuisance. `clamp_wd.note()` is the one call
|
||||
the guard exists to make, so it is hooked instead: it is reached from the
|
||||
guard under any name, from any helper, as long as that helper runs after the
|
||||
write.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.owner = None
|
||||
self.seen = [] # clamp_last.requested_w at each consultation
|
||||
self.seen_write = [] # was the WRITE-path half engaged, per cycle
|
||||
|
||||
def note(self, engaged, reason, now):
|
||||
cl = self.owner.clamp_last
|
||||
self.seen.append(None if cl is None else cl.requested_w)
|
||||
self.seen_write.append(bool(cl and cl.engaged))
|
||||
return super().note(engaged, reason, now)
|
||||
|
||||
|
||||
def probed(cls=Controller, grid=9000.0, cycles=5, **over):
|
||||
"""`wired()`, with the watchdog replaced by the spy and the per-cycle
|
||||
command returned. A RAMP is used on purpose: the slew limiter makes every
|
||||
cycle's command a different number, which is what makes "this cycle's
|
||||
evidence" and "last cycle's evidence" distinguishable at all."""
|
||||
async def go():
|
||||
# `track=True` - the plant follows, so the saturation freeze never
|
||||
# engages and the slew limiter keeps the command MOVING; against a
|
||||
# dead plant the freeze pins it flat after three cycles and the ramp
|
||||
# stops being a ramp.
|
||||
hass = _Hass(grid, track=True)
|
||||
c = cls(dict(
|
||||
{"setpoint_entity": "number.sp", "meter_entity": "sensor.grid",
|
||||
"soc_entity": "sensor.soc", "batt_entity": "sensor.batt",
|
||||
"meter_source": "off", "max_w": LIVE_MAX_W, "gain": 0.6,
|
||||
"slew_w": 1000, "deadband_w": 15, "target_grid_w": 0,
|
||||
"step_w": 10, "heartbeat_s": 10, "stale_input_s": 15},
|
||||
**over), hass, _Store(), _Pub(), stop=asyncio.Event())
|
||||
c.auto = True
|
||||
c.dev_min, c.dev_max = -LIVE_MAX_W, LIVE_MAX_W
|
||||
c.clamp_wd = _SpyWatchdog()
|
||||
c.clamp_wd.owner = c
|
||||
asked = []
|
||||
for _ in range(cycles):
|
||||
await c.read_inputs()
|
||||
await c.cycle()
|
||||
asked.append(c.target)
|
||||
return hass, c, asked
|
||||
return asyncio.run(go())
|
||||
|
||||
|
||||
def evidence_checks(label, asked, wd):
|
||||
"""The same four claims, run against the shipped controller (6a) and against
|
||||
a refactored one (6b). Sharing them is the point: if a rename or a helper
|
||||
changed the answer, this function would say so in the same words."""
|
||||
seen = wd.seen
|
||||
print(f" {label}: asked "
|
||||
f"{[f'{w:+.0f}' for w in asked]}")
|
||||
print(f" {label}: the guard saw "
|
||||
f"{['None' if s is None else f'{s:+.0f}' for s in seen]}")
|
||||
check(f"{label}: PRECONDITION - the command MOVES on every cycle, so this "
|
||||
f"cycle's evidence and last cycle's are different numbers",
|
||||
len(set(asked)) == len(asked) and len(asked) >= 4)
|
||||
check(f"{label}: the guard was consulted exactly once per cycle",
|
||||
len(seen) == len(asked))
|
||||
check(f"{label}: AC 1 - on EVERY cycle self.clamp_last held the result of "
|
||||
f"the write THAT CYCLE. write_setpoint() is the only line that "
|
||||
f"assigns self.clamp_last, so a check_output_clamp() moved above the "
|
||||
f"write grades the PREVIOUS cycle's write instead",
|
||||
seen == asked)
|
||||
check(f"{label}: ...and on the FIRST cycle self.clamp_last was already set "
|
||||
f"- before the run's first write it is None, i.e. the write-path half "
|
||||
f"of the guard has no evidence at all",
|
||||
bool(seen) and seen[0] is not None)
|
||||
|
||||
|
||||
hass_e, ctl_e, asked_e = probed()
|
||||
evidence_checks("shipped", asked_e, ctl_e.clamp_wd)
|
||||
|
||||
# ⚠️ AND HERE IS WHY AC 3 NEEDS A STIMULUS OF ITS OWN, MEASURED RATHER THAN
|
||||
# ASSERTED. Through the real cycle() the write-path half never engages: the
|
||||
# arbiter files the device range and max_w as P_SAFETY LIMIT claims, so
|
||||
# `resolution.target_w` is already inside both bounds before write_setpoint()
|
||||
# re-applies them (main.py calls that duplication defence in depth, and it is).
|
||||
# Every engagement the alarm reports on this path is therefore the loop-side
|
||||
# one - which is exactly what makes the move nearly invisible, and exactly why
|
||||
# 6c below drives the write path directly instead of hoping cycle() will.
|
||||
check(f"MEASURED: the write-path half engaged 0 times in {len(asked_e)} real "
|
||||
f"cycles ({sum(ctl_e.clamp_wd.seen_write)}), so no cycle()-driven check "
|
||||
f"can be watching it", not any(ctl_e.clamp_wd.seen_write))
|
||||
|
||||
|
||||
class _RefactoredController(Controller):
|
||||
"""AC 2, as a fixture rather than as a promise: the two refactors a P3 tidy
|
||||
would actually make, applied at once.
|
||||
|
||||
* the guard is RENAMED to `_clamp_guard()`, the old name left as the thin
|
||||
delegate such a rename leaves behind;
|
||||
* the write MOVES INTO A HELPER, `_emit_setpoint()`.
|
||||
|
||||
Neither changes when the guard runs relative to the write, so every check in
|
||||
`evidence_checks()` must stay green. If one of them goes red here, the check
|
||||
is grading the text of main.py and has to be thrown away.
|
||||
"""
|
||||
|
||||
async def _emit_setpoint(self, value, *, force=False):
|
||||
await Controller.write_setpoint(self, value, force=force)
|
||||
|
||||
async def write_setpoint(self, value, *, force=False):
|
||||
await self._emit_setpoint(value, force=force)
|
||||
|
||||
async def _clamp_guard(self):
|
||||
await Controller.check_output_clamp(self)
|
||||
|
||||
async def check_output_clamp(self):
|
||||
await self._clamp_guard()
|
||||
|
||||
|
||||
# ⚠️ VERIFIED AGAINST main.py ITSELF, NOT ONLY AGAINST THIS SUBCLASS. Renaming
|
||||
# `check_output_clamp` throughout main.py AND moving both the write and the guard
|
||||
# into a new `_emit_and_guard()` helper called from cycle() leaves every check in
|
||||
# this part green; moving the guard above the write turns the two AC 1 lines
|
||||
# below red. The one thing a repo-wide rename does cost is the direct call in 6c,
|
||||
# which is a mechanical find/replace and fails as an AttributeError naming the
|
||||
# new method - not as an assertion claiming the ordering is wrong, which is the
|
||||
# false signal this part was written to avoid.
|
||||
hass_f, ctl_f, asked_f = probed(cls=_RefactoredController)
|
||||
evidence_checks("renamed + helper", asked_f, ctl_f.clamp_wd)
|
||||
check("AC 2: the refactored controller behaves identically to the shipped one "
|
||||
"- same commands, same evidence, so the check above is not pinning "
|
||||
"either name",
|
||||
asked_f == asked_e and ctl_f.clamp_wd.seen == ctl_e.clamp_wd.seen)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 6c. AC 3 - the WRITE-PATH half, exercised
|
||||
# --------------------------------------------------------------------------- #
|
||||
# The stimulus is SAFETY-20's shape and that is not a coincidence: `max_w` 5000
|
||||
# on an inverter that reports +-2500 is the one configuration where the value
|
||||
# put on the wire DIFFERS from the value the loop asked for while every loop-side
|
||||
# flag stays clean. That difference is the whole content of `clamp_last`, and a
|
||||
# DEVICE-bound engagement is the only kind `loop_clamped` cannot also see.
|
||||
#
|
||||
# It is driven through `write_setpoint()` and the guard directly rather than
|
||||
# through cycle(), because the measurement above says cycle() cannot produce it
|
||||
# today. That is stated as a limitation, not hidden: what is being graded here is
|
||||
# the guard's own contract - given a write that clamped, alarm - and the ordering
|
||||
# in cycle() is what 6a grades.
|
||||
|
||||
|
||||
async def _write_path(moved=False):
|
||||
"""`moved` runs the two calls in the order the ticket asks about."""
|
||||
hass = _Hass(0.0)
|
||||
c = Controller({"setpoint_entity": "number.sp", "meter_source": "off",
|
||||
"max_w": LIVE_MAX_W},
|
||||
hass, _Store(), _Pub(), stop=asyncio.Event())
|
||||
c.auto = True
|
||||
# The inverter is SMALLER than the configured ceiling - SAFETY-20's install.
|
||||
c.dev_min, c.dev_max = -2500.0, 2500.0
|
||||
c.target = 3000.0
|
||||
if moved:
|
||||
await c.check_output_clamp()
|
||||
await c.write_setpoint(c.target)
|
||||
else:
|
||||
await c.write_setpoint(c.target)
|
||||
await c.check_output_clamp()
|
||||
return hass, c
|
||||
|
||||
|
||||
hass_w, ctl_w = asyncio.run(_write_path())
|
||||
notes_w = clamp_notes(hass_w)
|
||||
print(f" max_w {LIVE_MAX_W:.0f} on a +-2500 W device, asked for "
|
||||
f"{ctl_w.target:+.0f} W: the device saw {hass_w.writes[-1]:+.0f} W, "
|
||||
f"bound={ctl_w.clamp_last.bound!r}, loop_clamped={ctl_w.loop_clamped[0]}")
|
||||
check("PRECONDITION: the write really did clamp, on the DEVICE bound",
|
||||
ctl_w.clamp_last is not None and ctl_w.clamp_last.engaged
|
||||
and ctl_w.clamp_last.bound == "device"
|
||||
and hass_w.writes[-1] == 2500.0)
|
||||
check("...and the loop-side half is SILENT here, so self.clamp_last is the "
|
||||
"only evidence that this happened at all",
|
||||
ctl_w.loop_clamped == (False, ""))
|
||||
check("AC 3: the guard alarmed on write-path evidence alone",
|
||||
ctl_w.clamp_wd.engagements == 1 and len(notes_w) == 1)
|
||||
check("...and the operator is told WHICH bound bit, so a device-rating clamp "
|
||||
"is not reported as a max_w one",
|
||||
bool(notes_w) and "device bound" in notes_w[0]["message"])
|
||||
check("...and the action log carries the row, written by write_setpoint()",
|
||||
any(REASON_CODE in e and "device bound" in e for e in ctl_w.events))
|
||||
|
||||
# The same stimulus, the same clamp, the two calls swapped. This is the ticket
|
||||
# in one pair of runs.
|
||||
hass_m, ctl_m = asyncio.run(_write_path(moved=True))
|
||||
print(f" the same stimulus with the guard consulted BEFORE the write: "
|
||||
f"{ctl_m.clamp_wd.engagements} engagement(s), "
|
||||
f"{len(clamp_notes(hass_m))} notification(s), and the clamp still "
|
||||
f"happened (engaged={ctl_m.clamp_last.engaged})")
|
||||
check("THE DEFECT, DEMONSTRATED: consulted before the write the guard is "
|
||||
"SILENT - self.clamp_last is still None at that point - while the wire "
|
||||
"carries a clamped value either way",
|
||||
not clamp_notes(hass_m) and ctl_m.clamp_wd.engagements == 0
|
||||
and ctl_m.clamp_last.engaged and hass_m.writes[-1] == 2500.0)
|
||||
check("...and main.py:856's consumer is the line that goes quietly false",
|
||||
bool(ctl_w.clamp_last and ctl_w.clamp_last.engaged))
|
||||
|
||||
|
||||
print()
|
||||
if fails:
|
||||
print(f"{len(fails)} FAILED: {', '.join(fails)}")
|
||||
|
||||
@@ -6,6 +6,13 @@ its absence caused an observed failure on real hardware.
|
||||
|
||||
If you change control.py, run this. If it fails, the inverter would have done
|
||||
something you did not intend.
|
||||
|
||||
⚠️ MUTATING THE MODULE THIS FILE GRADES? PURGE `__pycache__` FIRST - or run
|
||||
`tools/mutation_run.sh`, which does. `python3 -B` alone does NOT save you: it
|
||||
stops bytecode being WRITTEN, not a stale one being READ, and a size-preserving
|
||||
edit reverted inside one second is invisible to CPython's staleness test. That
|
||||
is TEST-15, and it has already turned one live mutation into a false survivor.
|
||||
Read MUTATION.md before you report a survivor.
|
||||
"""
|
||||
|
||||
import sys
|
||||
@@ -71,14 +78,22 @@ def check(name, cond):
|
||||
# Hence: A FIXTURE MUST SIT CLEAR OF EVERY RAIL IT IS NOT TESTING. Where a test
|
||||
# names one mechanism, make that mechanism the binding one (see TCLAMP and TF).
|
||||
#
|
||||
# ⚠️ RUN MUTATIONS WITH `python -B` AND CLEAR app/__pycache__. CPython
|
||||
# invalidates a .pyc on (source mtime in whole seconds, source size), so a
|
||||
# same-second rewrite that also preserves the file size reuses stale bytecode
|
||||
# and the suite reports on code you are no longer running. It under-reported one
|
||||
# mutation here as 2 where the true figure is 6. The error is one-directional -
|
||||
# stale bytecode can only under-report - so every figure above is a lower bound
|
||||
# at worst, and the two zeros ever recorded were both confirmed by fixing them
|
||||
# and watching the count rise, which a caching artefact cannot do.
|
||||
# ⚠️ RUN MUTATIONS THROUGH `tools/mutation_run.sh`, WHICH CLEARS __pycache__
|
||||
# BEFORE IT RUNS ANYTHING. CPython invalidates a .pyc on (source mtime in whole
|
||||
# seconds, source size), so a same-second rewrite that also preserves the file
|
||||
# size reuses stale bytecode and the suite reports on code you are no longer
|
||||
# running. It under-reported one mutation here as 2 where the true figure is 6.
|
||||
#
|
||||
# ⚠️ AND THE CLEAR IS THE HALF THAT WORKS. This note used to lead with
|
||||
# `python -B`; TEST-15 measured what that flag actually does, and it is
|
||||
# write-only - it does not stop an EXISTING stale .pyc being read, and a
|
||||
# mutation run always has one, because the previous run wrote it. -B is still
|
||||
# worth passing, for the NEXT edit rather than this one.
|
||||
#
|
||||
# The error is one-directional - stale bytecode can only under-report - so
|
||||
# every figure above is a lower bound at worst, and the two zeros ever recorded
|
||||
# were both confirmed by fixing them and watching the count rise, which a
|
||||
# caching artefact cannot do.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
print("control law")
|
||||
|
||||
@@ -62,6 +62,13 @@ load the meter's POWER FIGURE never moved - 10130.0 W for 26 consecutive polls -
|
||||
and only the kWh registers kept `unchanged_s` at zero. See the note in
|
||||
freeze.py; it is why the fingerprint's register terms are the negative case
|
||||
rather than a nicety.
|
||||
|
||||
⚠️ MUTATING THE MODULE THIS FILE GRADES? PURGE `__pycache__` FIRST - or run
|
||||
`tools/mutation_run.sh`, which does. `python3 -B` alone does NOT save you: it
|
||||
stops bytecode being WRITTEN, not a stale one being READ, and a size-preserving
|
||||
edit reverted inside one second is invisible to CPython's staleness test. That
|
||||
is TEST-15, and it has already turned one live mutation into a false survivor.
|
||||
Read MUTATION.md before you report a survivor.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
@@ -79,7 +86,8 @@ import aiohttp
|
||||
|
||||
from app.control import Tuning, compute
|
||||
from app.freeze import (
|
||||
RAIL_FRAC, FreezeWatchdog, FreezeWatchdogConfig, looks_frozen, rail_w,
|
||||
RAIL_FRAC, FreezeWatchdog, FreezeWatchdogConfig, looks_frozen,
|
||||
rail_ceiling_w, rail_unreachable, rail_w,
|
||||
)
|
||||
from app.main import Controller
|
||||
from app.p1 import HomeWizardLocalSource, P1Ingest
|
||||
@@ -88,11 +96,17 @@ fails = []
|
||||
T0 = datetime(2026, 8, 26, 7, 0, 0, tzinfo=timezone.utc)
|
||||
HERE = Path(__file__).resolve().parent
|
||||
|
||||
# The live install's numbers, which are the ones the exposure is written at.
|
||||
LIVE_MAX_W = 5000.0
|
||||
# ⚠️ NOT config.yaml's shipped max_w. This is the LIVE INSTALL's own setting -
|
||||
# the schema maximum, 5000 - which this file uses on purpose wherever the
|
||||
# scenario under test is "a device smaller than the configured max_w" (freeze.py
|
||||
# describes exactly this install). Named LIVE_INSTALL_MAX_W, not the shorter
|
||||
# LIVE_MAX_W it used to be called, so it cannot be misread as "the current
|
||||
# shipped default" - see SHIPPED_MAX_W below for that number, and the pin two
|
||||
# sections down for what stops the two from drifting apart unnoticed (TEST-10).
|
||||
LIVE_INSTALL_MAX_W = 5000.0
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# THE SHIPPED THRESHOLD, READ FROM config.yaml (TEST-06 / AC3)
|
||||
# THE SHIPPED DEFAULTS, READ FROM config.yaml (TEST-06 / TEST-10 / AC3)
|
||||
# --------------------------------------------------------------------------- #
|
||||
# ⚠️ `meter_freeze_s: 300` used to appear in this file only as the literal 300,
|
||||
# retyped six times, so `300 -> 3600` in config.yaml left every check here
|
||||
@@ -110,9 +124,18 @@ def _cfg_default(key):
|
||||
return float(found[0]) if len(found) == 1 else None
|
||||
|
||||
|
||||
SHIPPED_HOLD_S = _cfg_default("meter_freeze_s")
|
||||
SHIPPED_DEADBAND_W = _cfg_default("deadband_w")
|
||||
SHIPPED_MAX_W = _cfg_default("max_w")
|
||||
# THE KEYS THIS FILE PINS - one place, so the next key added to config.yaml's
|
||||
# options block can be checked against it rather than discovered unread later
|
||||
# (TEST-10 / AC3). Deliberately not every key: max_w, deadband_w and
|
||||
# meter_freeze_s are the ones this file's arithmetic actually reasons about
|
||||
# (the mutual-exclusion argument in section 2b needs all three together).
|
||||
# Everything else in config.yaml's options block is out of scope here - see
|
||||
# test_validate.py for the general "no default silently drifts" pin, and do
|
||||
# NOT add a maintenance_* key here: CFG-03 is moving that default between
|
||||
# config.yaml, main.py and maintenance.py concurrently with this ticket.
|
||||
PINNED_KEYS = ("meter_freeze_s", "deadband_w", "max_w")
|
||||
SHIPPED_HOLD_S, SHIPPED_DEADBAND_W, SHIPPED_MAX_W = (
|
||||
_cfg_default(key) for key in PINNED_KEYS)
|
||||
|
||||
|
||||
def check(name, cond):
|
||||
@@ -121,7 +144,7 @@ def check(name, cond):
|
||||
fails.append(name)
|
||||
|
||||
|
||||
def tuning(max_w=LIVE_MAX_W):
|
||||
def tuning(max_w=LIVE_INSTALL_MAX_W):
|
||||
"""The shipped defaults from config.yaml, at the live install's max_w."""
|
||||
return Tuning(gain=0.6, max_w=max_w, slew_w=1000, deadband_w=15,
|
||||
target_grid_w=-10, step_w=10, saturation_w=500,
|
||||
@@ -155,6 +178,87 @@ check("no transport signal (unchanged_s None) -> silent, never assumed frozen",
|
||||
check("no command yet -> silent", not looks_frozen(3600, None, 5000, cfg))
|
||||
check("rail_w tracks RAIL_FRAC", rail_w(5000) == 5000 * RAIL_FRAC)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 1c. SAFETY-20 - the rail is measured against what the WIRE can carry
|
||||
# --------------------------------------------------------------------------- #
|
||||
# ⚠️ EVERY CHECK IN THIS SECTION WAS RED BEFORE THE FIX AND IS THE FIX'S ONLY
|
||||
# EVIDENCE. The shipped rail was `RAIL_FRAC * max_w` and the emitted command is
|
||||
# clipped to the SETPOINT DEVICE's range as well (clamp.py's second stage, and
|
||||
# the arbiter's `device` P_SAFETY claim), so any rating at or below
|
||||
# `0.95 * max_w` made term 2 unsatisfiable by construction while the status page
|
||||
# went on printing `armed (... over 4750 W)`.
|
||||
#
|
||||
# THIS IS ALSO THE CHECK THAT HAS TO GO RED IF ANYONE REVERTS THE RAIL TO BARE
|
||||
# `max_w` (AC3). Verified by doing it - reinstating
|
||||
# `return abs(float(max_w)) * RAIL_FRAC` in `rail_w()` fails the six checks
|
||||
# below plus three in part 6, and nothing else in the suite.
|
||||
print("SAFETY-20: the rail against the device rating")
|
||||
|
||||
# The ticket's own numbers: a 5 kW ceiling on a 4.7 kW inverter.
|
||||
DEV = dict(dev_min=-4700.0, dev_max=4700.0)
|
||||
|
||||
check("the rail is the DEVICE's rail, not max_w's, when the device is smaller",
|
||||
rail_w(LIVE_INSTALL_MAX_W, **DEV) == 4700.0 * RAIL_FRAC
|
||||
and rail_w(LIVE_INSTALL_MAX_W, **DEV) != LIVE_INSTALL_MAX_W * RAIL_FRAC)
|
||||
check("a command pinned at the device rating with a meter frozen for an hour "
|
||||
"FIRES - this is the ticket, and it returned False before the fix",
|
||||
looks_frozen(3600, 4700, LIVE_INSTALL_MAX_W, cfg, **DEV))
|
||||
check("...and the identical call without the rating is still False, so the "
|
||||
"check above is measuring the rating and not something else",
|
||||
not looks_frozen(3600, 4700, LIVE_INSTALL_MAX_W, cfg))
|
||||
check("the charge rail moves with it too - the runaway can be either sign",
|
||||
looks_frozen(3600, -4700, LIVE_INSTALL_MAX_W, cfg, **DEV))
|
||||
check("just under the DEVICE rail is still silent, so the fix widened term 2 "
|
||||
"by exactly the rating and not into a bare unchanged_s threshold",
|
||||
not looks_frozen(3600, 4700 * RAIL_FRAC - 1, LIVE_INSTALL_MAX_W, cfg, **DEV))
|
||||
check("a device BIGGER than max_w cannot raise the rail - max_w is still a "
|
||||
"ceiling the operator set and this is a min(), not a swap",
|
||||
rail_w(LIVE_INSTALL_MAX_W, dev_min=-9000.0, dev_max=9000.0)
|
||||
== LIVE_INSTALL_MAX_W * RAIL_FRAC)
|
||||
check("an unread rating (ESPHome not up) leaves the old behaviour exactly - "
|
||||
"no device clamp is applied on that path either, so max_w IS the ceiling",
|
||||
rail_w(LIVE_INSTALL_MAX_W, dev_min=None, dev_max=None) == LIVE_INSTALL_MAX_W * RAIL_FRAC)
|
||||
check("one bound alone still lowers it - hass.limits() reads min and max "
|
||||
"independently and either can come back None on its own",
|
||||
rail_w(LIVE_INSTALL_MAX_W, dev_max=4000.0) == 4000.0 * RAIL_FRAC)
|
||||
check("a non-finite rating is IGNORED, never read as a 0 W ceiling",
|
||||
rail_w(LIVE_INSTALL_MAX_W, dev_min=float("nan"), dev_max=float("inf"))
|
||||
== LIVE_INSTALL_MAX_W * RAIL_FRAC)
|
||||
check("the ceiling helper says what it measured",
|
||||
rail_ceiling_w(LIVE_INSTALL_MAX_W, **DEV) == 4700.0)
|
||||
|
||||
# The degenerate end. A ceiling of 0 W does not disarm term 2, it makes it TRUE
|
||||
# OF EVERY COMMAND - including a parked 0 W one - which decays the conjunction
|
||||
# into the bare `unchanged_s > N` threshold TEL-05 refused for false-tripping at
|
||||
# this controller's own operating point.
|
||||
check("a device that can command nothing makes the rail UNREACHABLE, with a "
|
||||
"reason for the status page",
|
||||
bool(rail_unreachable(LIVE_INSTALL_MAX_W, dev_min=0.0, dev_max=0.0)))
|
||||
check("...and a reachable rail says so with an empty string, or the row above "
|
||||
"would be permanent",
|
||||
rail_unreachable(LIVE_INSTALL_MAX_W, **DEV) == ""
|
||||
and rail_unreachable(LIVE_INSTALL_MAX_W) == "")
|
||||
check("...and the predicate is SILENT there rather than degenerately true - "
|
||||
"0 W would otherwise satisfy `abs(command) >= 0`",
|
||||
not looks_frozen(3600, 0.0, LIVE_INSTALL_MAX_W, cfg, dev_min=0.0, dev_max=0.0)
|
||||
and not looks_frozen(3600, 5000, LIVE_INSTALL_MAX_W, cfg, dev_min=0.0,
|
||||
dev_max=0.0))
|
||||
|
||||
# The alarm text is the third surface that carried the untrue number - it
|
||||
# outlives the page, in the log and in the HA notification.
|
||||
_wd20 = FreezeWatchdog(cfg)
|
||||
_wd20.evaluate(3600, 4700, LIVE_INSTALL_MAX_W, T0, **DEV)
|
||||
print(f" at max_w {LIVE_INSTALL_MAX_W:.0f} on a +-4700 W device: "
|
||||
f"{_wd20.reason}")
|
||||
check("the alarm reason quotes the rail it actually used and NOT the max_w one "
|
||||
"the command could never have reached",
|
||||
f"command over {4700 * RAIL_FRAC:.0f} W" in _wd20.reason
|
||||
and f"{LIVE_INSTALL_MAX_W * RAIL_FRAC:.0f} W" not in _wd20.reason)
|
||||
check("...and it says the device is what capped it, so the operator is not "
|
||||
"left wondering why the guard is armed somewhere other than max_w",
|
||||
"rating" in _wd20.reason and "max_w" in _wd20.reason)
|
||||
|
||||
print("the edge")
|
||||
wd = FreezeWatchdog(cfg)
|
||||
edges = [wd.evaluate(u, c, 5000, T0 + timedelta(seconds=i))
|
||||
@@ -188,6 +292,18 @@ check("the code default and the shipped default are the same number - "
|
||||
check("this file's `tuning()` really is config.yaml's deadband, so the "
|
||||
"mutual-exclusion arithmetic below is about the shipped law",
|
||||
tuning().deadband_w == SHIPPED_DEADBAND_W)
|
||||
# TEST-10: max_w had no such pin - `max_w: 2000 -> 4500` in config.yaml left
|
||||
# every check in this file green, the same gap TEST-06 closed for
|
||||
# meter_freeze_s one key over. `Tuning`'s own bare default (control.py) is
|
||||
# 2000.0 because that IS the shipped default; comparing the two means a
|
||||
# config.yaml edit that is not matched in control.py goes red here, the same
|
||||
# way FreezeWatchdogConfig().hold_s catches a drifted meter_freeze_s above.
|
||||
# This is deliberately NOT a check against LIVE_INSTALL_MAX_W (5000) - that
|
||||
# constant is the live install's own override and is supposed to differ from
|
||||
# the shipped default; see its definition for why.
|
||||
check("the code default and the shipped default agree on max_w too - "
|
||||
"Tuning() is a default, config.yaml is the ship",
|
||||
Tuning().max_w == SHIPPED_MAX_W)
|
||||
|
||||
# The upper bound is money: config.yaml's own comment says 300 s is "still
|
||||
# inside the 900 s quarter that bills the capacity tariff". A hold that outlives
|
||||
@@ -246,7 +362,7 @@ def replay(hold_s, max_w, cycle_floor_s=15.0):
|
||||
return wd, peak_cmd, peak_unchanged, fired_at
|
||||
|
||||
|
||||
for mw in (2000.0, LIVE_MAX_W):
|
||||
for mw in (SHIPPED_MAX_W, LIVE_INSTALL_MAX_W):
|
||||
wd_r, peak_cmd, peak_unchanged, fired = replay(SHIPPED_HOLD_S, mw)
|
||||
print(f" max_w {mw:.0f}: worst |command| {peak_cmd:.0f} W (rail "
|
||||
f"{rail_w(mw):.0f} W), worst unchanged {peak_unchanged:.1f} s "
|
||||
@@ -258,7 +374,7 @@ for mw in (2000.0, LIVE_MAX_W):
|
||||
# The margin on the OTHER term, as numbers rather than as trust. Both figures
|
||||
# are quoted in config.yaml and freeze.py, so they are re-measured every run and
|
||||
# a capture swapped underneath them cannot leave the prose saying the old thing.
|
||||
_, _, worst_unchanged, _ = replay(SHIPPED_HOLD_S, LIVE_MAX_W)
|
||||
_, _, worst_unchanged, _ = replay(SHIPPED_HOLD_S, LIVE_INSTALL_MAX_W)
|
||||
gaps, last, prev = [], rows[0]["t"], None
|
||||
for r in rows:
|
||||
if prev is None or r["pwr"] != prev:
|
||||
@@ -292,7 +408,7 @@ check(f"the shipped {SHIPPED_HOLD_S:.0f} s is at least 15x the worst of the two"
|
||||
# that happens not to move.
|
||||
print("TEL-05's low-power case - a converged meter that legitimately repeats")
|
||||
tel05 = FreezeWatchdog(FreezeWatchdogConfig(hold_s=SHIPPED_HOLD_S))
|
||||
t5 = tuning(LIVE_MAX_W)
|
||||
t5 = tuning(LIVE_INSTALL_MAX_W)
|
||||
tgt, iw, sc = 0.0, 0.0, 0
|
||||
bare_would_fire = False
|
||||
tel05_cmd = 0.0
|
||||
@@ -308,7 +424,7 @@ for k in range(TEL05_S):
|
||||
tel05_cmd = max(tel05_cmd, abs(tgt))
|
||||
# The REJECTED design, written out so the case can be shown to be real.
|
||||
bare_would_fire = bare_would_fire or float(k) >= SHIPPED_HOLD_S
|
||||
tel05.evaluate(float(k), tgt, LIVE_MAX_W, T0 + timedelta(seconds=k))
|
||||
tel05.evaluate(float(k), tgt, LIVE_INSTALL_MAX_W, T0 + timedelta(seconds=k))
|
||||
print(f" {TEL05_S / 60:.0f} min at -14.2 W: worst |command| {tel05_cmd:.0f} W, "
|
||||
f"unchanged_s reaches {TEL05_S - 1} s, episodes {tel05.episodes}")
|
||||
check("the bare unchanged_s threshold TEL-05 rejected WOULD fire here",
|
||||
@@ -316,7 +432,7 @@ check("the bare unchanged_s threshold TEL-05 rejected WOULD fire here",
|
||||
check("the conjunction does not - this is what the rail term buys",
|
||||
tel05.episodes == 0)
|
||||
check("...and the command stayed nowhere near the rail",
|
||||
tel05_cmd < rail_w(LIVE_MAX_W))
|
||||
tel05_cmd < rail_w(LIVE_INSTALL_MAX_W))
|
||||
|
||||
# The structural version of the same point, re-derived rather than asserted in
|
||||
# prose: the slowest register a HEALTHY meter can have while still being seen as
|
||||
@@ -332,7 +448,7 @@ print(f" at the shipped {SHIPPED_HOLD_S:.0f} s hold, the slowest healthy "
|
||||
check("a healthy meter slow enough to look unchanged is inside the deadband",
|
||||
slowest_healthy_w < DEADBAND_W)
|
||||
_park = compute(prev_w=0.0, grid_w=-slowest_healthy_w, actual_w=0.0,
|
||||
tuning=tuning(LIVE_MAX_W), sat_count=0, i_w=0.0)
|
||||
tuning=tuning(LIVE_INSTALL_MAX_W), sat_count=0, i_w=0.0)
|
||||
check("...and the shipped law really does park the command there",
|
||||
_park.target_w == 0.0)
|
||||
|
||||
@@ -411,7 +527,7 @@ while True:
|
||||
'''
|
||||
|
||||
|
||||
async def live_run(port, mode, hold_s=10.0, seconds=16.0, max_w=LIVE_MAX_W):
|
||||
async def live_run(port, mode, hold_s=10.0, seconds=16.0, max_w=LIVE_INSTALL_MAX_W):
|
||||
"""Poll a real HTTP meter through the real transport and drive the detector."""
|
||||
ingest = P1Ingest(phases=1, max_age_s=30)
|
||||
wd = FreezeWatchdog(FreezeWatchdogConfig(hold_s=hold_s))
|
||||
@@ -494,7 +610,7 @@ fired2, polls2, unch2, cmd2 = with_server(
|
||||
print(f" moving: {polls2} polls, worst unchanged {unch2:.1f} s, "
|
||||
f"worst |command| {cmd2:.0f} W, alarm at "
|
||||
f"{'never' if fired2 is None else f'{fired2:.1f} s'}")
|
||||
check("the moving meter also drove the command to the rail", cmd2 >= rail_w(LIVE_MAX_W))
|
||||
check("the moving meter also drove the command to the rail", cmd2 >= rail_w(LIVE_INSTALL_MAX_W))
|
||||
check("a REAL railed condition against a live meter stays silent", fired2 is None)
|
||||
check("...because the meter kept moving", unch2 < 10.0)
|
||||
|
||||
@@ -582,7 +698,7 @@ STALE_INPUT_S = 15.0
|
||||
def _opts(**over):
|
||||
o = {"setpoint_entity": "number.sp", "meter_entity": "sensor.grid",
|
||||
"soc_entity": "sensor.soc", "batt_entity": "sensor.batt",
|
||||
"meter_source": "off", "max_w": LIVE_MAX_W, "gain": 0.6,
|
||||
"meter_source": "off", "max_w": LIVE_INSTALL_MAX_W, "gain": 0.6,
|
||||
"slew_w": 1000, "deadband_w": SHIPPED_DEADBAND_W,
|
||||
"target_grid_w": -10, "step_w": 10, "heartbeat_s": 10,
|
||||
"stale_input_s": STALE_INPUT_S}
|
||||
@@ -649,19 +765,24 @@ def notes_by_text_of(hass):
|
||||
if "frozen" in str(d.get("title", "")).lower()]
|
||||
|
||||
|
||||
def wired(unchanged_s, grid, cycles=60, **over):
|
||||
def wired(unchanged_s, grid, cycles=60, dev=(-5000.0, 5000.0), **over):
|
||||
"""Returns (hass, controller, trace).
|
||||
|
||||
`trace` is one row per cycle - (command after the cycle, the watchdog's
|
||||
level, notifications raised so far) - which is what AC1 needs: the
|
||||
QUESTION IS NOT WHETHER THE ALARM HAPPENS BUT ON WHICH CYCLE.
|
||||
|
||||
⚠️ `dev` IS THE SETPOINT DEVICE'S OWN REPORTED RANGE, and it is a parameter
|
||||
rather than a constant because SAFETY-20 is entirely about installs where it
|
||||
is NOT the default +-5000. It defaults to the live install's rating, which
|
||||
equals its `max_w` - which is exactly why that install never saw the defect.
|
||||
"""
|
||||
async def go():
|
||||
hass = _Hass(grid)
|
||||
c = Controller(_opts(**over), hass, _Store(), _Pub(),
|
||||
stop=asyncio.Event())
|
||||
c.auto = True
|
||||
c.dev_min, c.dev_max = -5000.0, 5000.0
|
||||
c.dev_min, c.dev_max = dev
|
||||
c.p1_source = _Source(unchanged_s)
|
||||
trace = []
|
||||
for _ in range(cycles):
|
||||
@@ -717,7 +838,7 @@ check("the event log names it", any("METER FROZEN" in e for e in ctl_f.events))
|
||||
# ⚠️ NOTIFY, NOT TRIP. If a later cut turns this into a trip it must come here
|
||||
# and change this expectation deliberately, not discover it in the field.
|
||||
check("and it does NOT command 0 W - this cut is an alarm only",
|
||||
abs(ctl_f.target) >= rail_w(LIVE_MAX_W))
|
||||
abs(ctl_f.target) >= rail_w(LIVE_INSTALL_MAX_W))
|
||||
|
||||
# ⚠️ THE THREE SCENARIOS THAT SAFETY-03 FORCED A DECISION ON, decided one at a
|
||||
# time and not reflexively narrowed to green. Measured on the merged tree:
|
||||
@@ -754,7 +875,7 @@ print(f" real 8 kW load, moving meter: surface "
|
||||
f"freeze {len(notes_of(hass_m))}")
|
||||
check("wired up, a real railed load against a moving meter raises nothing FROM "
|
||||
"THIS GUARD (the clamp alarm there is SAFETY-03's and is correct)",
|
||||
not notes_of(hass_m) and abs(ctl_m.target) >= rail_w(LIVE_MAX_W))
|
||||
not notes_of(hass_m) and abs(ctl_m.target) >= rail_w(LIVE_INSTALL_MAX_W))
|
||||
|
||||
hass_u = wired(None, 4000.0)[0]
|
||||
print(f" uncovered transport: surface "
|
||||
@@ -808,7 +929,7 @@ check("an uncovered transport (no unchanged_s) raises nothing FROM THIS GUARD, "
|
||||
print("WHERE the detector is evaluated in cycle() - the ordering AC1 protects")
|
||||
|
||||
_railed = [i for i, (t, _, _) in enumerate(trace_f)
|
||||
if abs(t) >= rail_w(LIVE_MAX_W)]
|
||||
if abs(t) >= rail_w(LIVE_INSTALL_MAX_W)]
|
||||
_alarmed = [i for i, (_, _, n) in enumerate(trace_f) if n >= 1]
|
||||
_first_railed = _railed[0] if _railed else None
|
||||
_first_alarm = _alarmed[0] if _alarmed else None
|
||||
@@ -878,7 +999,7 @@ print(f" poll task killed: alarming at {_before[0]:+.0f} W "
|
||||
for i, (t, a, n) in enumerate(_dead)))
|
||||
check("the episode really was standing before the poll task died - otherwise "
|
||||
"the release below is vacuous",
|
||||
_before[1] and _before[2] == 1 and abs(_before[0]) >= rail_w(LIVE_MAX_W))
|
||||
_before[1] and _before[2] == 1 and abs(_before[0]) >= rail_w(LIVE_INSTALL_MAX_W))
|
||||
check("a dead poll task drives the command to 0 W",
|
||||
bool(_zeroed) and _zeroed[0] == 0)
|
||||
check("...and on THAT SAME cycle the alarm is already clear, because the "
|
||||
@@ -903,7 +1024,7 @@ check("...and it stays clear for as long as the failsafe holds it there",
|
||||
# loop re-rails, and that is a new episode which MUST speak. What must not
|
||||
# happen is a second notification stacking up beside the first.
|
||||
_re_railed = [i for i, (t, _, _) in enumerate(_revived)
|
||||
if abs(t) >= rail_w(LIVE_MAX_W)]
|
||||
if abs(t) >= rail_w(LIVE_INSTALL_MAX_W)]
|
||||
print(f" transport revived: command re-rails on cycle "
|
||||
f"{_re_railed[0] if _re_railed else None}, "
|
||||
f"{_ctl_d.freeze_wd.episodes} episode(s), {len(_freeze_notes)} "
|
||||
@@ -990,10 +1111,131 @@ check("...and it quotes the hold and the rail it is armed at, derived from the "
|
||||
"config the controller was actually built with",
|
||||
bool(_rows_c)
|
||||
and f"{_ctl_c.freeze_wd.cfg.hold_s:.0f} s unchanged" in _rows_c[0]["text"]
|
||||
and f"{rail_w(LIVE_MAX_W):.0f} W" in _rows_c[0]["text"])
|
||||
and f"{rail_w(LIVE_INSTALL_MAX_W):.0f} W" in _rows_c[0]["text"])
|
||||
check("...as an ok row, since a covered armed guard is not a warning",
|
||||
bool(_rows_c) and _rows_c[0]["ok"] and not _rows_c[0]["warn"])
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 5b. SAFETY-20 - is the device range actually WIRED into the guard? (AC1)
|
||||
# --------------------------------------------------------------------------- #
|
||||
# ⚠️ THIS SECTION EXISTS BECAUSE THE FIX SURVIVED ITS OWN MUTATION TEST WITHOUT
|
||||
# IT. Deleting `dev_min=`/`dev_max=` from `check_meter_frozen()`'s call - i.e.
|
||||
# shipping the corrected predicate and then not telling it the rating - left
|
||||
# every check in 1c and 6b green, because those grade `freeze.py` and the status
|
||||
# string and neither of them goes through `cycle()`. A guard that is right in the
|
||||
# module and unwired in the caller is the defect with an extra step.
|
||||
#
|
||||
# So this drives the REAL `Controller.cycle()` on a controller configured the way
|
||||
# the ticket describes - `max_w: 5000` on a +-4700 W inverter - and asserts on
|
||||
# the notification that leaves the process.
|
||||
#
|
||||
# ⚠️ WHAT IT STILL DOES NOT COVER, stated rather than implied: the OTHER call
|
||||
# site, `looks_frozen(...)` inside the SAFETY-07 peak-guard block, is behind
|
||||
# `if self.p1_enabled` and needs a fed averager to have any observable
|
||||
# consequence (`blindness()` returns BLIND_NO_BLOCK before it ever reads
|
||||
# `frozen`). That gate is uncovered here for the same reason freeze_rows() says
|
||||
# it is uncovered there, and widening the fixture belongs to whoever covers it.
|
||||
print("SAFETY-20: the device range through the REAL cycle()")
|
||||
|
||||
_h20, _c20, _t20 = wired(3600.0, 4000.0, dev=(-4700.0, 4700.0))
|
||||
_n20 = notes_of(_h20)
|
||||
print(f" max_w 5000 on a +-4700 W device, meter frozen an hour: the command "
|
||||
f"stood at {_c20.target:+.0f} W, {len(_n20)} freeze notification(s), "
|
||||
f"watchdog active={_c20.freeze_wd.active}")
|
||||
check("PRECONDITION: the device rating - not max_w - is what stopped the "
|
||||
"command, so this really is the configuration the ticket is about",
|
||||
abs(_c20.target) == 4700.0)
|
||||
check("...and that command is BELOW the max_w rail, which is why the shipped "
|
||||
"guard could never fire on this install",
|
||||
abs(_c20.target) < rail_w(LIVE_INSTALL_MAX_W))
|
||||
check("...and at or above the device rail, which is why it must",
|
||||
abs(_c20.target) >= rail_w(LIVE_INSTALL_MAX_W, dev_min=-4700.0, dev_max=4700.0))
|
||||
check("THE ALARM FIRES through the real cycle() - the rating reaches the "
|
||||
"predicate from the controller, not just from a unit call",
|
||||
len(_n20) == 1 and _c20.freeze_wd.active)
|
||||
check("...and the notification the operator gets quotes the capped rail, "
|
||||
"not the max_w one",
|
||||
bool(_n20)
|
||||
and f"{rail_w(LIVE_INSTALL_MAX_W, dev_min=-4700.0, dev_max=4700.0):.0f} W"
|
||||
in str(_n20[0].get("message", "")))
|
||||
# p1_enabled is what a homewizard_local install has - set by hand here for the
|
||||
# same reason part 4 sets it, see freeze_rows().
|
||||
_c20.p1_enabled = True
|
||||
check("...and the red status row is up too, so the page and the notification "
|
||||
"agree",
|
||||
any("METER MAY BE FROZEN" in r["text"] for r in _c20.checks()))
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 6b. SAFETY-20 - what the page says when the DEVICE is the ceiling (AC2)
|
||||
# --------------------------------------------------------------------------- #
|
||||
# ⚠️ THIS IS THE ACCEPTANCE CRITERION READ OFF THE RENDERED PAGE, NOT OFF THE
|
||||
# SOURCE. The card is explicit that reading the code does not settle it, so
|
||||
# every assertion below goes through the real `Controller.checks()` on a
|
||||
# controller that was CONFIGURED with a device smaller than its `max_w` and
|
||||
# then run - three real cycles, the real arbiter, the real write path.
|
||||
print("what the page says when the device rating is the smaller ceiling")
|
||||
|
||||
# max_w 5000 on a 4700 W inverter - the ticket's own install. Covered transport,
|
||||
# so the only question is what the ARMED row says.
|
||||
_ctl_s, _rows_s = freeze_rows(2.0, -14.2, dev=(-4700.0, 4700.0))
|
||||
# And the degenerate end: a device that can command nothing at all.
|
||||
_ctl_z, _rows_z = freeze_rows(2.0, -14.2, dev=(0.0, 0.0))
|
||||
print(f" max_w 5000 on a +-4700 W device: {_rows_s[0]['text'] if _rows_s else '(no row)'}")
|
||||
print(f" a device with no commandable range: {_rows_z[0]['text'] if _rows_z else '(no row)'}")
|
||||
|
||||
check("a device smaller than max_w still gets exactly one freeze-detector row",
|
||||
len(_rows_s) == 1)
|
||||
check("...and the page does NOT print the max_w rail the command can never "
|
||||
"reach - THE DEFECT, in one assertion",
|
||||
bool(_rows_s)
|
||||
and f"{rail_w(LIVE_INSTALL_MAX_W):.0f} W" not in _rows_s[0]["text"])
|
||||
check("...it prints the rail the predicate actually uses",
|
||||
bool(_rows_s)
|
||||
and f"{rail_w(LIVE_INSTALL_MAX_W, dev_min=-4700.0, dev_max=4700.0):.0f} W"
|
||||
in _rows_s[0]["text"])
|
||||
check("...and it names the device range as the reason, since the operator "
|
||||
"configured max_w and is owed the reason the guard is armed elsewhere",
|
||||
bool(_rows_s) and "4700" in _rows_s[0]["text"]
|
||||
and "max_w" in _rows_s[0]["text"])
|
||||
|
||||
# ⚠️ THE NUMBER IS TAKEN OFF THE ROW AND FED BACK INTO THE SHIPPED PREDICATE.
|
||||
# Asserting the page against `rail_w(...)` alone proves the two agree, which a
|
||||
# revert of BOTH to bare max_w also satisfies. What a revert cannot satisfy is
|
||||
# this: the rail the page advertises has to be a magnitude the wire can carry,
|
||||
# and the wire stops at the device rating.
|
||||
_m = re.search(r"command is over (\d+(?:\.\d+)?) W", _rows_s[0]["text"]) if _rows_s else None
|
||||
_page_rail = float(_m.group(1)) if _m else None
|
||||
print(f" the page advertises a rail of {_page_rail} W against a device that "
|
||||
f"stops at {_ctl_s.dev_max:.0f} W")
|
||||
check("...the row states a rail in watts at all, so the parse below means "
|
||||
"something", _page_rail is not None)
|
||||
check("...and THE RAIL THE PAGE ADVERTISES IS ONE THE WIRE CAN ACTUALLY CARRY. "
|
||||
"This is the whole ticket: 4750 W on a device that stops at 4700 W is a "
|
||||
"guard that cannot fire, advertising that it can",
|
||||
_page_rail is not None and _page_rail <= abs(_ctl_s.dev_max))
|
||||
check("...and a command at exactly that advertised rail, with the meter frozen, "
|
||||
"really does trip the shipped predicate the row is describing",
|
||||
_page_rail is not None
|
||||
and looks_frozen(3600, _page_rail, LIVE_INSTALL_MAX_W, cfg,
|
||||
dev_min=_ctl_s.dev_min, dev_max=_ctl_s.dev_max))
|
||||
check("...as an ok row - a guard armed at a lower rail is still armed, not a "
|
||||
"warning", bool(_rows_s) and _rows_s[0]["ok"] and not _rows_s[0]["warn"])
|
||||
|
||||
check("a device with no commandable range gets exactly one row", len(_rows_z) == 1)
|
||||
check("...and it says NOT COVERED - the rail is not merely low there, it is "
|
||||
"0 W, which would be TRUE of every command including a parked one",
|
||||
bool(_rows_z) and "NOT COVERED" in _rows_z[0]["text"])
|
||||
check("...and it NEVER says armed",
|
||||
bool(_rows_z) and "armed" not in _rows_z[0]["text"])
|
||||
check("...flagged as a warning rather than a silent ok, like the uncovered "
|
||||
"transport row it shares",
|
||||
bool(_rows_z) and not _rows_z[0]["ok"] and _rows_z[0]["warn"])
|
||||
check("...and the predicate agrees with the page rather than firing behind it",
|
||||
not looks_frozen(3600, 0.0, LIVE_INSTALL_MAX_W, cfg,
|
||||
dev_min=_ctl_z.dev_min, dev_max=_ctl_z.dev_max))
|
||||
|
||||
|
||||
# AC3's other half, through the built object rather than through a literal: the
|
||||
# opts dict does NOT carry meter_freeze_s, so this is the number an install that
|
||||
# leaves the key at its config.yaml default actually lands on.
|
||||
|
||||
@@ -19,6 +19,13 @@ HANDOVER.md. An understated runtime reads as a hang.
|
||||
`cycle_floor_s` is read from options with no lower bound in code, so a huge
|
||||
value reproduces the pre-fix behaviour exactly. Every claim below is therefore
|
||||
an A/B on one binary, not a comparison against a remembered old one.
|
||||
|
||||
⚠️ MUTATING THE MODULE THIS FILE GRADES? PURGE `__pycache__` FIRST - or run
|
||||
`tools/mutation_run.sh`, which does. `python3 -B` alone does NOT save you: it
|
||||
stops bytecode being WRITTEN, not a stale one being READ, and a size-preserving
|
||||
edit reverted inside one second is invisible to CPython's staleness test. That
|
||||
is TEST-15, and it has already turned one live mutation into a false survivor.
|
||||
Read MUTATION.md before you report a survivor.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
|
||||
@@ -3,12 +3,24 @@
|
||||
Walks a whole cycle in simulated time, which is the test the YAML version never
|
||||
had - and it is exactly the phase transitions that a real cycle takes ten hours
|
||||
to exercise once a month.
|
||||
|
||||
⚠️ MUTATING THE MODULE THIS FILE GRADES? PURGE `__pycache__` FIRST - or run
|
||||
`tools/mutation_run.sh`, which does. `python3 -B` alone does NOT save you: it
|
||||
stops bytecode being WRITTEN, not a stale one being READ, and a size-preserving
|
||||
edit reverted inside one second is invisible to CPython's staleness test. That
|
||||
is TEST-15, and it has already turned one live mutation into a false survivor.
|
||||
Read MUTATION.md before you report a survivor.
|
||||
"""
|
||||
|
||||
import dataclasses
|
||||
import re
|
||||
import sys
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
|
||||
from app.maintenance import CHARGE, DRAIN, HOLD, IDLE, MaintConfig, Maintenance
|
||||
from app.maintenance import (
|
||||
CHARGE, DRAIN, HOLD, IDLE, MAINT_OPTION_DEFAULTS, MaintConfig, Maintenance,
|
||||
)
|
||||
|
||||
fails = []
|
||||
|
||||
@@ -104,6 +116,114 @@ print("disabled schedule")
|
||||
m = Maintenance(MaintConfig(enabled=False), FakeStore())
|
||||
check("disabled never starts", m.tick(t0, soc=80).phase == IDLE)
|
||||
|
||||
print("CFG-03: config.yaml is the source, this module is the only mirror")
|
||||
# ⚠️ WHY THIS IS PINNED BY READING THE FILE. Before CFG-03 each maintenance
|
||||
# default was written down three times - config.yaml's `options:` block,
|
||||
# `opts.get(key, <literal>)` in main.py, and MaintConfig's dataclass defaults -
|
||||
# and MAINT-04 proved they had already drifted (2000 shipped, 2500 in code). The
|
||||
# fix is one source and one mirror; the mirror is only worth anything if drift
|
||||
# from it is a CI failure rather than a comment, and a transcription of
|
||||
# config.yaml into this file would just be a fourth place to disagree. So the
|
||||
# shipped values are READ out of the file the Supervisor reads.
|
||||
#
|
||||
# Regex rather than PyYAML on purpose, for test_validate.py's reason: the add-on
|
||||
# image installs py3-aiohttp and py3-paho-mqtt only, and a check that skips on
|
||||
# ImportError is not a check.
|
||||
HERE = Path(__file__).resolve().parent
|
||||
_CFG_TEXT = (HERE / "config.yaml").read_text(encoding="utf-8")
|
||||
_SCHEMA_AT = _CFG_TEXT.index("\nschema:")
|
||||
|
||||
|
||||
def shipped_default(key):
|
||||
"""The value under `options:` - the FIRST match, before `schema:`."""
|
||||
m = re.search(rf"^ {key}: *(.+?) *$", _CFG_TEXT[:_SCHEMA_AT], re.M)
|
||||
return None if m is None else m.group(1)
|
||||
|
||||
|
||||
def schema_range(key):
|
||||
"""`int(lo,hi)` under `schema:` -> (lo, hi); None if the key is absent."""
|
||||
m = re.search(rf"^ {key}: *\w+\((-?[\d.]+),(-?[\d.]+)\) *$",
|
||||
_CFG_TEXT[_SCHEMA_AT:], re.M)
|
||||
return None if m is None else (float(m.group(1)), float(m.group(2)))
|
||||
|
||||
|
||||
def as_number(text):
|
||||
if text in ("true", "false"):
|
||||
return 1.0 if text == "true" else 0.0
|
||||
return float(text)
|
||||
|
||||
|
||||
_ship = {k: shipped_default(k) for k in MAINT_OPTION_DEFAULTS}
|
||||
print(f" config.yaml ships {_ship}")
|
||||
check("every mirrored key is actually shipped in config.yaml's options: block",
|
||||
all(v is not None for v in _ship.values()))
|
||||
check("...and MAINT_OPTION_DEFAULTS reproduces each one exactly, so the mirror "
|
||||
"is a copy of the source and not an opinion about it",
|
||||
all(str(MAINT_OPTION_DEFAULTS[k]).lower() == _ship[k]
|
||||
for k in MAINT_OPTION_DEFAULTS))
|
||||
# ⚠️ THE OTHER DIRECTION MATTERS TOO. Equality alone would still pass if the
|
||||
# mirror quietly stopped covering a key someone added to config.yaml, and the
|
||||
# key nobody mirrors is exactly the key that gets a literal typed for it.
|
||||
_shipped_keys = set(re.findall(r"^ (maintenance_[a-z_]+):", _CFG_TEXT[:_SCHEMA_AT],
|
||||
re.M))
|
||||
check(f"...and it covers EVERY maintenance_* option the file ships, so a ninth "
|
||||
f"key cannot arrive unmirrored {sorted(_shipped_keys)}",
|
||||
_shipped_keys == set(MAINT_OPTION_DEFAULTS))
|
||||
|
||||
# ⚠️ WHERE THE RANGE LIVES, ASSERTED RATHER THAN COMMENTED. The PM proofread on
|
||||
# this card named a FOURTH declaration site of a different kind:
|
||||
# `maintenance_charge_w: int(500,5000)` in the schema block. It is a BOUND, not
|
||||
# a default, and the decision this card records is that bounds live in the
|
||||
# schema block ONLY - the Supervisor enforces them and reads only that file, so
|
||||
# a Python copy would be a place to disagree and nothing else. What that
|
||||
# decision needs from a check is (a) every mirrored key really does have a
|
||||
# schema entry, or the Supervisor drops the option and the add-on silently runs
|
||||
# on the mirror instead of the operator's value, and (b) the shipped default
|
||||
# lies INSIDE its own range, because a default the schema rejects is a config
|
||||
# that cannot be re-entered once it is edited.
|
||||
_ranged = {k: schema_range(k) for k in MAINT_OPTION_DEFAULTS}
|
||||
check("every mirrored key is in the schema: block too - `bool` has no range, so "
|
||||
"it is the one exception and it is named",
|
||||
all(v is not None for k, v in _ranged.items()
|
||||
if k != "maintenance_enabled")
|
||||
and _ranged["maintenance_enabled"] is None)
|
||||
_outside = {k: (as_number(_ship[k]), rng) for k, rng in _ranged.items()
|
||||
if rng is not None and not rng[0] <= as_number(_ship[k]) <= rng[1]}
|
||||
check(f"...and every shipped default sits inside its own schema range, so the "
|
||||
f"Supervisor accepts the file it ships with {_outside or 'all inside'}",
|
||||
not _outside)
|
||||
|
||||
# ⚠️ AND THE CONSUMERS MOVE WITH IT - checked as a RELATION, not against
|
||||
# numbers. AC4 asks for the replacement to be broken and every consumer observed
|
||||
# moving together. A number typed here would pass whether or not the derivation
|
||||
# survived; `dataclasses.fields()` reads what the class actually defaulted to,
|
||||
# so this can only pass while the class is still indexing the mirror.
|
||||
_fields = {f.name: f.default for f in dataclasses.fields(MaintConfig)}
|
||||
check(f"MaintConfig's field names are the option names minus the prefix, so a "
|
||||
f"new field cannot miss the mirror by being spelt differently {sorted(_fields)}",
|
||||
{f"maintenance_{n}" for n in _fields} == set(MAINT_OPTION_DEFAULTS))
|
||||
check("...and every dataclass default IS the mirror's value - no literal "
|
||||
"survives in the class that used to hold the third opinion",
|
||||
all(float(d) == float(MAINT_OPTION_DEFAULTS[f"maintenance_{n}"])
|
||||
for n, d in _fields.items()))
|
||||
# from_options() is the only reader, so it is the only thing that can put a
|
||||
# different number in front of main.py.
|
||||
_from_empty = MaintConfig.from_options({})
|
||||
check("...and from_options({}) - the sim/inject.py and test-suite path, the one "
|
||||
"the Supervisor never takes and the only one the divergence was reachable "
|
||||
"from - equals MaintConfig() exactly",
|
||||
_from_empty == MaintConfig())
|
||||
check("...while a supplied value still wins, or the mirror would be a ceiling "
|
||||
"rather than a default",
|
||||
MaintConfig.from_options({"maintenance_charge_w": 1234}).charge_w == 1234.0)
|
||||
# ⚠️ `key in opts`, not truthiness: `false` and `0` are values an operator can
|
||||
# set, and a truthy read would silently replace both with the default - this
|
||||
# card's own bug in a different costume.
|
||||
check("...and an explicit falsey value is honoured rather than defaulted away",
|
||||
MaintConfig.from_options({"maintenance_start_hour": 0}).start_hour == 0
|
||||
and MaintConfig.from_options({"maintenance_enabled": False}).enabled is False)
|
||||
|
||||
print()
|
||||
print()
|
||||
if fails:
|
||||
print(f"{len(fails)} FAILED: {', '.join(fails)}")
|
||||
|
||||
@@ -8,6 +8,13 @@ Every assert here is a rule whose absence poisons something downstream: an
|
||||
inverted sign inverts the control loop, a fabricated zero hides a dead meter, a
|
||||
naive per-phase sum misbills the capacity tariff, and a plain mean of samples
|
||||
computes the wrong quarter-hour figure whenever the telegram cadence changes.
|
||||
|
||||
⚠️ MUTATING THE MODULE THIS FILE GRADES? PURGE `__pycache__` FIRST - or run
|
||||
`tools/mutation_run.sh`, which does. `python3 -B` alone does NOT save you: it
|
||||
stops bytecode being WRITTEN, not a stale one being READ, and a size-preserving
|
||||
edit reverted inside one second is invisible to CPython's staleness test. That
|
||||
is TEST-15, and it has already turned one live mutation into a false survivor.
|
||||
Read MUTATION.md before you report a survivor.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
python3 test_peakguard.py
|
||||
|
||||
Ten parts. What each is for, and - where it matters - what it is deliberately
|
||||
Eleven parts. What each is for, and - where it matters - what it is deliberately
|
||||
NOT allowed to be tested at:
|
||||
|
||||
1. THE CONTROL LAW, `excess_w`, graded AWAY from the two points where it is
|
||||
@@ -46,7 +46,25 @@ NOT allowed to be tested at:
|
||||
capture, against a MODELLED PACK small enough that the guard's own 878 Wh
|
||||
day would take it to the BMS cut-out - so the two worlds, before and after
|
||||
this card, are run against each other rather than reasoned about.
|
||||
10. MUTATION. Eleven one-line defeats of these two guards, each run against
|
||||
10. SAFETY-25: THE LOOP, WHICH THIS FLOOR DOES NOT BOUND. A TRIPWIRE, not a
|
||||
guarantee - it records a defect and goes red when the defect is fixed.
|
||||
Part 11's mutation 13 has said in words since SAFETY-24 that ordinary
|
||||
self-consumption can take the pack past `peak_soc_floor`; this part
|
||||
replays a sustained-load evening through the SHIPPED control law, the
|
||||
SHIPPED guard and the REAL arbiter and measures how far past. It also
|
||||
sweeps `peak_soc_floor` over the whole schema range to show the answer
|
||||
does not move by one part in ten thousand, and pins the four
|
||||
operator-facing surfaces that now say so.
|
||||
⚠️ THE REPLAY ALONE IS NOT THE TRIPWIRE, and believing it was is the
|
||||
defect PR #31's reviewer found: `replay_loop()` hand-builds main.py's
|
||||
claim list, so it is blind to any claim main.py ADDS - which is where a
|
||||
loop-side floor would be built. 10f is what closes that. It pins the set
|
||||
of claim sources `Controller.cycle()` can file, statically over its AST
|
||||
and dynamically through real cycles swept over the whole SoC range, so a
|
||||
ninth source takes this part red. A floor built inside `control.compute()`
|
||||
or the guard instead moves 10a-10c's numbers directly, because the replay
|
||||
drives both.
|
||||
11. MUTATION. Eleven one-line defeats of these two guards, each run against
|
||||
the checks above to show they are not vacuous.
|
||||
|
||||
------------------------------------------------------------------------------
|
||||
@@ -72,6 +90,13 @@ Two days is also not thirty. AC 3's 95 %-over-30-days criterion is TARIFF-01's
|
||||
and is still not met; `test_tariff.py`'s part 9 says so at length and this file
|
||||
does not re-litigate it. What part 6 reports is the comparison that two days CAN
|
||||
support: the same quarters, with and without the guard.
|
||||
|
||||
⚠️ MUTATING THE MODULE THIS FILE GRADES? PURGE `__pycache__` FIRST - or run
|
||||
`tools/mutation_run.sh`, which does. `python3 -B` alone does NOT save you: it
|
||||
stops bytecode being WRITTEN, not a stale one being READ, and a size-preserving
|
||||
edit reverted inside one second is invisible to CPython's staleness test. That
|
||||
is TEST-15, and it has already turned one live mutation into a false survivor.
|
||||
Read MUTATION.md before you report a survivor.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
@@ -92,8 +117,9 @@ from app import peakguard
|
||||
from app.arbiter import (
|
||||
P_LOOP, P_MAINT_SHAPE, P_MAINTENANCE, P_PEAK, P_SAFETY, Claim, resolve,
|
||||
)
|
||||
from app.control import peak_at_risk
|
||||
from app.control import Tuning, compute, peak_at_risk
|
||||
from app.freeze import FreezeWatchdogConfig, looks_frozen, rail_w
|
||||
from app import main as app_main
|
||||
from app.main import Controller
|
||||
from app.p1 import (
|
||||
PLAUSIBLE_MAX_W, P1Ingest, QUARTER_S, QuarterAverager, make_sample,
|
||||
@@ -162,12 +188,26 @@ def read_option(key: str):
|
||||
|
||||
def read_schema_max(key: str):
|
||||
"""The schema's upper bound for `key` - `int(lo,hi)` -> hi."""
|
||||
return _schema_bound(key, 1)
|
||||
|
||||
|
||||
def read_schema_min(key: str):
|
||||
"""The schema's lower bound for `key` - `int(lo,hi)` -> lo.
|
||||
|
||||
SAFETY-25's sweep needs BOTH ends: the argument there is that no value the
|
||||
schema accepts changes the answer, and a sweep that only reached upwards
|
||||
would leave "well, set it lower then" unanswered.
|
||||
"""
|
||||
return _schema_bound(key, 0)
|
||||
|
||||
|
||||
def _schema_bound(key: str, which: int):
|
||||
body = (HERE / "config.yaml").read_text(encoding="utf-8")
|
||||
marker = body.index("\nschema:")
|
||||
for line in body[marker:].splitlines():
|
||||
st = line.strip()
|
||||
if st.startswith(f"{key}:") and "(" in st and ")" in st:
|
||||
return float(st[st.index("(") + 1:st.rindex(")")].split(",")[1])
|
||||
return float(st[st.index("(") + 1:st.rindex(")")].split(",")[which])
|
||||
return None
|
||||
|
||||
|
||||
@@ -810,9 +850,16 @@ print()
|
||||
print(f" BASELINE {totals['u_under']}/{totals['u_q']} = {U_PCT:.1f} % of "
|
||||
f"quarters under {CAP_W:.0f} W, uncontrolled")
|
||||
print(f" GUARDED {totals['g_under']}/{totals['g_q']} = {G_PCT:.1f} %")
|
||||
print(f" Two days, not thirty. AC 3 is TARIFF-01's and is still not met - "
|
||||
f"see test_tariff.py part 9. What this compares is the same quarters with "
|
||||
f"and without the guard, which is what two days can support.")
|
||||
print(f" Two days, not thirty - by choice: the thirty exist now "
|
||||
f"(scenarios/p1-net-30d-2026-08/, DATA-01) and live one directory down so "
|
||||
f"this glob does not pick them up and put ~50 s of replay on every PR. "
|
||||
f"tools/replay_ac3.py runs the month and must reproduce the totals above "
|
||||
f"to be believed: `python3 tools/replay_ac3.py scenarios --expect "
|
||||
f"{totals['u_under']}/{totals['u_q']}`. Over the thirty days the guard "
|
||||
f"takes August's peak from 5029.8 W to 4107.3 W - still over the "
|
||||
f"{CAP_W:.0f} W soft limit - and moves the interval count from 98.89 % to "
|
||||
f"98.99 %, because once a month peak is set the ceiling it defends is "
|
||||
f"that peak and not the cap. See that directory's README.")
|
||||
check("the guard improves on the uncontrolled baseline rather than merely "
|
||||
"matching it", G_PCT > U_PCT)
|
||||
check("...and it does not degrade a single quarter anywhere in the two days",
|
||||
@@ -868,6 +915,11 @@ class _Hass:
|
||||
def __init__(self):
|
||||
self.writes = []
|
||||
self.notifications = []
|
||||
# SAFETY-25. The whole payload, not only the id. AC 3 is about what the
|
||||
# operator READS, so a fixture that records only that a notification
|
||||
# fired cannot grade it - TEST-06's finding on SAFETY-18's NOT COVERED
|
||||
# row, one file across.
|
||||
self.calls = []
|
||||
|
||||
async def limits(self, entity):
|
||||
return (-LIVE_MAX_W, LIVE_MAX_W, 1.0)
|
||||
@@ -881,8 +933,15 @@ class _Hass:
|
||||
|
||||
async def call(self, domain, service, data):
|
||||
self.notifications.append(data.get("notification_id"))
|
||||
self.calls.append(dict(data))
|
||||
return True
|
||||
|
||||
def last_message(self, notification_id: str) -> str:
|
||||
"""The body of the most recent notification with that id, or ""."""
|
||||
bodies = [d.get("message", "") for d in self.calls
|
||||
if d.get("notification_id") == notification_id]
|
||||
return bodies[-1] if bodies else ""
|
||||
|
||||
|
||||
def built(db_path, opts=None, store=None):
|
||||
hass = _Hass()
|
||||
@@ -1779,9 +1838,9 @@ check("...and both are in the schema: block too, or the Supervisor drops the "
|
||||
"operator's value", sorted(_schema24) == sorted(PEAK_OPTION_DEFAULTS))
|
||||
_val_src = (HERE / "app" / "validate.py").read_text(encoding="utf-8")
|
||||
check("...and validate.py takes its fallbacks from that same mirror rather than "
|
||||
"typing literals - which is the divergence its own rule 6 documents "
|
||||
"(maintenance_charge_w 2000 there, 2500 in main.py), refused a second "
|
||||
"outing here",
|
||||
"typing literals - which is the divergence its own rule 6 used to "
|
||||
"document (maintenance_charge_w 2000 in config.yaml, 2500 in main.py), "
|
||||
"refused a second outing here and since closed by CFG-03",
|
||||
"PEAK_OPTION_DEFAULTS" in _val_src
|
||||
and not re.search(r'"peak_soc_floor"\s*,\s*[0-9]', _val_src)
|
||||
and not re.search(r'"peak_soc_floor"\s*,\s*[0-9]', _mainsrc))
|
||||
@@ -1800,9 +1859,617 @@ check("...and it is a SEPARATE KEY from maintenance_soc_floor, whose SHIPPED "
|
||||
and "maintenance_soc_floor" not in PEAK_OPTION_DEFAULTS)
|
||||
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
print()
|
||||
print("10. mutation: what defeats these guards, and which check bites")
|
||||
print("10. SAFETY-25: the loop discharges past this floor, and how far past")
|
||||
|
||||
# ⚠️ WHAT THIS PART IS. It is a TRIPWIRE, in MAINT-04's manner, and it records a
|
||||
# DEFECT rather than a guarantee. SAFETY-24's mutation 13 said in words that the
|
||||
# grid-following loop can take the pack past `peak_soc_floor`; that sentence has
|
||||
# now been written down four times across four tickets and never once measured.
|
||||
# This part measures it on the committed capture and pins the number, so that:
|
||||
#
|
||||
# * the honesty half of SAFETY-25 - the config comment, DOCS.md, the operator
|
||||
# notification and the status row - is anchored to a replayed figure rather
|
||||
# than to a claim, and
|
||||
# * THE DAY SOMEBODY BUILDS A LOOP-SIDE FLOOR, THIS GOES RED. That is the
|
||||
# point. The exposure must not be able to change under a green suite; it has
|
||||
# to be closed deliberately, and closing it means answering AC 2 and
|
||||
# deleting or inverting these checks along with
|
||||
# DECISIONS/SAFETY-25-loop-soc-floor.md's status - OPEN when this was
|
||||
# written, DECIDED (Option A, deferred B) since 2026-09-02.
|
||||
#
|
||||
# ⚠️ AND IT IS 10f THAT MAKES THAT SENTENCE TRUE, NOT 10a-10c. The replay
|
||||
# below hand-builds main.py's claim list, so on its own it is blind to a
|
||||
# floor filed as a NEW CLAIM - the memo's own Option B, and PR #31's
|
||||
# reviewer proved the blindness by building it: the whole suite stayed
|
||||
# green. 10f pins the claim-source set so that shape goes red too. The two
|
||||
# halves cover the two places a loop-side floor can be built: 10f for an
|
||||
# arbiter claim in Controller.cycle(), 10a-10c for a clamp inside
|
||||
# control.compute() or peakguard, which the replay drives directly.
|
||||
#
|
||||
# ⚠️ AND IT DRIVES THE SHIPPED CODE, not a transcription of it: control.compute()
|
||||
# at the shipped tuning, peakguard.decide(), peakguard.claim() and
|
||||
# arbiter.resolve(), in main.py's order. Break any of them and this part moves -
|
||||
# which is what makes it a check rather than a paragraph. See the memo section 7
|
||||
# for what is modelled and what is measured.
|
||||
|
||||
# The shipped tuning, READ from config.yaml rather than typed - the same rule as
|
||||
# every other number in this file. A tuning transcribed here would grade a
|
||||
# control law nobody ships.
|
||||
LOOP_TUNING = Tuning(
|
||||
gain=read_option("gain"), max_w=read_option("max_w"),
|
||||
slew_w=read_option("slew_w"), deadband_w=read_option("deadband_w"),
|
||||
step_w=int(read_option("step_w")), saturation_w=read_option("saturation_w"),
|
||||
saturation_cycles=int(read_option("saturation_cycles")),
|
||||
target_grid_w=read_option("target_grid_w"))
|
||||
LOOP_MAX_W = float(LOOP_TUNING.max_w)
|
||||
print(f" the shipped loop tuning, out of config.yaml: {LOOP_TUNING}")
|
||||
|
||||
# ⚠️ THE REFERENCE PACK, DERIVED FROM THE THREE HARDWARE NUMBERS THIS REPOSITORY
|
||||
# ALREADY STATES, not from a rounded kWh figure typed here. peakguard.py's
|
||||
# PEAK_OPTION_DEFAULTS comment says "300 Ah at 51.2 V with DoD 90 - 13.8 kWh
|
||||
# usable"; that sentence is asserted below, so if the reference pack ever
|
||||
# changes this fixture goes red instead of quietly modelling the old one.
|
||||
REF_PACK_WH = 300.0 * 51.2 * 0.90
|
||||
_pg_src = (HERE / "app" / "peakguard.py").read_text(encoding="utf-8")
|
||||
check("the modelled pack is the repository's own reference pack, and the source "
|
||||
"still says so - 300 Ah at 51.2 V with DoD 90. A fixture whose hardware "
|
||||
"assumption drifts away from the module it grades is a fixture measuring "
|
||||
"a machine nobody owns",
|
||||
"300 Ah at 51.2 V with DoD 90" in _pg_src
|
||||
and abs(REF_PACK_WH - 13800.0) < 100.0)
|
||||
|
||||
|
||||
def evening(h0: int, h1: int):
|
||||
"""The rows of 2026-08-20's capture inside [h0, h1) UTC, as they were.
|
||||
|
||||
`h1` may be 24, meaning "to the end of the capture" - the file runs to
|
||||
21:59:56 UTC, which is local midnight.
|
||||
"""
|
||||
lo = datetime(2026, 8, 20, h0, tzinfo=timezone.utc)
|
||||
hi = (datetime(2026, 8, 21, tzinfo=timezone.utc) if h1 >= 24
|
||||
else datetime(2026, 8, 20, h1, tzinfo=timezone.utc))
|
||||
out = []
|
||||
for line in gzip.open(BAD, "rt", encoding="utf-8"):
|
||||
row = json.loads(line)
|
||||
t = datetime.fromisoformat(row["t"])
|
||||
if lo <= t < hi:
|
||||
out.append((t, float(row["w"])))
|
||||
return out
|
||||
|
||||
|
||||
def replay_loop(window, *, start_soc, soc_floor, usable_wh=REF_PACK_WH):
|
||||
"""The GRID-FOLLOWING LOOP over a window, closed-loop, with a modelled pack.
|
||||
|
||||
part 6's `replay()` models the PEAK GUARD's discharge and pins the SoC above
|
||||
the floor on purpose - it is grading SAFETY-07. This one models the thing
|
||||
SAFETY-07 never claimed to bound: ordinary self-consumption.
|
||||
|
||||
The cycle is main.py's, in main.py's order and with main.py's claims:
|
||||
|
||||
peakguard.decide(...) the guard sees this cycle's SoC
|
||||
control.compute(...) the loop sees the meter minus the battery
|
||||
arbiter.resolve([supervised, loop@P_LOOP, peakguard.claim(...)])
|
||||
|
||||
⚠️ THE ARBITER IS IN THE PATH AND THAT IS THE WHOLE POINT. Cutting it out
|
||||
and reading `Decision.target_w` directly would measure the control law and
|
||||
prove nothing about the floor: the question is whether the guard's `lo`
|
||||
claim, filed at P_PEAK against a loop winning at P_LOOP, can cap the
|
||||
discharge. It cannot, and it is `resolve()` that has to say so.
|
||||
|
||||
The pack model is part 9's, one line for one line - SoC falls by the
|
||||
DELIVERED discharge integrated over the real telegram stamps, the BMS is a
|
||||
hard cut at `bms_soc_floor`, and nothing recharges inside the window.
|
||||
`start_soc` is the one number the captures cannot supply (they carry meter
|
||||
power only), and it is derived from the shipped option rather than picked.
|
||||
"""
|
||||
ing = P1Ingest(phases=1, max_age_s=MAX_HOLD_S)
|
||||
store = fresh_store(f"s25-{window[0][0]:%H%M}-{soc_floor:.0f}-{start_soc:.0f}")
|
||||
tracker = PeakTracker(store, cap_w=CAP_W)
|
||||
batt = 0.0 # delivered discharge, W (positive)
|
||||
prev_w = i_w = 0.0
|
||||
sat = 0
|
||||
soc = float(start_soc)
|
||||
min_soc = soc
|
||||
wh = 0.0
|
||||
prev_t = next_cycle = None
|
||||
cycles = below = below_discharging = limited = limited_discharging = 0
|
||||
at_bms = guard_floors = 0
|
||||
max_granted = 0.0
|
||||
for t, w in window:
|
||||
if prev_t is not None:
|
||||
dwh = batt * (t - prev_t).total_seconds() / 3600.0
|
||||
wh += dwh
|
||||
soc = max(0.0, soc - 100.0 * dwh / usable_wh)
|
||||
min_soc = min(min_soc, soc)
|
||||
prev_t = t
|
||||
ing.submit(sample(t, w - batt))
|
||||
tracker.sync(ing)
|
||||
if next_cycle is not None and t < next_cycle:
|
||||
continue
|
||||
next_cycle = t + timedelta(seconds=CYCLE_S)
|
||||
cycles += 1
|
||||
d = decide(PeakTracker.project(ing.averager, t), batt_w=batt,
|
||||
cap_w=CAP_W, reading=tracker.peak(t),
|
||||
achievable_w=LOOP_MAX_W, max_hold_s=MAX_HOLD_S, soc=soc,
|
||||
soc_floor=soc_floor, frozen=False)
|
||||
dec = compute(prev_w, w - batt, batt, LOOP_TUNING, sat_count=sat,
|
||||
i_w=i_w)
|
||||
sat, i_w = dec.sat_count, dec.i_w
|
||||
claims = [Claim.limit("supervised", P_SAFETY, -LOOP_MAX_W, LOOP_MAX_W,
|
||||
"max_w"),
|
||||
Claim.set("loop", P_LOOP, dec.target_w, dec.reason)]
|
||||
pc = peakguard.claim(d)
|
||||
if pc is not None:
|
||||
claims.append(pc)
|
||||
if pc.lo > 0.0:
|
||||
guard_floors += 1
|
||||
r = resolve(claims)
|
||||
prev_w = r.target_w
|
||||
# THE BMS, MODELLED - part 9's line, for part 9's reason. The pack's own
|
||||
# cut-out is a real floor and it works; the finding is that it is the
|
||||
# only one.
|
||||
if soc <= BMS_FLOOR:
|
||||
at_bms += 1
|
||||
batt = 0.0
|
||||
else:
|
||||
batt = max(0.0, r.target_w)
|
||||
max_granted = max(max_granted, batt)
|
||||
if soc < soc_floor:
|
||||
below += 1
|
||||
below_discharging += 1 if batt > 0.0 else 0
|
||||
if d.floor_limited:
|
||||
limited += 1
|
||||
limited_discharging += 1 if batt > 0.0 else 0
|
||||
return {"cycles": cycles, "wh": wh, "min_soc": min_soc, "end_soc": soc,
|
||||
"below": below, "below_discharging": below_discharging,
|
||||
"limited": limited, "limited_discharging": limited_discharging,
|
||||
"at_bms": at_bms, "guard_floors": guard_floors,
|
||||
"max_granted": max_granted}
|
||||
|
||||
|
||||
# --- 10a. the sustained-load evening ----------------------------------------
|
||||
# 19:00-22:00 UTC is 21:00-24:00 local: the sun is down, the PV is off, and the
|
||||
# house is simply drawing. Chosen for that property and CHECKED for it below -
|
||||
# a window with export in it would let the loop recharge and the replay would be
|
||||
# measuring something else.
|
||||
EVE = evening(19, 24)
|
||||
EVE_W = [w for _, w in EVE]
|
||||
print(f" the evening of 2026-08-20, {EVE[0][0]:%H:%M}-{EVE[-1][0]:%H:%M} UTC: "
|
||||
f"{len(EVE)} telegrams, mean {sum(EVE_W) / len(EVE_W):.0f} W, "
|
||||
f"min {min(EVE_W):.0f} W, max {max(EVE_W):.0f} W")
|
||||
check("the window really is a SUSTAINED-LOAD evening and not a quiet one - "
|
||||
"every telegram in it is an IMPORT, so the pack has nowhere to recharge "
|
||||
"from and the loop is discharging for the whole three hours",
|
||||
min(EVE_W) > 0.0 and len(EVE) > 1500)
|
||||
|
||||
# ⚠️ ONE POINT ABOVE THE FLOOR, DERIVED FROM THE SHIPPED OPTION. This is the
|
||||
# state an operator who has read `peak_soc_floor: 20` believes is protected: the
|
||||
# pack is above the number they set. It is the only fixture parameter the
|
||||
# captures cannot supply, and it is taken from config.yaml rather than chosen.
|
||||
EVE_START = SOC_FLOOR + 1.0
|
||||
EV = replay_loop(EVE, start_soc=EVE_START, soc_floor=SOC_FLOOR)
|
||||
print(f" the reference pack ({REF_PACK_WH:.0f} Wh usable) starting at "
|
||||
f"{EVE_START:.0f} %, one point above peak_soc_floor {SOC_FLOOR:.0f} %:")
|
||||
print(f" ends at {EV['end_soc']:.1f} %, low-water {EV['min_soc']:.1f} %, "
|
||||
f"{EV['wh']:.0f} Wh delivered by the LOOP over {EV['cycles']} cycles")
|
||||
print(f" {EV['below']} cycles with the pack under peak_soc_floor, "
|
||||
f"{EV['below_discharging']} of them still discharging; "
|
||||
f"{EV['at_bms']} at the BMS cut-out; the guard filed a floor on "
|
||||
f"{EV['guard_floors']}")
|
||||
check(f"THE FINDING, REPLAYED. One sustained-load evening takes the pack from "
|
||||
f"above peak_soc_floor to the pack's own BMS cut-out - "
|
||||
f"{EVE_START:.0f} % -> {EV['end_soc']:.1f} % against a "
|
||||
f"{BMS_FLOOR:.0f} % cut-out - and the EMS floor an operator set is not "
|
||||
f"what stopped it",
|
||||
EV["min_soc"] <= BMS_FLOOR + 0.05 and EV["at_bms"] > 0)
|
||||
check("...and it is not one cycle of overshoot past the floor either: the loop "
|
||||
"goes on delivering discharge for hundreds of cycles with the pack "
|
||||
"already below the number the operator configured",
|
||||
EV["below_discharging"] > 100 and EV["below"] > EV["below_discharging"])
|
||||
check("...and the peak guard is not involved at all. It never files a floor on "
|
||||
"this evening, because 830 W of house load never projects a quarter over "
|
||||
"the 3500 W ceiling - so `peak_soc_floor` is not merely too weak here, it "
|
||||
"is never consulted", EV["guard_floors"] == 0 and EV["limited"] == 0)
|
||||
|
||||
# --- 10b. and it is a BEHAVIOUR, not a config value -------------------------
|
||||
# ⚠️ THE SWEEP IS THE ARGUMENT. "Raise peak_soc_floor" is the first thing anyone
|
||||
# reading the option name would try, so the check is not that it is insufficient
|
||||
# - it is that it does NOTHING, at any value the schema will accept, to four
|
||||
# decimal places. Both ends of the schema range are swept rather than a
|
||||
# comfortable middle.
|
||||
SOC_SCHEMA_LO = float(read_schema_min("peak_soc_floor"))
|
||||
SOC_SCHEMA_HI = float(read_schema_max("peak_soc_floor"))
|
||||
SWEEP_FLOORS = [SOC_SCHEMA_LO, BMS_FLOOR + 1.0, SOC_FLOOR, SOC_SCHEMA_HI]
|
||||
SWEPT = [(f, replay_loop(EVE, start_soc=EVE_START, soc_floor=f))
|
||||
for f in SWEEP_FLOORS]
|
||||
for f, res in SWEPT:
|
||||
print(f" peak_soc_floor {f:5.0f} % -> ends at {res['end_soc']:.4f} %,"
|
||||
f" {res['wh']:.2f} Wh out, guard floors {res['guard_floors']}")
|
||||
check(f"the exposure is a BEHAVIOUR, NOT A CONFIG VALUE - the same evening ends "
|
||||
f"at the same state of charge at every peak_soc_floor the schema accepts "
|
||||
f"({SOC_SCHEMA_LO:.0f}..{SOC_SCHEMA_HI:.0f} %), to four decimal places. "
|
||||
f"This is AC 4's sentence, measured: the option an operator would reach "
|
||||
f"for cannot move this number by any amount at all",
|
||||
len({round(res["end_soc"], 4) for _, res in SWEPT}) == 1
|
||||
and len({round(res["wh"], 4) for _, res in SWEPT}) == 1)
|
||||
# ⚠️ THE SWEEP DELIBERATELY OVERRUNS WHAT VALIDATE WOULD ACCEPT. Its low end is
|
||||
# the SCHEMA's, and rule 8 refuses anything at or below `bms_soc_floor`, so a
|
||||
# start at 5 % is not a configuration an operator could boot. Including it is the
|
||||
# point: it closes "you swept only the legal band" without leaving the reader to
|
||||
# wonder what happens outside it. The band that IS startable is bounded below by
|
||||
# rule 8, and BMS_FLOOR + 1 is its first member, which is in the sweep too.
|
||||
check("...and the sweep spans the whole schema range, rule 8's refused low end "
|
||||
"included, so 'a legal value would have worked' is closed off rather "
|
||||
"than left open. The first STARTABLE floor - one point above "
|
||||
"bms_soc_floor - is swept as well, and lands on the same number",
|
||||
SOC_SCHEMA_HI >= 60.0 and SOC_SCHEMA_LO <= BMS_FLOOR
|
||||
and (BMS_FLOOR + 1.0) in SWEEP_FLOORS
|
||||
and len([f for f in SWEEP_FLOORS if f > BMS_FLOOR]) >= 3)
|
||||
|
||||
# --- 10c. the two states in the SAME cycle ----------------------------------
|
||||
# The evening never engages the guard, so it cannot show the sharpest form of
|
||||
# the finding: the status page saying FLOOR-LIMITED while the pack empties. The
|
||||
# same day's high-load block can, and it is the same capture and the same code.
|
||||
HOT = evening(15, 17)
|
||||
HOT_R = replay_loop(HOT, start_soc=SOC_FLOOR - 1.0, soc_floor=SOC_FLOOR)
|
||||
print(f" the same day's high-load block "
|
||||
f"{HOT[0][0]:%H:%M}-{HOT[-1][0]:%H:%M} UTC, pack started one point BELOW "
|
||||
f"the floor:")
|
||||
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 "
|
||||
"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",
|
||||
HOT_R["limited"] > 10
|
||||
and HOT_R["limited_discharging"] == HOT_R["limited"]
|
||||
and HOT_R["max_granted"] > 0.0)
|
||||
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 "
|
||||
"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)
|
||||
|
||||
# --- 10d. the trap in the obvious fix, checked rather than asserted ---------
|
||||
# ⚠️ THE MEMO'S CENTRAL ENGINEERING CLAIM, RUN THROUGH THE REAL ARBITER. The
|
||||
# first shape anyone reaches for is a `hi` limit on the loop - and filed while
|
||||
# the peak guard is asking for a positive floor it is `lo > hi`, which
|
||||
# arbiter.py resolves to 0 W: THE BATTERY PARKED, in the one quarter of the
|
||||
# month that sets the bill. That is the same crossing-limits hazard
|
||||
# shaping_suspended() already exists to avoid, and it is why the memo's Option B
|
||||
# carries an ORDERING RULE rather than a number.
|
||||
_RESERVE_HI = Claim.limit("reserve", P_LOOP, hi=0.0, reason="loop SoC floor")
|
||||
_naive = resolve(SAFE + [Claim.set("loop", P_LOOP, 1800.0, "grid"),
|
||||
peakguard.claim(d_ok), _RESERVE_HI])
|
||||
_ordered = resolve(SAFE + [Claim.set("loop", P_LOOP, 1800.0, "grid"),
|
||||
lc, _RESERVE_HI])
|
||||
print(f" a naive loop reserve while the guard wants a floor: "
|
||||
f"{_naive.explain()}")
|
||||
print(f" the same reserve while the guard is floor-limited: "
|
||||
f"{_ordered.explain()}")
|
||||
check("a loop-side `hi` reserve filed while the peak guard is asking for a "
|
||||
"POSITIVE floor is a CONTRADICTION and parks the battery at 0 W - so the "
|
||||
"obvious shape of AC 2 has a trap in it, and this is it, run rather than "
|
||||
"described", _naive.contradiction and near(_naive.target_w, 0.0))
|
||||
check("...and the ordering the memo proposes removes it: with "
|
||||
"loop_soc_floor <= peak_soc_floor the guard is ALREADY floor-limited "
|
||||
"wherever the reserve binds, so it files lo = 0, and lo == hi == 0 "
|
||||
"resolves to a clean 0 W with no contradiction",
|
||||
not _ordered.contradiction and near(_ordered.target_w, 0.0)
|
||||
and near(lc.lo, 0.0) and peakguard.claim(d_ok).lo > 0.0)
|
||||
|
||||
# --- 10e. the honesty half, pinned to the shipped text ----------------------
|
||||
# ⚠️ ASSERT THE STRING, NOT THE INTENT - TEST-06's lesson on SAFETY-18's NOT
|
||||
# COVERED row, which was untested for exactly this reason: the one branch that
|
||||
# exists to tell an operator what a guard does NOT cover is the one nothing
|
||||
# grades. These four surfaces are the whole of AC 3, and each is checked where
|
||||
# it actually renders.
|
||||
_cfg_src = (HERE / "config.yaml").read_text(encoding="utf-8")
|
||||
_docs_src = (HERE / "DOCS.md").read_text(encoding="utf-8")
|
||||
_memo = HERE / "DECISIONS" / "SAFETY-25-loop-soc-floor.md"
|
||||
check("config.yaml says next to the option itself that peak_soc_floor bounds "
|
||||
"the peak guard only and is not a pack-wide reserve - the operator edits "
|
||||
"this file, so it is the first place the scope has to be true",
|
||||
"BOUNDS THE PEAK GUARD ONLY" in _cfg_src
|
||||
and "NOT A PACK-WIDE RESERVE" in _cfg_src.upper()
|
||||
and "bms_soc_floor) stops it" in _cfg_src)
|
||||
check("...and DOCS.md says it in the options table AND in the section, with the "
|
||||
"replayed evening rather than an assurance",
|
||||
"not a pack-wide reserve" in _docs_src
|
||||
and "IT BOUNDS THE PEAK GUARD ONLY" in _docs_src
|
||||
and "SAFETY-25" in _docs_src)
|
||||
# ⚠️ THE DECISION LANDED (2026-09-02, Option A) AND THIS CHECK MOVED WITH IT.
|
||||
# It used to pin "Status: OPEN. This is a memo, not a decision." - the memo being
|
||||
# HONEST that AC 2 was unanswered. AC 2 is answered now, so the same check pins
|
||||
# the same property in its new form: the memo states WHICH option, WHEN, and its
|
||||
# REVISIT TRIGGER, and it still carries the options and the recommendation
|
||||
# UNCHANGED. A memo that recorded the verdict and deleted the reasoning would be
|
||||
# the failure this is guarding against, which is why "Recommendation" and both
|
||||
# rejected options are still asserted here rather than only the status line.
|
||||
_memo_txt = _memo.read_text(encoding="utf-8")
|
||||
check("...and the decision memo AC 1 asks for is COMMITTED, records AC 2 as "
|
||||
"DECIDED with a date, an option and a revisit trigger, and STILL carries "
|
||||
"the options analysis and the recommendation that were put to the owner",
|
||||
_memo.exists()
|
||||
and "Status: DECIDED 2026-09-02 — Option A." in _memo_txt
|
||||
and "ALLOC-01" in _memo_txt
|
||||
and "Recommendation" in _memo_txt
|
||||
and "### Option A" in _memo_txt and "### Option B" in _memo_txt)
|
||||
check("...and it says plainly that part 10f - the pin that made SAFETY-25 "
|
||||
"mergeable - is a SCALAR SoC sweep against a single-series capture and "
|
||||
"so cannot express two packs. The tripwire's own limits belong in the "
|
||||
"memo that leans on it, or the next reader merges a two-pack reserve on "
|
||||
"a green check that cannot see the failure",
|
||||
"10f" in _memo_txt and "SAFETY-27" in _memo_txt
|
||||
and "cannot express two packs" in _memo_txt.lower())
|
||||
check("...and DOCS.md sends the reader to it rather than leaving the open "
|
||||
"question implicit",
|
||||
"DECISIONS/SAFETY-25-loop-soc-floor.md" in _docs_src)
|
||||
|
||||
# The two OPERATOR-FACING surfaces, rendered by the real Controller rather than
|
||||
# grepped: the status row and the notification body are what a human reads at
|
||||
# the moment the guard stops, and a scope sentence that lives only in a source
|
||||
# comment is a scope sentence the operator never sees.
|
||||
c25, hass25, NET25, _ = wired_over_limit(
|
||||
TMP / "soc25.db", LIVE_MAX_W * 0.3, soc=SOC_FLOOR - 1.0)
|
||||
rows25 = [r for r in c25.checks() if "peak guard" in r["text"].lower()]
|
||||
print(" status row: " + (rows25[0]["text"] if rows25 else "(none)"))
|
||||
check("the STATUS PAGE row for a floor-limited guard says the floor bounds the "
|
||||
"guard only and that self-consumption may keep discharging below it. "
|
||||
"Without that sentence the page implies a pack-wide reserve at the exact "
|
||||
"moment the replay above says the loop is still emptying the pack",
|
||||
len(rows25) == 1
|
||||
and "PEAK GUARD FLOOR-LIMITED" in rows25[0]["text"]
|
||||
and "BOUNDS THE PEAK GUARD ONLY" in rows25[0]["text"].upper()
|
||||
and "not a pack-wide reserve" in rows25[0]["text"]
|
||||
and "BMS cut-out" in rows25[0]["text"])
|
||||
# ⚠️ THE ROW KEEPS THE WHOLE SENTENCE; THE BANNER DOES NOT. status_payload()
|
||||
# renders the first not-ok/not-warn row as the page headline, so before this the
|
||||
# loudest element on the page was the same 550-character paragraph the row three
|
||||
# lines below repeats verbatim. The scope wording is not weakened anywhere it
|
||||
# matters - it is the ROW that an operator reads to learn what the floor bounds,
|
||||
# and the row is asserted in full above.
|
||||
_pay25 = c25.status_payload()
|
||||
print(f" banner ({len(_pay25['banner'])} chars): {_pay25['banner']}")
|
||||
# The guard's own line, which the banner has always carried and which is not
|
||||
# this card's to shorten: `explain()` is SAFETY-24's sentence about a quarter
|
||||
# that is going over the ceiling.
|
||||
_expl25 = rows25[0]["text"].split(". NOTE:")[0]
|
||||
check("the NOT READY banner is the guard's own line plus a SHORT scope tag - "
|
||||
"under 90 characters of it - and NOT the row's whole paragraph repeated "
|
||||
"at the top of the page. A headline that is a paragraph is a headline "
|
||||
"nobody reads, and this one is followed three lines later by the same "
|
||||
"text verbatim",
|
||||
_pay25["level"] == "bad"
|
||||
and _pay25["banner"].startswith("NOT READY")
|
||||
and _expl25 in _pay25["banner"]
|
||||
and "BOUNDS THE PEAK GUARD ONLY" in _pay25["banner"].upper()
|
||||
and "not a pack-wide reserve" not in _pay25["banner"]
|
||||
and len(_pay25["banner"]) - len(_expl25) < 90)
|
||||
check("...and shortening the banner did NOT shorten the row: the full AC 3 "
|
||||
"sentence is still what the checks list carries, which is the surface the "
|
||||
"operator reads to find out what the floor does not bound",
|
||||
len(rows25[0]["text"]) > 300
|
||||
and "not a pack-wide reserve" in rows25[0]["text"]
|
||||
and "BMS cut-out" in rows25[0]["text"])
|
||||
|
||||
_body25 = hass25.last_message("goodwe_peak_soc_floor")
|
||||
print(f" notification body tail: ...{_body25[-180:]}")
|
||||
check("...and so does the persistent notification, which outlives the page and "
|
||||
"is the thing an operator reads on a phone at 19:00. It names what has "
|
||||
"stopped - the guard buying a lower bill - and what has not",
|
||||
"peak_soc_floor bounds THE PEAK GUARD ONLY" in _body25
|
||||
and "not a" in _body25 and "pack-wide reserve" in _body25
|
||||
and "BMS cut-out" in _body25)
|
||||
|
||||
|
||||
# --- 10f. THE CLAIM-SOURCE SET, PINNED --------------------------------------
|
||||
# ⚠️ THIS IS WHAT MAKES 10a-10c A TRIPWIRE RATHER THAN A SNAPSHOT, and it is
|
||||
# here because the first cut of this part did NOT have it and the tripwire
|
||||
# sentence above was therefore FALSE. `replay_loop()` hand-builds main.py's
|
||||
# claim list as a literal `[supervised, loop, peakguard.claim(...)]`, so it is
|
||||
# structurally BLIND to any claim main.py ADDS - which is exactly where AC 2
|
||||
# would be built. PR #31's reviewer proved it by building the fix: they
|
||||
# implemented the memo's own Option B in main.py - a
|
||||
# `Claim.limit("reserve", P_LOOP, hi=0.0)` filed under a `loop_soc_floor` - and
|
||||
# the whole suite stayed GREEN, this part included, while mutation 13 went on
|
||||
# printing "NOTHING PREVENTS IT, ON PURPOSE" and the same 21 % -> 10.0 % on a
|
||||
# tree where something DID prevent it. Pushed to an always-binding 95 % reserve
|
||||
# it was still green here. That is this repository's named failure mode - a
|
||||
# check that observed something other than what it claimed to observe - and it
|
||||
# had been committed as a guarantee in four places.
|
||||
#
|
||||
# So the MODEL is now pinned to the MODELLED THING, two ways, because the two
|
||||
# fail differently:
|
||||
#
|
||||
# * STATICALLY, over `Controller.cycle()`'s own AST. Every `claims.append(...)`
|
||||
# in it must be one this scan can read, and the set of sources it can file
|
||||
# must be exactly the eight below. A ninth - a `reserve`, whatever it ends
|
||||
# up called - takes this red on the line it is written, in every
|
||||
# configuration, whether or not any fixture here reaches the state that
|
||||
# files it.
|
||||
# * DYNAMICALLY, through REAL `Controller.cycle()`s with main.py's OWN
|
||||
# `resolve` spied, swept over the WHOLE state-of-charge range in the two
|
||||
# states 10a-10c replay. The static scan pins the NAMES; this pins that the
|
||||
# names actually reach the arbiter and that nothing else does. A claim that
|
||||
# appears only at a low SoC - precisely the shape a loop-side floor has -
|
||||
# cannot hide from a sweep that visits 0 %.
|
||||
#
|
||||
# The third way a loop-side floor could be built is INSIDE `control.compute()`
|
||||
# or the guard (the memo's Option D), and that needs nothing new here: the
|
||||
# replay above drives both, so it moves the numbers in 10a-10c directly.
|
||||
|
||||
# The whole inventory of claim sources main.py can file, in any configuration.
|
||||
# ⚠️ ADDING TO THIS SET IS A DELIBERATE ACT. If you are here because you added a
|
||||
# claim to `Controller.cycle()` and this went red, that is the tripwire working:
|
||||
# read DECISIONS/SAFETY-25-loop-soc-floor.md and update part 10 and mutation 13
|
||||
# rather than this line alone. ⚠️ AC 2 IS DECIDED (2026-09-02, Option A) AND
|
||||
# THAT DOES NOT RETIRE THIS SET - Option B is DEFERRED, not rejected, and
|
||||
# "deferred" is exactly the state in which a ninth source gets built by
|
||||
# accident. Its revisit trigger is ALLOC-01, under which the reserve becomes a
|
||||
# PER-INVERTER interval at the allocator rather than a ninth claim here.
|
||||
CLAIM_SOURCES = {"device", "supervised", "failsafe", "safety", "peak",
|
||||
"arbitrage", "maintenance", "loop"}
|
||||
# The two appends that file a claim BUILT ELSEWHERE in the method. Named here so
|
||||
# that a THIRD such indirection reads as an unrecognised append rather than as a
|
||||
# silent gap in the scan.
|
||||
CLAIM_BUILDERS = {"peak_claim": "peak", "arb_claim": "arbitrage"}
|
||||
|
||||
_main_tree = ast.parse((HERE / "app" / "main.py").read_text(encoding="utf-8"))
|
||||
_cycle_def = next(
|
||||
f
|
||||
for cls in ast.walk(_main_tree)
|
||||
if isinstance(cls, ast.ClassDef) and cls.name == "Controller"
|
||||
for f in cls.body
|
||||
if isinstance(f, (ast.FunctionDef, ast.AsyncFunctionDef)) and f.name == "cycle")
|
||||
|
||||
|
||||
def claim_source(node):
|
||||
"""The source string an appended expression files, or None if unreadable."""
|
||||
if (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute)
|
||||
and isinstance(node.func.value, ast.Name)
|
||||
and node.func.value.id == "Claim"
|
||||
and node.func.attr in ("set", "limit") and node.args
|
||||
and isinstance(node.args[0], ast.Constant)
|
||||
and isinstance(node.args[0].value, str)):
|
||||
return node.args[0].value
|
||||
if isinstance(node, ast.Name):
|
||||
return CLAIM_BUILDERS.get(node.id)
|
||||
return None
|
||||
|
||||
|
||||
_appends = [n for n in ast.walk(_cycle_def)
|
||||
if isinstance(n, ast.Call) and isinstance(n.func, ast.Attribute)
|
||||
and n.func.attr == "append" and isinstance(n.func.value, ast.Name)
|
||||
and n.func.value.id == "claims" and len(n.args) == 1]
|
||||
_filed = [claim_source(n.args[0]) for n in _appends]
|
||||
print(f" main.py Controller.cycle() files {len(_appends)} claims, from "
|
||||
f"{len(CLAIM_SOURCES)} sources: "
|
||||
f"{', '.join(sorted({s for s in _filed if s}))}")
|
||||
check("every `claims.append(...)` in main.py's cycle is one this scan can READ "
|
||||
"- a claim filed through a shape it cannot parse has to fail here rather "
|
||||
"than be counted as nothing, which is how a scan like this goes quietly "
|
||||
"vacuous", len(_appends) >= 10 and None not in _filed)
|
||||
check("...and the sources that cycle can file are EXACTLY these eight. THIS is "
|
||||
"what makes part 10 a tripwire: replay_loop() hand-builds the claim list, "
|
||||
"so it cannot see a claim main.py adds - and a loop-side SoC reserve is a "
|
||||
"NINTH source. Filing one takes this line red on the line it is written",
|
||||
set(_filed) == CLAIM_SOURCES)
|
||||
|
||||
|
||||
def cycle_claims(run):
|
||||
"""The claim list main.py's OWN `resolve` was handed, from a real cycle.
|
||||
|
||||
⚠️ SPIED AT `app.main.resolve`, not reconstructed. The point of the whole
|
||||
sub-part is that this file must stop believing its own transcription of
|
||||
main.py's claim list, so the observation has to be taken from main.py's
|
||||
call site and nowhere else.
|
||||
"""
|
||||
seen = []
|
||||
real = app_main.resolve
|
||||
|
||||
def _spy(claims):
|
||||
seen.append(list(claims))
|
||||
return real(claims)
|
||||
|
||||
app_main.resolve = _spy
|
||||
try:
|
||||
out = run()
|
||||
finally:
|
||||
app_main.resolve = real
|
||||
return out, (seen[-1] if seen else [])
|
||||
|
||||
|
||||
def run_cycle(ctl):
|
||||
asyncio.get_event_loop_policy().new_event_loop().run_until_complete(
|
||||
ctl.cycle())
|
||||
return ctl
|
||||
|
||||
|
||||
# The IDLE state, which is what 10a and 10b replay: a sustained house load well
|
||||
# under the ceiling, so the guard files nothing and the loop is alone with the
|
||||
# safety limits. One controller, cycled once per state of charge - the load is
|
||||
# the evening's own mean, so this is the evening's cycle at every SoC it passes
|
||||
# through and at every SoC it does not.
|
||||
EVE_MEAN_W = sum(EVE_W) / len(EVE_W)
|
||||
c_src, _ = built(TMP / "sources.db")
|
||||
c_src.auto, c_src.batt, c_src.soc = True, 0.0, 100.0
|
||||
_blk_src = datetime.fromtimestamp(
|
||||
int(datetime.now(timezone.utc).timestamp() // QUARTER_S) * QUARTER_S,
|
||||
timezone.utc)
|
||||
for _i in range(0, int((datetime.now(timezone.utc)
|
||||
- _blk_src).total_seconds()) + 1, 5):
|
||||
c_src.p1.submit(sample(_blk_src + timedelta(seconds=_i), EVE_MEAN_W))
|
||||
c_src.grid = EVE_MEAN_W
|
||||
|
||||
# ⚠️ THE WHOLE RANGE, INCLUDING 0 %. A reserve conditioned on a low pack is
|
||||
# invisible to a sweep that starts at a comfortable one, and "conditioned on a
|
||||
# low pack" is the definition of the claim this is watching for.
|
||||
SRC_SWEEP = sorted({float(s) for s in range(0, 101, 5)}
|
||||
| {BMS_FLOOR, SOC_FLOOR, EVE_START, EV["end_soc"]})
|
||||
IDLE_SRC = {}
|
||||
for _soc in SRC_SWEEP:
|
||||
c_src.soc = _soc
|
||||
_, _cl = cycle_claims(lambda: run_cycle(c_src))
|
||||
IDLE_SRC[_soc] = frozenset(c.source for c in _cl)
|
||||
IDLE_SETS = set(IDLE_SRC.values())
|
||||
print(f" a real idle cycle at {len(SRC_SWEEP)} states of charge "
|
||||
f"({min(SRC_SWEEP):.0f}..{max(SRC_SWEEP):.0f} %) files: "
|
||||
+ " | ".join(sorted(", ".join(sorted(s)) for s in IDLE_SETS)))
|
||||
check("a REAL Controller.cycle() in the state 10a and 10b replay - auto, P1 "
|
||||
"healthy, the guard idle under an 830 W load - hands the arbiter exactly "
|
||||
"{device, supervised, loop}, at EVERY state of charge from 0 to 100 %. "
|
||||
"Not one source appears at a low pack that does not appear at a full one, "
|
||||
"which is the claim a loop-side reserve would break",
|
||||
IDLE_SETS == {frozenset({"device", "supervised", "loop"})}
|
||||
and len(SRC_SWEEP) >= 21 and min(SRC_SWEEP) == 0.0)
|
||||
|
||||
# The ENGAGED state, which is what 10c replays: the guard over its ceiling and
|
||||
# floor-limited on an empty pack. Two states of charge, both under the floor,
|
||||
# because that is the band a loop-side reserve would be conditioned on.
|
||||
HOT_SRC = set()
|
||||
for _soc in (SOC_FLOOR - 1.0, 0.0):
|
||||
(c_h, _h, _n, _r), _cl = cycle_claims(
|
||||
lambda: wired_over_limit(TMP / f"sources-hot-{_soc:.0f}.db",
|
||||
LIVE_MAX_W * 0.3, soc=_soc))
|
||||
HOT_SRC.add(frozenset(c.source for c in _cl))
|
||||
_hot_limited = c_h.peak_guard is not None and c_h.peak_guard.floor_limited
|
||||
print(" a real FLOOR-LIMITED cycle files: "
|
||||
+ " | ".join(sorted(", ".join(sorted(s)) for s in HOT_SRC)))
|
||||
check("...and with the guard actually FLOOR-LIMITED - 10c's state, on an empty "
|
||||
"pack - the set gains the guard's own claim and NOTHING ELSE. So the "
|
||||
"three sources replay_loop() hand-builds are the whole cycle in both of "
|
||||
"the states it replays, rather than a subset of it that happened to "
|
||||
"match", _hot_limited
|
||||
and HOT_SRC == {frozenset({"device", "supervised", "loop", "peak"})})
|
||||
|
||||
# THE FOLD, stated rather than assumed. replay_loop() files ONE `supervised`
|
||||
# limit where main.py files two - `device`, from the inverter's own reported
|
||||
# range, and `supervised`, from `max_w`. Both are symmetric P_SAFETY limits, so
|
||||
# the tighter one binds and modelling them as one is exact, not an
|
||||
# approximation. Checked on the claims the real cycle actually filed.
|
||||
_safety_lims = [c for c in _cl if c.source in ("device", "supervised")]
|
||||
check("...and replay_loop() folding main.py's TWO P_SAFETY rating limits into "
|
||||
"its one `supervised` claim is exact rather than convenient: both are "
|
||||
"symmetric LIMIT claims at P_SAFETY, so the tighter of the pair binds and "
|
||||
"one claim at the tighter bound is the same constraint",
|
||||
len(_safety_lims) == 2
|
||||
and all(c.kind == "limit" and c.priority == P_SAFETY
|
||||
and near(c.lo, -c.hi) and c.hi > 0.0 for c in _safety_lims)
|
||||
and near(LOOP_MAX_W, read_option("max_w")))
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
print()
|
||||
print("11. mutation: what defeats these guards, and which check bites")
|
||||
|
||||
# Each entry re-implements ONE defeat and reports whether a check above would
|
||||
# have gone red. The last row is the honest one: it does NOT bite, and saying so
|
||||
@@ -1915,13 +2582,28 @@ MUT.append(("floor-limited reported but the floor still filed at `wanted`",
|
||||
# 13. THE SECOND ONE THAT DOES NOT BITE, and it is a real limitation rather than
|
||||
# a defect. Stated, because the alternative is a reader believing this card
|
||||
# bounds more than it does.
|
||||
#
|
||||
# ⚠️ SAFETY-25 CHANGED WHAT "NOT CAUGHT" MEANS HERE, AND ONLY THAT. Nothing
|
||||
# PREVENTS it - the code is unchanged and a `lo` limit still cannot cap a
|
||||
# discharge - but part 10 now MEASURES it on the committed capture and 10f
|
||||
# PINS THE CLAIM-SOURCE SET around it, so the exposure can no longer change
|
||||
# size under a green suite: file the reserve and 10f goes red on the line
|
||||
# it is written. That is the whole difference between an uncaught mutation
|
||||
# and an unrecorded one. ⚠️ THE PIN IS LOAD-BEARING FOR THIS ROW. Without
|
||||
# it this rationale was FALSE - PR #31's reviewer built the memo's Option B
|
||||
# and this row went on printing "NOTHING PREVENTS IT" under a green suite.
|
||||
_loop_unbounded = near(r_disch.target_w, 1800.0, 1e-9)
|
||||
MUT.append(("the grid-following loop discharging past this floor",
|
||||
not _loop_unbounded,
|
||||
"NOTHING, ON PURPOSE - this card bounds THE PEAK GUARD's forced "
|
||||
"discharge, the thing SAFETY-07 introduced. SAFETY-18's finding "
|
||||
"that the loop itself has no SoC guard is still open, and a `lo` "
|
||||
"limit is structurally incapable of closing it"))
|
||||
"NOTHING PREVENTS IT, ON PURPOSE - this card bounds THE PEAK "
|
||||
"GUARD's forced discharge, the thing SAFETY-07 introduced. A `lo` "
|
||||
"limit is structurally incapable of closing SAFETY-18's finding "
|
||||
"that the loop has no SoC guard. SAFETY-25 part 10 now MEASURES "
|
||||
"it: one sustained-load evening, "
|
||||
f"{EVE_START:.0f} % -> {EV['end_soc']:.1f} % on the reference pack, "
|
||||
f"identical at every peak_soc_floor the schema accepts - and 10f "
|
||||
f"pins the claim-source set, so building the floor takes this "
|
||||
f"part RED instead of leaving this row quietly stale"))
|
||||
|
||||
for label, caught, where in MUT:
|
||||
print(f" {'caught' if caught else 'NOT CAUGHT':>10} {label}")
|
||||
@@ -1941,7 +2623,9 @@ check("...and so is the last one, which is not a defeat at all but the EDGE OF "
|
||||
"THIS CARD: the grid-following loop can still take the pack past this "
|
||||
"floor, because the floor bounds the peak guard's own forced discharge "
|
||||
"and a `lo` limit cannot cap a discharge. Saying so here is worth more "
|
||||
"than a green line that would be untrue", not MUT[12][1])
|
||||
"than a green line that would be untrue - and part 10 now says it with a "
|
||||
"number instead of a sentence, which is worth more again",
|
||||
not MUT[12][1] and EV["min_soc"] <= BMS_FLOOR + 0.05)
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
|
||||
@@ -34,6 +34,13 @@ TWO RULES THIS FILE HOLDS ITSELF TO, because the reviewer will:
|
||||
- the DST checks run on the 23-hour and 25-hour days, not on a normal
|
||||
24-hour day where a fixed-24-slot implementation and a correct one
|
||||
agree exactly.
|
||||
|
||||
⚠️ MUTATING THE MODULE THIS FILE GRADES? PURGE `__pycache__` FIRST - or run
|
||||
`tools/mutation_run.sh`, which does. `python3 -B` alone does NOT save you: it
|
||||
stops bytecode being WRITTEN, not a stale one being READ, and a size-preserving
|
||||
edit reverted inside one second is invisible to CPython's staleness test. That
|
||||
is TEST-15, and it has already turned one live mutation into a false survivor.
|
||||
Read MUTATION.md before you report a survivor.
|
||||
"""
|
||||
|
||||
import ast
|
||||
|
||||
@@ -48,6 +48,13 @@ THREE RULES THIS FILE HOLDS ITSELF TO, because the reviewer will:
|
||||
and a stale one is not a fresh one: the gate blocks on `no_data`, blocks on
|
||||
an hour the series does not cover, and blocks on a provisional hour - three
|
||||
different reasons, none of them an answer.
|
||||
|
||||
⚠️ MUTATING THE MODULE THIS FILE GRADES? PURGE `__pycache__` FIRST - or run
|
||||
`tools/mutation_run.sh`, which does. `python3 -B` alone does NOT save you: it
|
||||
stops bytecode being WRITTEN, not a stale one being READ, and a size-preserving
|
||||
edit reverted inside one second is invisible to CPython's staleness test. That
|
||||
is TEST-15, and it has already turned one live mutation into a false survivor.
|
||||
Read MUTATION.md before you report a survivor.
|
||||
"""
|
||||
|
||||
import ast
|
||||
|
||||
@@ -10,6 +10,11 @@ it:
|
||||
AC2 Fully-fixed pricing DISABLES ARBITRAGE and leaves self-consumption only.
|
||||
AC3 The Belgian scenario suite carries a static-profile regression case.
|
||||
|
||||
Section 9 is TEST-16 and is not one of those criteria. It pins the two
|
||||
`arbitrage()` rungs SAFETY-26's AC4 sweep found pinned from ONE SIDE ONLY -
|
||||
`spread == 0.0` and `len(firm) < 2` - and, more to the point, pins them so
|
||||
they stop MASKING EACH OTHER. Read its header before editing either rung.
|
||||
|
||||
THREE RULES THIS FILE HOLDS ITSELF TO, because the reviewer will:
|
||||
|
||||
* EVERY VERDICT IS DERIVED. No `check("the split is right", True)`. Where a
|
||||
@@ -45,6 +50,13 @@ THREE RULES THIS FILE HOLDS ITSELF TO, because the reviewer will:
|
||||
price, and zero is exactly the value that makes everything look free. So
|
||||
`static_plan` with no profile is checked to produce a read with NO
|
||||
`.points`, and `price_at` on it must RAISE rather than answer 0.0.
|
||||
|
||||
⚠️ MUTATING THE MODULE THIS FILE GRADES? PURGE `__pycache__` FIRST - or run
|
||||
`tools/mutation_run.sh`, which does. `python3 -B` alone does NOT save you: it
|
||||
stops bytecode being WRITTEN, not a stale one being READ, and a size-preserving
|
||||
edit reverted inside one second is invisible to CPython's staleness test. That
|
||||
is TEST-15, and it has already turned one live mutation into a false survivor.
|
||||
Read MUTATION.md before you report a survivor.
|
||||
"""
|
||||
|
||||
import gzip
|
||||
@@ -55,7 +67,7 @@ from pathlib import Path
|
||||
|
||||
from app.price import (
|
||||
Absence, PricePoint, PriceProduct, PriceRead, arbitrage_allowed, brussels,
|
||||
plan_is_provisional,
|
||||
plan_is_provisional, required_spread, uncertainty_of,
|
||||
)
|
||||
from app.static_tariff import (
|
||||
MEAN_WINDOW_DAYS, ProfileInvalid, StaticProfile, TariffPlan,
|
||||
@@ -853,6 +865,255 @@ check("...and main.py grew no `o.get(\"static_profile\", <a default>)` fallback
|
||||
'get("static_profile"' not in _MAIN and "static_status(" in _MAIN)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
print()
|
||||
print("9. TEST-16 - the two arbitrage rungs, pinned from BOTH sides and "
|
||||
"un-masked from each other")
|
||||
# SAFETY-26's AC4 gave the same tolerance mutation to every price and quantity
|
||||
# boundary in arbitrage.py and static_tariff.py. Everything in arbitrage.py went
|
||||
# red. The two survivors are the two rungs graded below, and section 2 above is
|
||||
# why they survived: it probes the flat rung with an EXACTLY FLAT series and
|
||||
# never probes the firm-pair rung at all.
|
||||
#
|
||||
# D `spread == 0.0` weakened to `spread <= 0.001` SURVIVED (+2 B). An
|
||||
# exactly flat series refuses under both spellings, so a tolerance is
|
||||
# invisible to a flat probe. It is NOT cosmetic: a real 0.0005 spread
|
||||
# flips ALLOWED -> REFUSED at min_spread_eur_kwh=0.0, which arbitrage()'s
|
||||
# own docstring documents as supported ("pass 0.0 to mean any positive
|
||||
# spread, explicitly") and which its validator at :861 accepts on purpose.
|
||||
#
|
||||
# F `len(firm) < 2` weakened to `< 1` SURVIVED, at +0 BYTES - the delta
|
||||
# MUTATION.md names as the risky one.
|
||||
#
|
||||
# ⚠️ AND THE FINDING IS THE INTERACTION, NOT EITHER ROW. D AND F MASK EACH
|
||||
# OTHER. A single firm hour has a spread of 0.0, so with F weakened the FLAT
|
||||
# rung catches the stimulus and the verdict is still "refused"; with D weakened
|
||||
# the tiny-spread stimulus is still refused, just for a lie. Each rung's failure
|
||||
# is absorbed by the other, so BOTH can be weakened together and a suite that
|
||||
# grades only `kind` reports nothing. That is invisible to single-mutation
|
||||
# testing, which is how this pair survived four rounds of review on TARIFF-03
|
||||
# and FCST-03.
|
||||
#
|
||||
# TWO THINGS FOLLOW, and they shape every check below.
|
||||
#
|
||||
# 1. THE REASON IS GRADED, NOT JUST THE REFUSAL. The masking case REFUSES
|
||||
# CORRECTLY WHILE REPORTING THE WRONG SENTENCE - an operator reading "the
|
||||
# tariff is flat" about a tariff that is not flat, or reading it about a
|
||||
# series whose real problem is that §8.3 has no firm pair to trade on. A
|
||||
# check that asserts only "refused" passes on a broken tree. So each
|
||||
# stimulus below is graded on WHICH RUNG ANSWERED IT.
|
||||
# 2. EACH RUNG NEEDS A STIMULUS THE OTHER CANNOT ABSORB, or the pinning is
|
||||
# circular. The flat rung gets a series with THREE firm hours, where the
|
||||
# firm-pair rung cannot fire under any weakening down to `< 0`. The
|
||||
# firm-pair rung gets a ONE-FIRM series, which the flat rung CAN answer -
|
||||
# so its attribution is the whole check, and that is why row 2 of the table
|
||||
# is written as a rung name rather than as a verdict.
|
||||
#
|
||||
# ⚠️ SHIPPED BEHAVIOUR IS UNCHANGED BY THIS SECTION. Both rungs are correct
|
||||
# today; nothing in app/ was touched. This is the missing measurement, not a fix.
|
||||
#
|
||||
# THE LEDGER. Eight rounds through `tools/mutation_run.sh` (TEST-15): recursive
|
||||
# `__pycache__` purge before each, `python3 -B`, the tree re-copied FROM DISK
|
||||
# between rounds, the mutated line grepped out of the file before the run, and
|
||||
# the byte delta printed. `test_static_tariff.py` and `test_arbitrage.py` graded
|
||||
# each time. Both suites green on the unmutated tree.
|
||||
#
|
||||
# round delta test_static_tariff.py
|
||||
# --------------------------------------------- ------ ---------------------
|
||||
# baseline, shipped +0 B PASS
|
||||
# D1 `spread == 0.0` -> `<= 0.001` +2 B RED, 3 checks
|
||||
# D2 `spread == 0.0` -> `<= 0.000001` +5 B RED, AC1 alone
|
||||
# D3 `spread == 0.0` -> `< 0.0` (rung gone) +0 B RED (section 2 too)
|
||||
# F1 `len(firm) < 2` -> `< 1` +0 B RED, 3 checks
|
||||
# F2 `len(firm) < 2` -> `< 3` +0 B RED, 6 checks
|
||||
# F3 `len(firm) < 2` -> `< 0` (rung gone) +0 B RED (and ValueError)
|
||||
# D1+F1 BOTH AT ONCE - THE TICKET +2 B RED, 5 checks
|
||||
#
|
||||
# Read the rows in pairs. D1 and F1 are SAFETY-26's two survivors and each is
|
||||
# now red on its own; D2 is the tolerance bisected to the rung's own resolution,
|
||||
# so "pinned at exactly zero" is measured rather than asserted at one epsilon;
|
||||
# F2 and F3 pin the firm-pair count from ABOVE and BELOW, which the ticket's
|
||||
# criteria do not ask for but which is what stops this section being one-sided
|
||||
# in the way it was written to fix. THE LAST ROW IS THE TICKET: with BOTH rungs
|
||||
# weakened together - the arrangement that reported nothing before this section
|
||||
# existed - five checks go red, including AC1 and AC2, because neither of them
|
||||
# is spelled in terms of the other rung's behaviour.
|
||||
#
|
||||
# ⚠️ FOUR OF THOSE SEVEN MUTATIONS ARE +0 BYTES, which MUTATION.md names as the
|
||||
# delta stale bytecode can hide. They are all REDS, the direction the bytecode
|
||||
# defect cannot fabricate - but they were run under the purge anyway, because
|
||||
# "it went red so the cache cannot have lied" is a conclusion, not a procedure.
|
||||
|
||||
_A9 = dict(peak_guard_active=False, min_spread_eur_kwh=0.0,
|
||||
uncertainty=frozenset())
|
||||
|
||||
|
||||
def plan9(prices, provisional=None, product=PriceProduct.DAY_AHEAD):
|
||||
"""A bare hourly series, built here rather than through a profile.
|
||||
|
||||
A `static_profile` cannot express a 0.0005 spread or a part-provisional day,
|
||||
and going through one would grade the profile generator as well. These are
|
||||
the smallest series that put exactly one rung in question.
|
||||
"""
|
||||
flags = provisional if provisional is not None else [False] * len(prices)
|
||||
pts = [PricePoint(start=brussels(THU + timedelta(hours=i)),
|
||||
eur_per_kwh=p, provisional=v)
|
||||
for i, (p, v) in enumerate(zip(prices, flags))]
|
||||
return TariffPlan(PriceRead.series(pts, product, "generic_dayahead", THU),
|
||||
None, "provider")
|
||||
|
||||
|
||||
def rung9(verdict):
|
||||
"""WHICH refusal answered, named from the reason the operator would read.
|
||||
|
||||
Deliberately not a code inspection: the sentence in the log IS the artefact
|
||||
that degrades when these two rungs mask each other, so it is the sentence
|
||||
that gets graded. An unrecognised refusal is reported as such rather than
|
||||
quietly matching nothing - "no rung fired" and "a rung I did not list fired"
|
||||
must not grade the same.
|
||||
"""
|
||||
if verdict.kind == "allowed":
|
||||
return "allowed"
|
||||
r = verdict.reason
|
||||
hit = [n for n, needle in (("flat", "the tariff is flat"),
|
||||
("firm-pair", "carry a published price"),
|
||||
("threshold", "needs"),
|
||||
("peak", "peak guard"),
|
||||
("no-series", "No series exists"))
|
||||
if needle in r]
|
||||
return hit[0] if len(hit) == 1 else f"UNATTRIBUTED<{r[:60]}>"
|
||||
|
||||
|
||||
# --- the sweep D survived: a small but REAL spread, at min_spread 0.0 --------
|
||||
# ⚠️ NOT AN EXACTLY FLAT SERIES, which is the whole point - a flat probe cannot
|
||||
# see a tolerance. The threshold is 0.0 so the `spread < need` rung below cannot
|
||||
# fire either (required_spread(0.0, anything) is 0.0, asserted first), leaving
|
||||
# the flat rung as the only thing that can refuse these.
|
||||
check(f"the widened threshold at min_spread_eur_kwh=0.0 is still 0.0, so the "
|
||||
f"probes below are graded by the FLAT rung and not by the threshold rung "
|
||||
f"({required_spread(0.0, uncertainty_of(PriceProduct.DAY_AHEAD)):.6f})",
|
||||
near(required_spread(0.0, uncertainty_of(PriceProduct.DAY_AHEAD)), 0.0))
|
||||
|
||||
# 1e-6 is the floor of the question, not of the check: app/static_tariff.py
|
||||
# rounds the spread to 6 decimals before comparing, so a 5e-7 difference IS
|
||||
# zero to this rung by construction. Graded as its own row below rather than
|
||||
# left as an unstated edge.
|
||||
TINY9 = (0.0005, 0.0001, 0.00001, 0.000001)
|
||||
_tiny9 = [(d, plan9([0.20000, round(0.20000 + d, 6)])) for d in TINY9]
|
||||
check(f"each tiny-spread probe really carries the spread it is named for, and "
|
||||
f"two FIRM hours - so the firm-pair rung cannot be what answers them "
|
||||
f"{[(f'{d:.6f}', f'{p.spread_eur_kwh():.6f}') for d, p in _tiny9]}",
|
||||
all(near(p.spread_eur_kwh(), d, 1e-12)
|
||||
and len([q for q in p.read.points if not q.provisional]) == 2
|
||||
for d, p in _tiny9))
|
||||
_tinyv9 = [(d, rung9(p.arbitrage(**_A9))) for d, p in _tiny9]
|
||||
check(f"TEST-16 AC1: a spread that is SMALL BUT REAL is ALLOWED at "
|
||||
f"min_spread_eur_kwh=0.0 - down to 0.000001 EUR/kWh, so the flat rung is "
|
||||
f"`spread == 0.0` and not `spread <= epsilon` for any epsilon "
|
||||
f"{_tinyv9}",
|
||||
all(r == "allowed" for _d, r in _tinyv9))
|
||||
check("...and the exactly flat series on the OTHER side of that boundary is "
|
||||
"still refused, and refused BY THE FLAT RUNG - without this the sweep "
|
||||
"above would also pass for a rung that had been deleted outright",
|
||||
rung9(plan9([0.20000, 0.20000]).arbitrage(**_A9)) == "flat")
|
||||
_q9 = plan9([0.20000, 0.2000005])
|
||||
check(f"...and a difference below the rung's own 6-decimal rounding is flat BY "
|
||||
f"CONSTRUCTION and says so: the raw difference is "
|
||||
f"{_q9.spread_eur_kwh():.7f} and non-zero, `round(..., 6)` makes it "
|
||||
f"exactly 0.0, and the rung agrees. That is the QUANTISATION the shipped "
|
||||
f"line chooses in the open, not a tolerance smuggled into the comparison "
|
||||
f"- and it is why the sweep above stops at 0.000001 rather than pretending "
|
||||
f"to bisect further",
|
||||
not near(_q9.spread_eur_kwh(), 0.0, 1e-9)
|
||||
and near(round(_q9.spread_eur_kwh(), 6), 0.0, 1e-12)
|
||||
and rung9(_q9.arbitrage(**_A9)) == "flat")
|
||||
|
||||
# --- and what D's survival actually costs: the sentence, not the verdict -----
|
||||
_lie9 = plan9([0.20000, 0.20050]).arbitrage(**_A9)
|
||||
check(f"TEST-16 AC4: the 0.0005 verdict carries the real spread rather than a "
|
||||
f"flatness claim about a tariff that is not flat - the false sentence is "
|
||||
f"what a loosened rung ships to the operator while the outcome at a "
|
||||
f"shipped threshold looks unchanged ({_lie9.kind})",
|
||||
_lie9.kind == "allowed" and near(_lie9.spread_eur_kwh, 0.0005)
|
||||
and near(_lie9.cheapest.eur_per_kwh, 0.20000)
|
||||
and near(_lie9.dearest.eur_per_kwh, 0.20050))
|
||||
|
||||
# --- the rung F survived: ON ITS OWN, not through the flat rung --------------
|
||||
# ⚠️ THIS ROW IS THE ANTI-MASKING ONE. A one-firm series has a spread of 0.0,
|
||||
# so with `< 2` weakened to `< 1` the FLAT rung refuses it and `kind` never
|
||||
# moves. The only thing that moves is the sentence: §8.3's honest "only 1 of 3
|
||||
# hours carry a published price" degrades to "the tariff is flat" about a series
|
||||
# whose firm and provisional prices differ by 0.20 EUR/kWh. Grading the rung
|
||||
# name is what makes `< 1` red without borrowing anything from the flat rung.
|
||||
_one9 = plan9([0.20, 0.40, 0.10], [False, True, True])
|
||||
check(f"the one-firm probe is well formed: exactly ONE firm hour out of three, "
|
||||
f"and its full series is anything but flat (spread "
|
||||
f"{max(p.eur_per_kwh for p in _one9.read.points) - min(p.eur_per_kwh for p in _one9.read.points):.2f} "
|
||||
f"EUR/kWh) - so 'flat' would be a false sentence about it",
|
||||
len([p for p in _one9.read.points if not p.provisional]) == 1
|
||||
and len(_one9.read.points) == 3)
|
||||
check("TEST-16 AC2: one firm hour is refused BY §8.3's FIRM-PAIR RUNG, named "
|
||||
"in the reason - not by the flat rung that would also have refused it. "
|
||||
"This is what takes `len(firm) < 2` -> `< 1` red on its own",
|
||||
rung9(_one9.arbitrage(**_A9)) == "firm-pair")
|
||||
check("...and the sentence is §8.3's in full, so the operator is told the "
|
||||
"series is half-published rather than told it is fixed-price",
|
||||
"§8.3" in _one9.arbitrage(**_A9).reason
|
||||
and "only 1 of 3" in _one9.arbitrage(**_A9).reason
|
||||
and "flat" not in _one9.arbitrage(**_A9).reason)
|
||||
# The rung pinned from ABOVE as well. Without this, `len(firm) < 3` - the same
|
||||
# +0 B edit in the other direction - would pass everything above.
|
||||
_two9 = plan9([0.20, 0.40, 0.10], [False, False, True])
|
||||
check("...and TWO firm hours are ALLOWED on the identical series shape, so the "
|
||||
"rung is pinned from above too and `< 3` is red as well as `< 1`",
|
||||
rung9(_two9.arbitrage(**_A9)) == "allowed"
|
||||
and near(_two9.arbitrage(**_A9).spread_eur_kwh, 0.20))
|
||||
# ...and from below, where the failure is not a wrong sentence but a crash:
|
||||
# `max()` over an empty `firm` raises ValueError, so `< 0` does not degrade the
|
||||
# reason, it takes the verdict away entirely.
|
||||
_zero9 = plan9([0.20, 0.40, 0.10], [True, True, True])
|
||||
check("...and a FULLY provisional series is refused by the same rung and does "
|
||||
"not raise - `max()` over an empty firm set is a ValueError, so this row "
|
||||
"is what makes `len(firm) < 0` red",
|
||||
rung9(derived(lambda: _zero9.arbitrage(**_A9))) == "firm-pair")
|
||||
|
||||
# --- AC3: the two rungs do not mask each other ------------------------------
|
||||
# ⚠️ THE POINT OF THE TICKET, AND IT IS A PROPERTY OF THE TABLE, NOT OF A ROW.
|
||||
# Masking is possible exactly when every stimulus that one rung answers could
|
||||
# also be answered by the other with an acceptable-looking result. The table
|
||||
# below denies that on both sides:
|
||||
#
|
||||
# * the flat rung is asked a question the firm-pair rung CANNOT reach - three
|
||||
# firm hours, where `len(firm) < N` refuses for no N a person would write;
|
||||
# * the firm-pair rung is asked a question the flat rung CAN reach - one firm
|
||||
# hour - and the answer is graded on WHICH rung gave it, so the flat rung
|
||||
# absorbing it is a failure rather than a pass;
|
||||
# * and the tiny-spread row is allowed, which neither rung may refuse.
|
||||
#
|
||||
# Verified by running BOTH mutations at once (`spread <= 0.001` AND
|
||||
# `len(firm) < 1`, purged harness, +2 B and +0 B): three rows move. Under
|
||||
# single-mutation testing this arrangement reports nothing at all.
|
||||
_TABLE9 = (
|
||||
("three firm hours, all 0.2000", plan9([0.2, 0.2, 0.2]), "flat"),
|
||||
("two firm hours, 0.0005 apart", plan9([0.20000, 0.20050]), "allowed"),
|
||||
("one firm hour of three", _one9, "firm-pair"),
|
||||
("two firm hours of three", _two9, "allowed"),
|
||||
("no firm hours at all", _zero9, "firm-pair"),
|
||||
)
|
||||
_got9 = [(name, want, rung9(derived(lambda p=pl: p.arbitrage(**_A9))))
|
||||
for name, pl, want in _TABLE9]
|
||||
check(f"TEST-16 AC3: each stimulus is answered by the rung that OWNS it, and "
|
||||
f"by no other - the flat rung is asked a question the firm-pair rung "
|
||||
f"cannot reach, and the firm-pair rung is asked one the flat rung could "
|
||||
f"reach but must not be allowed to. Weakening EITHER rung moves a row; "
|
||||
f"weakening BOTH TOGETHER still moves three "
|
||||
f"{[(n, w, g) for n, w, g in _got9]}",
|
||||
all(want == got for _n, want, got in _got9))
|
||||
check("...and the table really does exercise both rungs and the allowing path, "
|
||||
"so 'every row matched' is not a statement about one rung repeated",
|
||||
{want for _n, _p, want in _TABLE9} == {"flat", "firm-pair", "allowed"})
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
print()
|
||||
if fails:
|
||||
|
||||
@@ -35,16 +35,39 @@ NOT allowed to be tested at:
|
||||
10. THE WIRING, through the real `Controller` and its real status page.
|
||||
|
||||
------------------------------------------------------------------------------
|
||||
⚠️ AC 3 IS NOT MET, AND PART 9 DOES NOT PRETEND OTHERWISE.
|
||||
⚠️ PART 9 IS A TWO-DAY MEASUREMENT AND SAYS SO. THE 30-DAY ANSWER IS ELSEWHERE
|
||||
(DATA-01), AND IT DOES NOT LAND WHERE ANYONE EXPECTED.
|
||||
|
||||
AC 3 asks for "the monthly peak held under the soft limit in >= 95 % of
|
||||
intervals over a 30-day simulation replay". THERE IS NO 30-DAY DATASET. The
|
||||
infra repo's `sim/scenarios/` holds exactly two days of this house's real meter
|
||||
- 2026-08-20 (the Illusmart failure day) and 2026-08-23 (the healthy reference)
|
||||
- exported on 2026-08-25 because they were about to age out of HA's recorder,
|
||||
and nothing longer was ever captured. `sim/scenarios/README.md` lists the whole
|
||||
inventory; the rest is RS485 bus frames, OTA witness logs and a 578-row rollback
|
||||
poll, none of which carries grid power over calendar time.
|
||||
intervals over a 30-day simulation replay". When this file was written there
|
||||
were two days of this house's real meter - 2026-08-20 (the Illusmart failure
|
||||
day) and 2026-08-23 (the healthy reference) - exported on 2026-08-25 because
|
||||
they were about to age out of HA's recorder.
|
||||
|
||||
⚠️ AND THE SENTENCE THAT USED TO STAND HERE, "nothing longer was ever
|
||||
captured", WAS TRUE ABOUT THE PAST AND WAS READ AS A CLAIM ABOUT THE FUTURE.
|
||||
It was not one. HA's recorder still held the whole month; DATA-01 probed it on
|
||||
2026-08-31 (230 samples in a 20-minute window at 30 days back, 0 at 45) and
|
||||
exported thirty days the same day, into `scenarios/p1-net-30d-2026-08/` with
|
||||
`tools/export_p1_history.py` - which is committed now precisely because the
|
||||
2026-08-25 one-off was not, and its absence is what let the belief survive.
|
||||
|
||||
Over those thirty days the criterion measures 98.89 % UNCONTROLLED and 98.99 %
|
||||
guarded, so it is met - and that is a finding about the CRITERION as much as
|
||||
about the guard, because a month with no controller at all passes it. Read the
|
||||
other way - the monthly PEAK itself under the soft limit - it is not met: the
|
||||
guard takes August's peak from 5029.8 W to 4107.3 W, still over 3500 W. Both
|
||||
numbers, and why they part company, are in
|
||||
`scenarios/p1-net-30d-2026-08/README.md`.
|
||||
|
||||
PART 9 IS DELIBERATELY LEFT GRADING THE TWO COMMITTED DAYS. It is a per-PR
|
||||
regression check and the thirty days cost about fifty seconds of replay; they
|
||||
also live one directory down precisely so this file's glob does not pick them
|
||||
up. `tools/replay_ac3.py` is the thing that runs the month, and it is checked
|
||||
against part 6 of test_peakguard.py rather than trusted:
|
||||
|
||||
python3 tools/replay_ac3.py scenarios --expect 189/190
|
||||
python3 tools/replay_ac3.py scenarios/p1-net-30d-2026-08
|
||||
|
||||
So part 9 replays the two days that exist, reports the percentage over them, and
|
||||
states the sample size in days next to it. It is a MEASUREMENT, not a verdict:
|
||||
@@ -60,8 +83,15 @@ export) for the reason `scenarios/p1-age-2026-08-26.jsonl.gz` already is: the
|
||||
infra repo is private, CI's token is minted for this repository only, and a
|
||||
regression fixture that CI cannot see is not a regression fixture.
|
||||
|
||||
Closing AC 3 needs 30 days of capture. That is TEST-01's replay harness, and it
|
||||
cannot start before somebody starts recording.
|
||||
The recorder's window rolls: 2026-08-01 leaves it around 2026-09-15, which is
|
||||
why the committed copy is the artefact and not the API call.
|
||||
|
||||
⚠️ MUTATING THE MODULE THIS FILE GRADES? PURGE `__pycache__` FIRST - or run
|
||||
`tools/mutation_run.sh`, which does. `python3 -B` alone does NOT save you: it
|
||||
stops bytecode being WRITTEN, not a stale one being READ, and a size-preserving
|
||||
edit reverted inside one second is invisible to CPython's staleness test. That
|
||||
is TEST-15, and it has already turned one live mutation into a false survivor.
|
||||
Read MUTATION.md before you report a survivor.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
@@ -85,10 +115,16 @@ fails = []
|
||||
HERE = Path(__file__).resolve().parent
|
||||
TMP = Path(tempfile.mkdtemp(prefix="goodwe-tariff-"))
|
||||
|
||||
# The live install's numbers: NOTES.md and freeze.py both record max_w 5000
|
||||
# there. `peak_cap_w` ships at 3500 in config.yaml and is the SOFT LIMIT AC 3
|
||||
# grades against - read out of the shipped file in part 10 rather than typed.
|
||||
LIVE_MAX_W = 5000.0
|
||||
# ⚠️ NOT config.yaml's shipped max_w (2000). NOTES.md and freeze.py both record
|
||||
# that the LIVE INSTALL runs max_w 5000, and that is the number this file uses
|
||||
# as the device's power ceiling wherever it needs one - it is named
|
||||
# LIVE_INSTALL_MAX_W, not the shorter LIVE_MAX_W, precisely so it cannot be
|
||||
# misread as "the current shipped default" (TEST-10; test_freeze.py carries the identical
|
||||
# constant, under the identical name, for the identical reason - grep it there
|
||||
# for the pin that stops config.yaml's max_w from drifting under it unnoticed).
|
||||
# `peak_cap_w` ships at 3500 in config.yaml and is the SOFT LIMIT AC 3 grades
|
||||
# against - read out of the shipped file in part 10 rather than typed.
|
||||
LIVE_INSTALL_MAX_W = 5000.0
|
||||
|
||||
|
||||
def check(name, cond):
|
||||
@@ -268,7 +304,7 @@ CTRL_W = ctrl_closed[0].offtake_avg_w
|
||||
|
||||
# (b) restarted at minute 10, checkpoint restored through a real SQLite file.
|
||||
st = fresh_store("restart")
|
||||
tr = PeakTracker(st, cap_w=LIVE_MAX_W)
|
||||
tr = PeakTracker(st, cap_w=LIVE_INSTALL_MAX_W)
|
||||
a1 = QuarterAverager(phases=1, max_hold_s=MAX_HOLD_S)
|
||||
feed(a1, 0, RESTART_AT_S)
|
||||
check("the checkpoint round-trips through SQLite", st.save_partial(a1.snapshot()))
|
||||
@@ -305,7 +341,7 @@ OUTAGE_S = 200
|
||||
a4 = QuarterAverager(phases=1, max_hold_s=MAX_HOLD_S)
|
||||
st4 = fresh_store("outage")
|
||||
st4.save_partial(a1.snapshot())
|
||||
PeakTracker(st4, cap_w=LIVE_MAX_W).restore(a4, B + timedelta(seconds=RESTART_AT_S + OUTAGE_S))
|
||||
PeakTracker(st4, cap_w=LIVE_INSTALL_MAX_W).restore(a4, B + timedelta(seconds=RESTART_AT_S + OUTAGE_S))
|
||||
o_closed = feed(a4, RESTART_AT_S + OUTAGE_S, QUARTER_S)
|
||||
OUTAGE_UNCOVERED_S = OUTAGE_S - MAX_HOLD_S
|
||||
print(f" a {OUTAGE_S} s outage inside the quarter, of which "
|
||||
@@ -385,7 +421,7 @@ check("...so a new month starts from its OWN quarters, not from the previous "
|
||||
# The restart that straddles the boundary: a checkpoint whose open block is in
|
||||
# August, restored when `now` is already September.
|
||||
st7 = fresh_store("straddle")
|
||||
tr7 = PeakTracker(st7, cap_w=LIVE_MAX_W)
|
||||
tr7 = PeakTracker(st7, cap_w=LIVE_INSTALL_MAX_W)
|
||||
straddler = QuarterAverager(phases=1, max_hold_s=MAX_HOLD_S)
|
||||
for i in range(0, 400, STEP_S):
|
||||
straddler.add(sample(AUG_LATE + timedelta(seconds=i), RUN_W))
|
||||
@@ -413,17 +449,17 @@ print("5. AN UNREADABLE STORE IS NOT A ZERO PEAK (the acceptance argument)")
|
||||
|
||||
# Three stores, three states, and the three must not answer alike.
|
||||
good = fresh_store("states")
|
||||
good_tr = PeakTracker(good, cap_w=LIVE_MAX_W)
|
||||
good_tr = PeakTracker(good, cap_w=LIVE_INSTALL_MAX_W)
|
||||
empty_r = good_tr.peak(B)
|
||||
|
||||
gone = fresh_store("gone")
|
||||
gone_tr = PeakTracker(gone, cap_w=LIVE_MAX_W)
|
||||
gone_tr = PeakTracker(gone, cap_w=LIVE_INSTALL_MAX_W)
|
||||
gone.record_block(_CB(B, 3000.0, None))
|
||||
gone.close() # the database goes away under a live reader
|
||||
gone_r = gone_tr.peak(B)
|
||||
|
||||
never = PeakStore(str(TMP / "no-such-dir" / "x.db"))
|
||||
never_tr = PeakTracker(never, cap_w=LIVE_MAX_W)
|
||||
never_tr = PeakTracker(never, cap_w=LIVE_INSTALL_MAX_W)
|
||||
never_r = never_tr.peak(B)
|
||||
|
||||
# A store that is OPEN and whose query FAILS is a third code path - a closed
|
||||
@@ -433,7 +469,7 @@ broken = fresh_store("broken-table")
|
||||
broken.record_block(_CB(B, 3000.0, None))
|
||||
broken._db.execute("DROP TABLE monthly_peak")
|
||||
broken._db.commit()
|
||||
broken_r = PeakTracker(broken, cap_w=LIVE_MAX_W).peak(B)
|
||||
broken_r = PeakTracker(broken, cap_w=LIVE_INSTALL_MAX_W).peak(B)
|
||||
|
||||
for label, r in (("fresh store, no quarter yet", empty_r),
|
||||
("store that broke under a live reader", gone_r),
|
||||
@@ -483,26 +519,26 @@ check("PeakReading exposes no accessor that defaults a missing peak to a "
|
||||
if a.startswith(("get", "value")) or a.endswith("_or")])
|
||||
|
||||
# The consequence, which is the reason any of this matters.
|
||||
print(f" headroom under a {LIVE_MAX_W:.0f} W limit: "
|
||||
print(f" headroom under a {LIVE_INSTALL_MAX_W:.0f} W limit: "
|
||||
f"no quarter yet -> {good_tr.headroom_w(B)}, "
|
||||
f"unreadable -> {gone_tr.headroom_w(B)}")
|
||||
check("an unreadable store yields NO headroom figure - the disarming default "
|
||||
"(full headroom, guard silently off) is unreachable",
|
||||
gone_tr.headroom_w(B) is None and never_tr.headroom_w(B) is None)
|
||||
check(f"...where a genuinely empty month yields the full {LIVE_MAX_W:.0f} W, "
|
||||
check(f"...where a genuinely empty month yields the full {LIVE_INSTALL_MAX_W:.0f} W, "
|
||||
f"which is correct and is a different answer",
|
||||
near(good_tr.headroom_w(B), LIVE_MAX_W))
|
||||
near(good_tr.headroom_w(B), LIVE_INSTALL_MAX_W))
|
||||
check("the 80 % warning fraction is likewise None when nothing was observed",
|
||||
gone_tr.warning_frac(B) is None and good_tr.warning_frac(B) == 0.0)
|
||||
|
||||
# And a real peak reduces headroom, so "always None" does not pass this part.
|
||||
good.record_block(_CB(B, LIVE_MAX_W * 0.9, None))
|
||||
print(f" after one {LIVE_MAX_W * 0.9:.0f} W quarter: "
|
||||
good.record_block(_CB(B, LIVE_INSTALL_MAX_W * 0.9, None))
|
||||
print(f" after one {LIVE_INSTALL_MAX_W * 0.9:.0f} W quarter: "
|
||||
f"headroom {good_tr.headroom_w(B):.0f} W, "
|
||||
f"warning {good_tr.warning_frac(B) * 100:.0f} % of the limit")
|
||||
check("a real observed peak gives a real headroom, so this part is not passed "
|
||||
"by a store that answers None to everything",
|
||||
near(good_tr.headroom_w(B), LIVE_MAX_W * 0.1, 1e-6))
|
||||
near(good_tr.headroom_w(B), LIVE_INSTALL_MAX_W * 0.1, 1e-6))
|
||||
check(f"...and it is over §9.1's 80 % warning threshold",
|
||||
good_tr.warning_frac(B) > 0.8)
|
||||
|
||||
@@ -511,7 +547,7 @@ check(f"...and it is over §9.1's 80 % warning threshold",
|
||||
corrupt_path = TMP / "corrupt.db"
|
||||
corrupt_path.write_bytes(b"this is not a database" * 64)
|
||||
corrupt = PeakStore(str(corrupt_path))
|
||||
c_r = PeakTracker(corrupt, cap_w=LIVE_MAX_W).peak(B)
|
||||
c_r = PeakTracker(corrupt, cap_w=LIVE_INSTALL_MAX_W).peak(B)
|
||||
print(f" a corrupt database file -> {c_r.state}")
|
||||
check("a corrupt database reads NOT_OBSERVED and does not raise into the "
|
||||
"control loop (§6 fail-open)", c_r.state == NOT_OBSERVED)
|
||||
@@ -645,6 +681,65 @@ check(f"...and on a BALANCED load NET and SUM coincide ({b_vals[POLICY_NET]:.0f}
|
||||
f"so a balanced fixture could not have told them apart",
|
||||
near(b_vals[POLICY_NET], b_vals[POLICY_SUM], 1e-6))
|
||||
|
||||
# --- TEST-13 item 1: the POLICY ARGUMENT'S PLUMBING, not just billed_w() ------
|
||||
# `PeakStore.record_block(block, policy)` really does call `billed_w(block,
|
||||
# policy)` - the product code is correct and is not what this adds. What was
|
||||
# missing is that NO CHECK COULD TELL that call apart from a hardcoded
|
||||
# `billed_w(block, POLICY_NET)`. Mutating it to exactly that left all 17 suites
|
||||
# green, twice measured (TARIFF-01's reviewer, re-run through the purge harness
|
||||
# for TEST-15 and again here).
|
||||
#
|
||||
# The reason is this section's own subject, one level up. `billed_w()`
|
||||
# short-circuits to `block.offtake_avg_w` whenever `per_phase_offtake_avg_w` is
|
||||
# absent, and EVERY block that reached a store anywhere in this file was
|
||||
# single-phase or built with `per_phase_offtake_avg_w=None` - so all three
|
||||
# policies collapsed onto one number and the argument was unobservable at the
|
||||
# call site. The checks above grade the FUNCTION on an unbalanced fixture; they
|
||||
# say nothing about whether its CALLER forwards what it was handed. That is the
|
||||
# same shape as WITNESS-02's span normalisation and TARIFF-01's own DST window:
|
||||
# a stimulus evaluated where the quantity it grades is degenerate.
|
||||
#
|
||||
# So the stimulus here is `blk` - the unbalanced three-phase block from the top
|
||||
# of this section, whose three reductions were asserted three lines up to be
|
||||
# three DIFFERENT numbers. A `record_block()` that ignores its argument stores
|
||||
# one policy's figure under all three names and at least two of these
|
||||
# round-trips go red.
|
||||
#
|
||||
# Which direction the defect runs in, because that is what makes it worth
|
||||
# plumbing-testing at all: NET is the SMALLEST of the three on this fixture (the
|
||||
# exporting phase nets off against the other two). A store that silently billed
|
||||
# NET while its caller asked for MAX would under-record the month's peak, and an
|
||||
# under-recorded peak is maximum headroom for SAFETY-07 - the same
|
||||
# under-guarding direction as item 4's `getattr(..., 0.0)` default.
|
||||
_banked = {}
|
||||
for _pol in (POLICY_NET, POLICY_SUM, POLICY_MAX):
|
||||
_st = fresh_store(f"policy-{_pol}")
|
||||
_st.record_block(blk, _pol)
|
||||
_read = _st.peak(month=month_key(blk.start))
|
||||
_derived = _st.recompute_month(month_key(blk.start))
|
||||
_banked[_pol] = _read.peak_w
|
||||
check(f"record_block(block, {_pol!r}) banks {vals[_pol]:.0f} W - the store "
|
||||
f"applies the reduction it was HANDED, not one of its own",
|
||||
_read.is_observed and near(_read.peak_w, vals[_pol]))
|
||||
check(f"...and re-deriving from the 15-min tier gives the same {_pol!r} "
|
||||
f"figure, so BOTH writes in that one transaction used that reduction",
|
||||
_derived.is_observed and near(_derived.peak_w, vals[_pol]))
|
||||
|
||||
_st_def = fresh_store("policy-default")
|
||||
_st_def.record_block(blk)
|
||||
check(f"...and record_block() with NO policy argument banks the NET figure "
|
||||
f"({vals[POLICY_NET]:.0f} W), matching billed_w()'s own shipped default",
|
||||
near(_st_def.peak(month=month_key(blk.start)).peak_w, vals[POLICY_NET]))
|
||||
# The anti-degeneracy pin, stated over the BANKED numbers rather than over
|
||||
# `vals`, because it is the banked ones this triple is made of. If a future
|
||||
# fixture change ever made two of these coincide, the triple above would start
|
||||
# passing under a hardcoded policy and would be silently back where it started.
|
||||
print(f" banked through the store: "
|
||||
+ ", ".join(f"{k}={v:.0f} W" for k, v in _banked.items()))
|
||||
check("the three BANKED figures are three distinct numbers, so this triple is "
|
||||
"not itself degenerate - it can only pass if the argument is read",
|
||||
len({round(v, 6) for v in _banked.values() if v is not None}) == 3)
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
print()
|
||||
@@ -716,7 +811,7 @@ under = 0
|
||||
for path in REPLAY:
|
||||
st9 = fresh_store("replay-" + path.stem)
|
||||
ing = P1Ingest(phases=1, max_age_s=MAX_HOLD_S)
|
||||
tr9 = PeakTracker(st9, cap_w=SHIPPED_CAP_W or LIVE_MAX_W)
|
||||
tr9 = PeakTracker(st9, cap_w=SHIPPED_CAP_W or LIVE_INSTALL_MAX_W)
|
||||
first = last = None
|
||||
with gzip.open(path, "rt", encoding="utf-8") as fh:
|
||||
for line in fh:
|
||||
@@ -730,7 +825,7 @@ for path in REPLAY:
|
||||
span_h = (last - first).total_seconds() / 3600.0
|
||||
qs = [w for _, w in st9.blocks_in(sorted(months)[0])] if months else []
|
||||
peak = max(qs) if qs else 0.0
|
||||
ok_q = sum(1 for w in qs if w <= (SHIPPED_CAP_W or LIVE_MAX_W))
|
||||
ok_q = sum(1 for w in qs if w <= (SHIPPED_CAP_W or LIVE_INSTALL_MAX_W))
|
||||
total_q += len(qs)
|
||||
under += ok_q
|
||||
replay_days += span_h / 24.0
|
||||
@@ -748,9 +843,11 @@ print()
|
||||
print(f" AC 3 MEASURED: {under}/{total_q} quarters = {PCT:.1f} % under the "
|
||||
f"{SHIPPED_CAP_W:.0f} W soft limit, over {replay_days:.1f} DAYS of "
|
||||
f"replay, UNCONTROLLED (no peak shaving was running on either day).")
|
||||
print(f" AC 3 ASKS FOR 30 DAYS. {replay_days:.1f} days exist. "
|
||||
f"AC 3 IS NOT MET and this run does not claim it is - see the module "
|
||||
f"docstring. The figure above is the BASELINE SAFETY-07 has to improve.")
|
||||
print(f" AC 3 ASKS FOR 30 DAYS and this run is {replay_days:.1f}, so it "
|
||||
f"does not settle it either way. The 30 days DO now exist - "
|
||||
f"scenarios/p1-net-30d-2026-08/, DATA-01 - and "
|
||||
f"tools/replay_ac3.py is what runs them; the figure above is the "
|
||||
f"BASELINE SAFETY-07 has to improve, on the two days CI replays.")
|
||||
check("the replay produced a measurable number over a stated sample size, "
|
||||
"rather than a criterion quietly redefined to fit the data",
|
||||
total_q > 100 and replay_days < 30)
|
||||
@@ -783,7 +880,7 @@ class _Pub:
|
||||
|
||||
class _Hass:
|
||||
async def limits(self, entity):
|
||||
return (-LIVE_MAX_W, LIVE_MAX_W, 1.0)
|
||||
return (-LIVE_INSTALL_MAX_W, LIVE_INSTALL_MAX_W, 1.0)
|
||||
|
||||
async def number(self, entity, invert=False):
|
||||
return None
|
||||
@@ -799,7 +896,7 @@ def built(db_path, opts=None):
|
||||
return Controller(dict(
|
||||
{"setpoint_entity": "number.sp", "meter_source": "ha_signed",
|
||||
"p1_net_entity": "sensor.net", "meter_phases": 1,
|
||||
"max_w": LIVE_MAX_W, "gain": 0.6, "slew_w": 1000, "deadband_w": 15,
|
||||
"max_w": LIVE_INSTALL_MAX_W, "gain": 0.6, "slew_w": 1000, "deadband_w": 15,
|
||||
"target_grid_w": 0, "step_w": 10, "heartbeat_s": 10,
|
||||
"stale_input_s": 15}, **(opts or {})),
|
||||
_Hass(), _Store(), _Pub(), stop=asyncio.Event(),
|
||||
@@ -838,7 +935,12 @@ check("...and syncing the same quarter again banks nothing new, so the count "
|
||||
check("...and the peak is unchanged by the repeat",
|
||||
near(c.peak.peak(B).peak_w, 4998.0, 1e-6))
|
||||
|
||||
rows = [r for r in c.checks() if "capacity-tariff" in r["text"] or "peak" in r["text"]]
|
||||
# ⚠️ `when=B`, AND THAT ARGUMENT IS THE TICKET (TEST-17). Without it `checks()`
|
||||
# reads the peak for `datetime.now()`'s month while this fixture banked its
|
||||
# quarter in August, so every check below passed in August and failed from
|
||||
# 2026-09-01 - on a commit nobody had touched. The suite must grade the month
|
||||
# it created, not the month the machine happens to be running in.
|
||||
rows = [r for r in c.checks(when=B) if "capacity-tariff" in r["text"] or "peak" in r["text"]]
|
||||
peak_rows = [r for r in rows if "peak" in r["text"] and "quarter(s) banked" in r["text"]]
|
||||
print(" status row: " + (peak_rows[0]["text"] if peak_rows else "(none)"))
|
||||
check("the status page carries exactly one capacity-tariff peak row",
|
||||
@@ -854,7 +956,7 @@ check("...and it is FLAGGED, because 4998 W is over §9.1's 80 % warning point "
|
||||
|
||||
# The half that matters: the same page with a store that cannot answer.
|
||||
c2 = built(TMP / "no-such-dir" / "nope.db")
|
||||
u_rows = [r for r in c2.checks() if "capacity-tariff peak" in r["text"]]
|
||||
u_rows = [r for r in c2.checks(when=B) if "capacity-tariff peak" in r["text"]]
|
||||
print(" status row (unreadable store): "
|
||||
+ (u_rows[0]["text"] if u_rows else "(none)"))
|
||||
check("an unreadable store gets its OWN row, saying UNREADABLE", len(u_rows) == 1)
|
||||
@@ -866,6 +968,58 @@ check("...and the healthy row and the unreadable row are different text",
|
||||
bool(u_rows) and bool(peak_rows)
|
||||
and u_rows[0]["text"] != peak_rows[0]["text"])
|
||||
|
||||
# --- TEST-17: the page must be graded at a stated time, and prove it ----------
|
||||
# Three ways this can regress, so three checks. The first two would both go
|
||||
# green again if `checks()` quietly went back to reading the clock, which is
|
||||
# exactly the mutation this section could not previously detect.
|
||||
|
||||
# ⚠️ SELECTED ON "quarter(s) banked", NOT ON "peak". The NO_RECORD row reads
|
||||
# "2026-10: no completed quarter recorded yet - ..." and contains neither the
|
||||
# word "peak" nor "capacity-tariff" - only the UNREADABLE branch prefixes the
|
||||
# family name. Filtering these rows the way the checks above do would drop the
|
||||
# row and then grade its absence, which is the very mistake this ticket fixes.
|
||||
# (That asymmetry in the row's own text is worth a look on its own; it is what
|
||||
# made the original filter brittle. Not changed here - it is product text with
|
||||
# other suites reading it.)
|
||||
_peak_rows = lambda rows: [r for r in rows if "quarter(s) banked" in r["text"]]
|
||||
|
||||
_later = B + timedelta(days=45) # same fixture, a later billing month
|
||||
_other_peak = _peak_rows(c.checks(when=_later))
|
||||
print(f" the SAME controller read at {_later.date()}: "
|
||||
+ (_other_peak[0]["text"] if _other_peak else "(no peak row)"))
|
||||
check("asked for a LATER month, the same controller reports that month's "
|
||||
"absence of a quarter, not August's 4998 W - the row follows `when`",
|
||||
bool(_other_peak) and "4998 W" not in _other_peak[0]["text"]
|
||||
and "no completed quarter recorded yet" in _other_peak[0]["text"])
|
||||
check("...and that is NO_RECORD, distinguishable from BOTH an observed peak and "
|
||||
"an unreadable store - a month with no quarter is not a broken instrument",
|
||||
bool(_other_peak) and bool(peak_rows)
|
||||
and "UNREADABLE" not in _other_peak[0]["text"]
|
||||
and _other_peak[0]["text"] != peak_rows[0]["text"])
|
||||
check("...and it is not FLAGGED, because an empty month is not an exceedance",
|
||||
bool(_other_peak) and _other_peak[0]["ok"] and not _other_peak[0]["warn"])
|
||||
|
||||
# The mutation guard. `checks()` ignoring `when` is the whole defect, and it is
|
||||
# invisible to every check above whenever the machine's clock happens to sit in
|
||||
# the fixture's own month - which is how this shipped. Grading two DIFFERENT
|
||||
# reference months against each other cannot be satisfied by a clock at all.
|
||||
check("the peak row differs between two reference months, so a `checks()` that "
|
||||
"dropped `when` and read datetime.now() would fail HERE regardless of "
|
||||
"what day the suite is run on",
|
||||
bool(peak_rows) and bool(_other_peak)
|
||||
and peak_rows[0]["text"] != _other_peak[0]["text"])
|
||||
|
||||
# And the production meaning is unchanged: no argument still means today.
|
||||
_now_peak = _peak_rows(c.checks())
|
||||
_today_is_fixture_month = month_key(datetime.now(timezone.utc)) == month_key(B)
|
||||
check("calling checks() with NO argument still reads the month being billed "
|
||||
"today - the live status page's meaning is untouched",
|
||||
bool(_now_peak) and (bool(peak_rows)
|
||||
and _now_peak[0]["text"] == peak_rows[0]["text"]
|
||||
if _today_is_fixture_month
|
||||
else "no completed quarter recorded yet"
|
||||
in _now_peak[0]["text"]))
|
||||
|
||||
# THE MEASUREMENT IS OF DELIVERED POWER (SAFETY-20). Graded on the parsed
|
||||
# SYNTAX, not on the text: the module docstring argues this at length and names
|
||||
# every forbidden word while doing so, so a grep over the source would be
|
||||
@@ -881,24 +1035,106 @@ _names |= {n.name for n in _ast.walk(_tree)
|
||||
_FORBIDDEN = {"setpoint", "write_setpoint", "target", "Decision", "i_clamped",
|
||||
"clamped", "Claim", "resolve", "P_PEAK", "arbiter"}
|
||||
_found = sorted(_names & _FORBIDDEN)
|
||||
_imports = sorted(m.module or "" for m in _ast.walk(_tree)
|
||||
if isinstance(m, _ast.ImportFrom))
|
||||
|
||||
# ⚠️ THE IMPORT HALF WALKS `Import` TOO, AND READS THE IMPORTED NAMES - TEST-13
|
||||
# item 2. It used to be `m.module for m in walk(_tree) if isinstance(m,
|
||||
# ImportFrom)`, matched against a literal list of six spellings, and that is
|
||||
# blind to TWO OF PYTHON'S THREE import forms:
|
||||
#
|
||||
# * `from . import arbiter as _ab` is an `ImportFrom` whose `.module` is
|
||||
# **None** - the dots live in `.level` and the module name lives in
|
||||
# `.names` - so the old grader collected `""` and matched nothing;
|
||||
# * `import app.arbiter` is an `ast.Import` node, a different class the walk
|
||||
# filtered out entirely and therefore never looked at.
|
||||
#
|
||||
# Neither was a live exposure: the `_names` half above catches any USE of either
|
||||
# alias, because reaching anything through it produces an `Attribute` whose
|
||||
# `.attr` is a forbidden name. The defect was in the SENTENCE. A check that
|
||||
# prints "it imports nothing from arbiter, clamp or control" while verifying
|
||||
# that for one spelling out of three is worse than one that claims less, because
|
||||
# the next reader stops looking. So: collect every module any import statement
|
||||
# names, in all three forms, and match per dotted SEGMENT - `app.arbiter` and
|
||||
# `.arbiter` must not be able to hide behind a package prefix either.
|
||||
_FORBIDDEN_MODULES = {"arbiter", "clamp", "control"}
|
||||
|
||||
|
||||
def _imported_modules(tree):
|
||||
"""Every module path an import statement in `tree` names, all three forms."""
|
||||
out = set()
|
||||
for node in _ast.walk(tree):
|
||||
if isinstance(node, _ast.Import):
|
||||
# `import app.arbiter`, `import app.arbiter as x` - the whole
|
||||
# dotted path is the module.
|
||||
out |= {a.name for a in node.names}
|
||||
elif isinstance(node, _ast.ImportFrom):
|
||||
base = node.module or "" # None for `from . import arbiter`
|
||||
if base:
|
||||
out.add(base) # `from .arbiter import resolve`
|
||||
# ...and in the `module is None` form the MODULE is in .names, so
|
||||
# the names have to be joined on whether or not there is a base.
|
||||
out |= {f"{base}.{a.name}" if base else a.name for a in node.names}
|
||||
return out
|
||||
|
||||
|
||||
def _forbidden_imports(mods):
|
||||
# Segment-wise, not substring: `arbitrage` contains no forbidden segment and
|
||||
# must not be flagged, while `app.arbiter` must be.
|
||||
return sorted(m for m in mods
|
||||
if _FORBIDDEN_MODULES & {p for p in m.split(".") if p})
|
||||
|
||||
|
||||
_imports = sorted(_imported_modules(_tree))
|
||||
print(f" tariff.py evaluates {len(_names)} distinct names and imports "
|
||||
f"from {_imports or ['(stdlib only)']}")
|
||||
f"{sorted({m.split('.')[0] for m in _imports}) or ['(nothing)']}")
|
||||
check(f"none of them is a command-side name {sorted(_FORBIDDEN)} - the utility "
|
||||
f"bills what FLOWED, so this reads the meter and nothing else"
|
||||
+ (f"; found {_found}" if _found else ""), not _found)
|
||||
check("...and it imports nothing from arbiter, clamp or control: it files no "
|
||||
"claim, applies no clamp, and commands nothing - SAFETY-07's job",
|
||||
not [m for m in _imports if m in ("arbiter", "clamp", "control",
|
||||
".arbiter", ".clamp", ".control")])
|
||||
# ...and the guard is not vacuous: the same grader run over main.py, which DOES
|
||||
# command, must light up.
|
||||
_main = {n.attr for n in _ast.walk(
|
||||
_ast.parse((HERE / "app" / "main.py").read_text(encoding="utf-8")))
|
||||
if isinstance(n, _ast.Attribute)}
|
||||
check(f"the same grader over main.py finds {sorted(_main & _FORBIDDEN)}, so it "
|
||||
f"is capable of failing", bool(_main & _FORBIDDEN))
|
||||
check("...and it imports nothing from arbiter, clamp or control in ANY of the "
|
||||
"three import spellings: it files no claim, applies no clamp, and "
|
||||
"commands nothing - SAFETY-07's job",
|
||||
not _forbidden_imports(_imports))
|
||||
|
||||
# The import grader graded. Every one of these is a real way to reach the
|
||||
# command side from this module, and the first two are the ones the previous
|
||||
# version let through; the last two it already caught and must keep catching.
|
||||
_EVASIONS = ["from .arbiter import resolve",
|
||||
"from . import arbiter as _ab",
|
||||
"import app.arbiter",
|
||||
"from app.control import compute",
|
||||
"import app.clamp as _c"]
|
||||
_missed = [e for e in _EVASIONS
|
||||
if not _forbidden_imports(_imported_modules(_ast.parse(e)))]
|
||||
check(f"...and that import grader is not spelling-blind: all {len(_EVASIONS)} "
|
||||
f"ways of importing the command side are caught"
|
||||
+ (f"; MISSED {_missed}" if _missed else ""), not _missed)
|
||||
# ...and it is not simply flagging everything, which would make the line above
|
||||
# free. The last three are the reason the match is per SEGMENT and not `f in m`:
|
||||
# `clamps`, `arbiters` and `controller` all CONTAIN a forbidden word and none of
|
||||
# them is the command side. `controller` is not hypothetical - this package is
|
||||
# `goodwe_controller`, and a substring grader pointed at a path rather than a
|
||||
# module name would refuse the whole repository.
|
||||
_INNOCENT = ["import json", "from datetime import datetime, timezone",
|
||||
"from . import arbitrage", "from .price import Uncertainty",
|
||||
"from zoneinfo import ZoneInfo",
|
||||
"import clamps", "from .arbiters import x",
|
||||
"from . import controller"]
|
||||
_false = [i for i in _INNOCENT
|
||||
if _forbidden_imports(_imported_modules(_ast.parse(i)))]
|
||||
check("...and it does not fire on innocent imports whose names merely CONTAIN a "
|
||||
"forbidden word (`clamps`, `arbiters`, `controller`) - a substring match "
|
||||
"would have"
|
||||
+ (f"; FALSELY FLAGGED {_false}" if _false else ""), not _false)
|
||||
|
||||
# ...and neither half is vacuous: the same two graders run over main.py, which
|
||||
# DOES command, must both light up. main.py carries all three import forms.
|
||||
_main_tree = _ast.parse((HERE / "app" / "main.py").read_text(encoding="utf-8"))
|
||||
_main = {n.attr for n in _ast.walk(_main_tree) if isinstance(n, _ast.Attribute)}
|
||||
_main_imports = _forbidden_imports(_imported_modules(_main_tree))
|
||||
check(f"the same NAME grader over main.py finds {sorted(_main & _FORBIDDEN)}, "
|
||||
f"so it is capable of failing", bool(_main & _FORBIDDEN))
|
||||
check(f"...and the same IMPORT grader over main.py finds {_main_imports}, so "
|
||||
f"it is capable of failing on a real module and not only on a fixture",
|
||||
bool(_main_imports))
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
|
||||
@@ -5,11 +5,19 @@ three refusable configurations are refused. The second asserts that everything
|
||||
on validate.py's "deliberately not refused" list still STARTS - because the way
|
||||
a validator dies is not by missing a fault, it is by refusing something harmless
|
||||
until somebody deletes the call.
|
||||
|
||||
⚠️ MUTATING THE MODULE THIS FILE GRADES? PURGE `__pycache__` FIRST - or run
|
||||
`tools/mutation_run.sh`, which does. `python3 -B` alone does NOT save you: it
|
||||
stops bytecode being WRITTEN, not a stale one being READ, and a size-preserving
|
||||
edit reverted inside one second is invisible to CPython's staleness test. That
|
||||
is TEST-15, and it has already turned one live mutation into a false survivor.
|
||||
Read MUTATION.md before you report a survivor.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
|
||||
from app.maintenance import MAINT_OPTION_DEFAULTS, MaintConfig
|
||||
from app.validate import (
|
||||
ACTUATOR_WRITE_KEYS, FIRMWARE_INGEST_VETO_S, ConfigRefused, refuse,
|
||||
validate_startup_config,
|
||||
@@ -27,10 +35,16 @@ def check(name, cond):
|
||||
def base(**over):
|
||||
"""A configuration that must start. Everything else is this, spoilt."""
|
||||
# ⚠️ The maintenance rates are named EXPLICITLY, at the values config.yaml
|
||||
# ships (MAINT-04). They are not decoration: with the key absent, rule 6
|
||||
# falls back to main.py's 2500 W, which against this 2000 W ceiling is a
|
||||
# genuine refusal - so a base() without them would be a config that does
|
||||
# not start, and every check below would be measuring the wrong thing.
|
||||
# ships (MAINT-04). Under MAINT-04 that was load-bearing: with the key
|
||||
# absent, rule 6 fell back to a 2500 W literal that against this 2000 W
|
||||
# ceiling is a genuine refusal, so a base() without them was a config that
|
||||
# does not start and every check below would have been measuring the wrong
|
||||
# thing. CFG-03 closed that - the fallback is now config.yaml's own 2000 -
|
||||
# so they are here to say out loud what this fixture asks for rather than to
|
||||
# rescue it. The CFG-03 section at the foot of this file is what asserts
|
||||
# that absent and present are now THE SAME NUMBER; do not delete these two
|
||||
# keys, because a base() that agrees with the default by accident is a
|
||||
# fixture that cannot tell you when the default moves.
|
||||
o = {"setpoint_entity": "number.goodwe_setpoint", "max_w": 2000,
|
||||
"soc_entity": "sensor.soc", "batt_entity": "sensor.batt",
|
||||
"meter_source": "off",
|
||||
@@ -76,6 +90,40 @@ check("an unreachable device skips the range check rather than assuming",
|
||||
check("a non-numeric max_w is refused",
|
||||
why(validate_startup_config(base(max_w="lots"), -5000, 5000), "not a number"))
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 1b. SAFETY-20's AC4 decision, PINNED HERE RATHER THAN ONLY WRITTEN DOWN
|
||||
# --------------------------------------------------------------------------- #
|
||||
# AC4 asked whether a device rating that disarms SAFETY-18's freeze rail
|
||||
# additionally warrants a refusal of its own, the way `sign_disagree_w >= max_w`
|
||||
# is refused. THE ANSWER IS NO, AND THE REASON IS RULE 2 ABOVE: the configuration
|
||||
# is `max_w` above the device rating, which rule 2 already refuses on the
|
||||
# identical predicate. A rail-specific rule (`0.95 * max_w > dev_max`) would fire
|
||||
# on a strict SUBSET of what rule 2 refuses, so it could never be the rule that
|
||||
# stopped a start.
|
||||
#
|
||||
# ⚠️ THAT DECISION HAS A PREMISE, AND THIS IS THE PREMISE, EXECUTED. If rule 2 is
|
||||
# ever softened to a warning - which is exactly what main.py used to do before
|
||||
# CFG-01 - the reasoning recorded in validate.py's "deliberately not refused"
|
||||
# list silently stops being true, and SAFETY-18 is left with only its runtime
|
||||
# NOT COVERED row. Then somebody has to come back and re-decide AC4.
|
||||
from app.freeze import RAIL_FRAC # noqa: E402 - imported here, beside its use
|
||||
|
||||
_DEV = 4700.0 # the ticket's inverter
|
||||
_CEIL = 5000.0 # the ticket's configured ceiling
|
||||
check("SAFETY-20's premise: a rating below max_w disarms the freeze rail, so "
|
||||
f"{RAIL_FRAC:g} * max_w is unreachable on the ticket's install",
|
||||
_DEV < RAIL_FRAC * _CEIL)
|
||||
check("...and rule 2 REFUSES that whole configuration at startup, which is why "
|
||||
"SAFETY-20 added no rule of its own (AC4)",
|
||||
len(validate_startup_config(base(max_w=_CEIL), -_DEV, _DEV)) == 1)
|
||||
check("...on the rating side specifically, not incidentally through some other "
|
||||
"rule", why(validate_startup_config(base(max_w=_CEIL), -_DEV, _DEV),
|
||||
"THE DEVICE WINS"))
|
||||
check("...and the case the refusal CANNOT reach - the rating unread because "
|
||||
"ESPHome was not up - still starts, which is precisely why SAFETY-20's "
|
||||
"answer had to be a runtime status row and not a startup gate",
|
||||
validate_startup_config(base(max_w=_CEIL), None, None) == [])
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
print("2. an actuator to write to")
|
||||
# A controller with no actuator: write_setpoint() returns on the blank entity,
|
||||
@@ -338,74 +386,6 @@ check("...and a ceiling already past the billing quarter, so no value the "
|
||||
"schema still accepts can alarm inside the quarter that bills it",
|
||||
_hi is not None and _hi > _QUARTER_S)
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
print("the KNOWN cross-file default divergence, pinned rather than commented")
|
||||
# ⚠️ WHAT THIS GUARDS, AND WHY IT ASSERTS THE BUG RATHER THAN THE FIX.
|
||||
# config.yaml and validate.py now default maintenance_charge_w to 2000, while
|
||||
# main.py's two `opts.get(..., 2500)` fallbacks and MaintConfig's dataclass
|
||||
# default still say 2500. So an options dict with the key ABSENT is ACCEPTED by
|
||||
# rule 6 at 2000 and then built by main.py at 2500 - which is a contradiction:
|
||||
#
|
||||
# validate_startup_config -> [] (accepted)
|
||||
# MaintConfig().charge_w -> 2500.0
|
||||
# arbiter -> 0.0 W, contradiction=True
|
||||
#
|
||||
# That is the bug rule 6 exists to catch, passing rule 6. It is unreachable on a
|
||||
# Supervisor install (every key is always supplied from config.yaml) but fully
|
||||
# reachable from sim/inject.py and from tests - which is exactly where anyone
|
||||
# debugging maintenance works.
|
||||
#
|
||||
# The fix is ONE SOURCE OF TRUTH for option defaults. That is a bigger change
|
||||
# than this ticket and it lands in main.py, which another ticket is live in - so
|
||||
# the divergence is RECORDED here instead of closed. The check therefore passes
|
||||
# on the mismatch and FAILS when either side moves, in EITHER direction:
|
||||
#
|
||||
# - config.yaml moves -> FAIL: re-decide what the fallback should be
|
||||
# - main.py is fixed to match -> FAIL: the divergence is gone, DELETE this
|
||||
# check and the ⚠️ block in validate.py
|
||||
#
|
||||
# A comment cannot do that, and "a comment where a check belonged" is this
|
||||
# repo's most repeated defect.
|
||||
_APP = os.path.join(os.path.dirname(os.path.abspath(__file__)), "app")
|
||||
|
||||
def _read(*parts):
|
||||
with open(os.path.join(*parts), encoding="utf-8") as fh:
|
||||
return fh.read()
|
||||
|
||||
# Every literal fallback for this key in main.py, whatever the call shape.
|
||||
_main_falls = [float(m) for m in re.findall(
|
||||
r'\.get\(\s*"maintenance_charge_w"\s*,\s*(-?\d+(?:\.\d+)?)\s*\)',
|
||||
_read(_APP, "main.py"))]
|
||||
# ...and MaintConfig's own dataclass default, which is the one that bites when
|
||||
# main.py is bypassed entirely (a Maintenance built straight from defaults).
|
||||
_dc_falls = [float(m) for m in re.findall(
|
||||
r"^\s*charge_w:\s*float\s*=\s*(-?\d+(?:\.\d+)?)\s*$",
|
||||
_read(_APP, "maintenance.py"), re.M)]
|
||||
|
||||
check(f"main.py's fallbacks are still found and still 2500 {_main_falls}",
|
||||
len(_main_falls) == 2 and set(_main_falls) == {2500.0})
|
||||
check(f"MaintConfig's default is still found and still 2500 {_dc_falls}",
|
||||
len(_dc_falls) == 1 and set(_dc_falls) == {2500.0})
|
||||
check(f"...and config.yaml still ships 2000, so the divergence is UNCHANGED "
|
||||
f"(shipped {_shipped['maintenance_charge_w']:.0f}, code 2500)",
|
||||
_shipped["maintenance_charge_w"] == 2000.0)
|
||||
|
||||
# ⚠️ And the consequence itself, through the REAL code rather than through the
|
||||
# numbers above - so that if someone "fixes" this by changing a literal without
|
||||
# understanding it, the thing that goes red is the behaviour, not the transcript.
|
||||
from app.maintenance import MaintConfig # noqa: E402
|
||||
|
||||
_absent = {k: v for k, v in base().items() if k != "maintenance_charge_w"}
|
||||
_built = MaintConfig().charge_w
|
||||
check("with the key ABSENT the validator accepts...",
|
||||
validate_startup_config(_absent, -5000, 5000) == [])
|
||||
check(f"...while the code would build {_built:.0f} W against a "
|
||||
f"{_absent['max_w']:.0f} W ceiling...", _built > _absent["max_w"])
|
||||
_r = _charge(_absent["max_w"], _built)
|
||||
check("...which the arbiter resolves to 0 W as a contradiction - the hole, "
|
||||
"asserted so it cannot widen unnoticed",
|
||||
_r.target_w == 0.0 and _r.contradiction)
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
print("max_w must be a positive magnitude")
|
||||
# Schema-blocked on a real install, but validate_startup_config() is also
|
||||
@@ -566,6 +546,94 @@ try:
|
||||
except TypeError:
|
||||
check("a Controller with no stop Event is rejected at construction", True)
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
print("CFG-03: the key ABSENT is the SAME NUMBER everywhere, through real code")
|
||||
# ⚠️ WHAT THIS REPLACES, AND WHY IT IS THE OPPOSITE ASSERTION. MAINT-04 left a
|
||||
# TRIPWIRE here whose PASSING CONDITION WAS THE BUG: it asserted that
|
||||
# config.yaml said 2000 while main.py's two `opts.get(..., 2500)` fallbacks and
|
||||
# MaintConfig's dataclass default said 2500, and it went red if EITHER side
|
||||
# moved - including when somebody closed the divergence. That check has been
|
||||
# DELETED, as it and validate.py's ⚠️ block both instructed, and this is what
|
||||
# stands in its place: the same four consumers, exercised the same way, now
|
||||
# agreeing.
|
||||
#
|
||||
# The four are the four the defect ran through. The validator ACCEPTS a dict
|
||||
# with the key missing; main.py BUILDS a MaintConfig from that same dict; the
|
||||
# dataclass answers on its own with no dict at all; and the arbiter is what
|
||||
# turns their disagreement into a number an operator can see. Any three of them
|
||||
# agreeing was never the property that mattered.
|
||||
_absent = {k: v for k, v in base().items()
|
||||
if not k.startswith("maintenance_")}
|
||||
_ship_charge = _shipped["maintenance_charge_w"]
|
||||
_ship_drain = _shipped["maintenance_discharge_w"]
|
||||
|
||||
check("the validator still ACCEPTS a dict with every maintenance key missing - "
|
||||
"the fixture is the reachable one, not a refusal in disguise",
|
||||
validate_startup_config(_absent, -5000, 5000) == [])
|
||||
|
||||
# 1. the mirror against the shipped file. Read, not transcribed: a transcription
|
||||
# is the thing that drifted.
|
||||
check(f"the ONE in-code mirror equals what config.yaml ships "
|
||||
f"(charge {MAINT_OPTION_DEFAULTS['maintenance_charge_w']}, "
|
||||
f"shipped {_ship_charge:.0f})",
|
||||
float(MAINT_OPTION_DEFAULTS["maintenance_charge_w"]) == _ship_charge
|
||||
and float(MAINT_OPTION_DEFAULTS["maintenance_discharge_w"]) == _ship_drain)
|
||||
|
||||
# 2. MaintConfig on its own - the one that bites when main.py is bypassed
|
||||
# entirely, which is sim/inject.py and most of this suite.
|
||||
check(f"MaintConfig() answers the shipped number, not a third one "
|
||||
f"({MaintConfig().charge_w:.0f} W)",
|
||||
MaintConfig().charge_w == _ship_charge
|
||||
and MaintConfig().discharge_w == _ship_drain)
|
||||
|
||||
# 3. main.py's own path, through a real Controller rather than through a regex
|
||||
# over its source. A source scan can only say the literal is gone; this says
|
||||
# the object an operator's install actually runs on holds the right number.
|
||||
_ctl_absent = Controller(_absent, None, _Store2(), _Pub2(), stop=asyncio.Event())
|
||||
print(f" a Controller built from a dict with NO maintenance key: "
|
||||
f"charge_w={_ctl_absent.maint.cfg.charge_w:.0f} W, "
|
||||
f"discharge_w={_ctl_absent.maint.cfg.discharge_w:.0f} W")
|
||||
check("main.py builds the shipped number from a dict that does not contain it",
|
||||
_ctl_absent.maint.cfg.charge_w == _ship_charge
|
||||
and _ctl_absent.maint.cfg.discharge_w == _ship_drain)
|
||||
# ...and it is the SAME number when the operator supplies it explicitly, which
|
||||
# is what "the default is not a special case" means.
|
||||
_ctl_named = Controller(base(), None, _Store2(), _Pub2(), stop=asyncio.Event())
|
||||
check("...and an explicit key builds the identical config, so absent and "
|
||||
"present are not two code paths",
|
||||
_ctl_named.maint.cfg == _ctl_absent.maint.cfg)
|
||||
|
||||
# 4. the arbiter - the consequence itself. Under MAINT-04 this pair was
|
||||
# (2000, 2500) and resolved to 0 W with contradiction=True; that was the
|
||||
# ACCEPTED-then-contradicted hole. The rates come out of the built config,
|
||||
# not out of a literal, so if the single source moves this moves with it.
|
||||
_r_ok = _charge(float(_absent["max_w"]), _ctl_absent.maint.cfg.charge_w)
|
||||
print(f" arbiter with that config: {_r_ok.explain()}")
|
||||
check("the arbiter CHARGES instead of contradicting itself - the hole MAINT-04 "
|
||||
"pinned open is closed at the only place it was ever reachable",
|
||||
_r_ok.target_w == -_ship_charge and not _r_ok.contradiction)
|
||||
_r_drain = _drain(float(_absent["max_w"]), _ctl_absent.maint.cfg.discharge_w)
|
||||
check("...and the drain SET is not clamped either, so the twin key the card "
|
||||
"did not name is closed too",
|
||||
_r_drain.target_w == _ship_drain and not _r_drain.contradiction)
|
||||
|
||||
# 5. nothing typed a number behind the mirror's back. Rule 6's fallback and
|
||||
# main.py's are the two sites the divergence lived at, so they are the two
|
||||
# sites a scan is worth running over.
|
||||
_srcs = {name: open(os.path.join(os.path.dirname(os.path.abspath(__file__)),
|
||||
"app", name), encoding="utf-8").read()
|
||||
for name in ("main.py", "validate.py", "maintenance.py")}
|
||||
_literals = {name: re.findall(
|
||||
r'"(maintenance_[a-z_]+)"\s*,\s*(-?\d+(?:\.\d+)?)\s*[,)]', src)
|
||||
for name, src in _srcs.items()}
|
||||
check(f"no numeric fallback for any maintenance_* key survives in main.py, "
|
||||
f"validate.py or maintenance.py {_literals}",
|
||||
not any(_literals.values()))
|
||||
check("...and MaintConfig's dataclass defaults carry no numeric literal either "
|
||||
"- they are indexed out of the mirror",
|
||||
not re.search(r"^\s*(charge_w|discharge_w):\s*float\s*=\s*-?\d",
|
||||
_srcs["maintenance.py"], re.M))
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
print()
|
||||
if fails:
|
||||
|
||||
@@ -8,6 +8,13 @@ person switches it off.
|
||||
The headline validation is not here - it is `sim/replay_sign.py` in the infra
|
||||
repo, which drives this module over the two captured bus days. This file is the
|
||||
table-driven half: boundaries, timers, the latch, and the arming gate.
|
||||
|
||||
⚠️ MUTATING THE MODULE THIS FILE GRADES? PURGE `__pycache__` FIRST - or run
|
||||
`tools/mutation_run.sh`, which does. `python3 -B` alone does NOT save you: it
|
||||
stops bytecode being WRITTEN, not a stale one being READ, and a size-preserving
|
||||
edit reverted inside one second is invisible to CPython's staleness test. That
|
||||
is TEST-15, and it has already turned one live mutation into a false survivor.
|
||||
Read MUTATION.md before you report a survivor.
|
||||
"""
|
||||
|
||||
import sys
|
||||
@@ -204,13 +211,15 @@ TABLE = [
|
||||
Claim.limit("maintenance", P_MAINT_SHAPE, hi=0.0, reason="charge-only"),
|
||||
MAXW], 900, False),
|
||||
# ⚠️ THE CASE `winner == \"loop\"` ALONE WOULD HAVE GOT WRONG. 1500 W, not
|
||||
# the default 2500 W: at max_w 2000 a -2500 hi against a -2000 lo is an
|
||||
# arbiter contradiction, not a charge - see main.py.
|
||||
# 2500 W: at max_w 2000 a -2500 hi against a -2000 lo is an arbiter
|
||||
# contradiction, not a charge. That pair was the SHIPPED default until
|
||||
# MAINT-04 refused it and CFG-03 gave the default one source of truth; it is
|
||||
# kept below as a case rather than as a configuration.
|
||||
("cheap-window charge REDIRECTS the loop while it still 'wins'",
|
||||
[Claim.set("loop", P_LOOP, 500),
|
||||
Claim.limit("maintenance", P_MAINT_SHAPE, hi=-1500, reason="cheap-window"),
|
||||
MAXW], 500, False),
|
||||
("...and the contradiction at the shipped defaults is not following either",
|
||||
("...and the contradiction when charge_w exceeds max_w is not following either",
|
||||
[Claim.set("loop", P_LOOP, 500),
|
||||
Claim.limit("maintenance", P_MAINT_SHAPE, hi=-2500, reason="cheap-window"),
|
||||
MAXW], 500, False),
|
||||
|
||||
@@ -0,0 +1,455 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Export a P1 power signal out of Home Assistant's recorder into the committed
|
||||
scenario format - one gzipped JSON object per line, one file per LOCAL day.
|
||||
|
||||
WHY THIS FILE EXISTS AT ALL
|
||||
===========================
|
||||
`scenarios/p1-net-2026-08-20.jsonl.gz` and `p1-net-2026-08-23.jsonl.gz` were
|
||||
produced once, by hand, and the script was thrown away. The consequence was not
|
||||
theoretical: TARIFF-01's and SAFETY-07's AC 3 ("monthly peak held under the soft
|
||||
limit in >= 95 % of intervals over a 30-day simulation replay") were both merged
|
||||
UNMET on the belief that thirty days could not be produced retroactively - a
|
||||
belief that was simply wrong, and that survived because nobody could re-run the
|
||||
export to find out. So the export is a committed, runnable artefact now, and the
|
||||
next person does not have to re-derive it under time pressure while a retention
|
||||
window rolls.
|
||||
|
||||
python3 tools/export_p1_history.py --days 30 --out-dir /some/where
|
||||
|
||||
THE TWO RULES THIS FILE IS BUILT AROUND
|
||||
=======================================
|
||||
1. A FAILED READ IS NOT AN OBSERVATION. An HTTP error, a timeout, a truncated
|
||||
body, a non-JSON body - none of those are "the meter reported nothing that
|
||||
hour". They are "we do not know what the meter reported that hour", and the
|
||||
two must never end up looking the same in the output. So:
|
||||
|
||||
* every request is retried with backoff;
|
||||
* a day whose read ultimately fails writes NO FILE and is recorded in the
|
||||
manifest as `"read": "FAILED"` with the error text, and the process exits
|
||||
non-zero;
|
||||
* a day that reads back successfully but EMPTY writes an empty file and is
|
||||
recorded as `"read": "OK", "samples": 0`. Empty-and-known and
|
||||
unknown are therefore distinguishable both in the manifest and by the
|
||||
presence or absence of the file;
|
||||
* before any day is fetched, the entity is proved to exist through
|
||||
/api/states/<entity>. Without that check a typo in --entity would return
|
||||
200 + `[]` for all thirty days and produce a beautifully consistent
|
||||
dataset of nothing.
|
||||
|
||||
2. GAPS ARE VISIBLE, NEVER INTERPOLATED. Nothing here carries a value forward,
|
||||
fills, resamples or averages. A recorder outage or an HA restart shows up as
|
||||
what it is: consecutive `t` values further apart than the meter's cadence.
|
||||
The controller's own ingest already reads that correctly - `meter_max_age_s`
|
||||
(30 s shipped) is exactly the age past which a held reading stops counting as
|
||||
coverage - so an hour with no telegrams replays as an hour of NO COVERAGE
|
||||
rather than as an hour of whatever the last sample said. The manifest lists
|
||||
every gap over --gap-s so a reader does not have to diff timestamps to find
|
||||
them.
|
||||
|
||||
DAY AT A TIME, AND WHY NOT SMALLER
|
||||
==================================
|
||||
One request per local day. That is gentle on a live HA (~1 MB of JSON per day)
|
||||
and it is also the only chunking that reproduces the committed files: the
|
||||
history API prepends the state as it stood AT the period start
|
||||
(`include_start_time_state`), stamped with the start instant. Splitting a day
|
||||
into six-hour chunks would therefore inject three synthetic boundary samples per
|
||||
day that no meter ever sent. Days are the natural boundary because the committed
|
||||
files are local days.
|
||||
|
||||
VERIFYING THE EXPORTER
|
||||
======================
|
||||
python3 tools/export_p1_history.py --verify scenarios/p1-net-2026-08-20.jsonl.gz
|
||||
|
||||
re-fetches that day by this exact route and compares the DECOMPRESSED bytes with
|
||||
the committed file. Byte equality of the .gz containers is not expected and not
|
||||
required: a gzip header carries an mtime, and this file writes mtime 0 so its
|
||||
own output is reproducible. Content equality is the claim that matters.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import gzip
|
||||
import hashlib
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
|
||||
try: # py3.9+; the add-on image has it
|
||||
from zoneinfo import ZoneInfo
|
||||
except ImportError: # pragma: no cover
|
||||
ZoneInfo = None # type: ignore
|
||||
|
||||
DEFAULT_URL = "http://192.168.2.158:8123"
|
||||
DEFAULT_ENTITY = "sensor.p1_meter_active_power"
|
||||
DEFAULT_TZ = "Europe/Brussels"
|
||||
# The shipped meter_max_age_s. A hole longer than this is a hole the controller
|
||||
# itself would refuse to see through, which makes it the honest gap threshold.
|
||||
DEFAULT_GAP_S = 30.0
|
||||
|
||||
|
||||
class ReadFailed(RuntimeError):
|
||||
"""The read did not happen. NOT the same thing as an empty result."""
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# transport
|
||||
|
||||
|
||||
def _get(url: str, token: str, timeout: float):
|
||||
req = urllib.request.Request(url, headers={
|
||||
"Authorization": f"Bearer {token}",
|
||||
"Content-Type": "application/json",
|
||||
})
|
||||
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
||||
if resp.status != 200:
|
||||
raise ReadFailed(f"HTTP {resp.status}")
|
||||
return resp.read()
|
||||
|
||||
|
||||
def fetch_json(url: str, token: str, *, timeout: float, retries: int,
|
||||
backoff: float, log=print):
|
||||
"""GET and parse, or raise ReadFailed. Never returns a partial answer."""
|
||||
last = None
|
||||
for attempt in range(1, retries + 1):
|
||||
try:
|
||||
raw = _get(url, token, timeout)
|
||||
except urllib.error.HTTPError as exc:
|
||||
last = f"HTTP {exc.code} {exc.reason}"
|
||||
except Exception as exc: # URLError, timeout, ...
|
||||
last = f"{type(exc).__name__}: {exc}"
|
||||
else:
|
||||
try:
|
||||
return json.loads(raw.decode("utf-8")), len(raw), attempt
|
||||
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
|
||||
# A truncated body looks exactly like this. It is a failure.
|
||||
last = f"unparseable body ({len(raw)} bytes): {exc}"
|
||||
if attempt < retries:
|
||||
wait = backoff * attempt
|
||||
log(f" read failed ({last}); retry {attempt + 1}/{retries} "
|
||||
f"in {wait:.0f} s")
|
||||
time.sleep(wait)
|
||||
raise ReadFailed(last or "unknown")
|
||||
|
||||
|
||||
def assert_entity_exists(base: str, entity: str, token: str, *, timeout: float,
|
||||
retries: int, backoff: float, log=print):
|
||||
"""Prove the entity is real BEFORE trusting any empty day.
|
||||
|
||||
Without this, `--entity sensor.typo` answers 200 + [] for every day and the
|
||||
exporter cheerfully writes thirty empty files.
|
||||
"""
|
||||
url = f"{base}/api/states/{urllib.parse.quote(entity)}"
|
||||
doc, _, _ = fetch_json(url, token, timeout=timeout, retries=retries,
|
||||
backoff=backoff, log=log)
|
||||
if not isinstance(doc, dict) or doc.get("entity_id") != entity:
|
||||
raise ReadFailed(f"{entity} is not a known entity")
|
||||
return doc
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# one day
|
||||
|
||||
|
||||
def day_bounds(day: datetime, tz):
|
||||
start = datetime(day.year, day.month, day.day, tzinfo=tz)
|
||||
return start, start + timedelta(days=1)
|
||||
|
||||
|
||||
def history_url(base: str, entity: str, start: datetime, end: datetime) -> str:
|
||||
q = urllib.parse.urlencode({
|
||||
"filter_entity_id": entity,
|
||||
"end_time": end.isoformat(),
|
||||
"minimal_response": "",
|
||||
})
|
||||
return (f"{base}/api/history/period/"
|
||||
f"{urllib.parse.quote(start.isoformat())}?{q}")
|
||||
|
||||
|
||||
def rows_from(doc, entity: str):
|
||||
"""HA's shape -> [(iso_t, state_str)], plus the states that are not numbers.
|
||||
|
||||
`minimal_response` returns the first record in full and the rest as
|
||||
{state, last_changed}. An entity that went unavailable reports the string
|
||||
"unavailable" (or "unknown") where a number belongs. Those are dropped from
|
||||
the numeric series - there is no float to write and the committed schema has
|
||||
no slot for a non-number - but every one is returned here so it lands in the
|
||||
manifest. Dropping them is what MAKES the outage visible: the series simply
|
||||
has no samples across it, which is the same thing the meter falling silent
|
||||
looks like, and is what the controller's freshness rule already handles.
|
||||
"""
|
||||
if not isinstance(doc, list):
|
||||
raise ReadFailed(f"expected a list, got {type(doc).__name__}")
|
||||
if not doc:
|
||||
return [], []
|
||||
series = doc[0]
|
||||
if not isinstance(series, list):
|
||||
raise ReadFailed("history series is not a list")
|
||||
good, bad = [], []
|
||||
for rec in series:
|
||||
eid = rec.get("entity_id")
|
||||
if eid is not None and eid != entity:
|
||||
raise ReadFailed(f"unexpected entity {eid!r} in the response")
|
||||
t = rec.get("last_changed") or rec.get("last_updated")
|
||||
s = rec.get("state")
|
||||
if t is None:
|
||||
raise ReadFailed("a record carries no timestamp")
|
||||
try:
|
||||
w = float(s)
|
||||
except (TypeError, ValueError):
|
||||
bad.append({"t": t, "state": s})
|
||||
continue
|
||||
good.append((t, w))
|
||||
return good, bad
|
||||
|
||||
|
||||
def render(rows, *, newline: str) -> bytes:
|
||||
"""The committed format, exactly: `{"t": <iso>, "w": <float>}` per line.
|
||||
|
||||
json.dumps' default separators (", " / ": ") and repr of a float are what
|
||||
the two committed files contain; so is the CRLF, an artefact of the original
|
||||
one-off having been run on Windows in text mode. It is reproduced rather
|
||||
than tidied because reproducing the committed bytes is this exporter's
|
||||
verification, and gzip.open(..., 'rt') strips it either way.
|
||||
"""
|
||||
out = bytearray()
|
||||
for t, w in rows:
|
||||
out += json.dumps({"t": t, "w": w}).encode("utf-8")
|
||||
out += newline.encode("ascii")
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def gz(payload: bytes) -> bytes:
|
||||
"""gzip level 9, mtime 0 - so the same input always gives the same bytes."""
|
||||
import io
|
||||
buf = io.BytesIO()
|
||||
with gzip.GzipFile(fileobj=buf, mode="wb", compresslevel=9, mtime=0) as f:
|
||||
f.write(payload)
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def gaps_in(rows, gap_s: float):
|
||||
out = []
|
||||
prev = None
|
||||
for t, _ in rows:
|
||||
cur = datetime.fromisoformat(t)
|
||||
if prev is not None:
|
||||
d = (cur - prev).total_seconds()
|
||||
if d > gap_s:
|
||||
out.append({"from": prev.isoformat(), "to": cur.isoformat(),
|
||||
"seconds": round(d, 3)})
|
||||
prev = cur
|
||||
return out
|
||||
|
||||
|
||||
def export_day(base, entity, token, day, tz, *, timeout, retries, backoff,
|
||||
gap_s, newline, log=print):
|
||||
"""Read one local day. Raises ReadFailed rather than returning a guess."""
|
||||
start, end = day_bounds(day, tz)
|
||||
doc, nbytes, attempts = fetch_json(
|
||||
history_url(base, entity, start, end), token,
|
||||
timeout=timeout, retries=retries, backoff=backoff, log=log)
|
||||
rows, bad = rows_from(doc, entity)
|
||||
entry = {
|
||||
"date": day.date().isoformat(),
|
||||
"window": [start.isoformat(), end.isoformat()],
|
||||
"read": "OK",
|
||||
"http_bytes": nbytes,
|
||||
"attempts": attempts,
|
||||
"samples": len(rows),
|
||||
"non_numeric_states": bad,
|
||||
"first": rows[0][0] if rows else None,
|
||||
"last": rows[-1][0] if rows else None,
|
||||
"gaps": gaps_in(rows, gap_s),
|
||||
}
|
||||
if rows:
|
||||
span = (datetime.fromisoformat(rows[-1][0])
|
||||
- datetime.fromisoformat(rows[0][0])).total_seconds()
|
||||
entry["covered_span_s"] = round(span, 1)
|
||||
entry["mean_cadence_s"] = round(span / max(1, len(rows) - 1), 3)
|
||||
return rows, entry
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# modes
|
||||
|
||||
|
||||
def do_export(args, token, tz, log=print):
|
||||
base = args.url.rstrip("/")
|
||||
out_dir = Path(args.out_dir)
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
newline = "\r\n" if args.newline == "crlf" else "\n"
|
||||
|
||||
log(f" proving {args.entity} exists before trusting any empty day")
|
||||
st = assert_entity_exists(base, args.entity, token, timeout=args.timeout,
|
||||
retries=args.retries, backoff=args.backoff,
|
||||
log=log)
|
||||
log(f" {args.entity} = {st.get('state')} "
|
||||
f"{st.get('attributes', {}).get('unit_of_measurement', '')}")
|
||||
|
||||
if args.end_date:
|
||||
last = datetime.fromisoformat(args.end_date).replace(tzinfo=tz)
|
||||
else: # yesterday: today is still being logged
|
||||
last = datetime.now(tz).replace(hour=0, minute=0, second=0,
|
||||
microsecond=0) - timedelta(days=1)
|
||||
days = [last - timedelta(days=i) for i in range(args.days - 1, -1, -1)]
|
||||
|
||||
manifest = {
|
||||
"generated": datetime.now(timezone.utc).isoformat(),
|
||||
"generator": "tools/export_p1_history.py",
|
||||
"source": f"{base}/api/history/period",
|
||||
"entity": args.entity,
|
||||
"timezone": args.tz,
|
||||
"gap_threshold_s": args.gap_s,
|
||||
"format": '{"t": <ISO-8601 UTC>, "w": <float watts>} per line, gzip',
|
||||
"days": [],
|
||||
}
|
||||
failures = []
|
||||
for day in days:
|
||||
name = f"{args.prefix}{day.date().isoformat()}.jsonl.gz"
|
||||
log(f" {name}")
|
||||
try:
|
||||
rows, entry = export_day(
|
||||
base, args.entity, token, day, tz, timeout=args.timeout,
|
||||
retries=args.retries, backoff=args.backoff, gap_s=args.gap_s,
|
||||
newline=newline, log=log)
|
||||
except ReadFailed as exc:
|
||||
# NO FILE. A missing file is the honest record of a read that did
|
||||
# not happen; an empty one would claim the meter was silent.
|
||||
entry = {"date": day.date().isoformat(), "read": "FAILED",
|
||||
"error": str(exc), "file": None}
|
||||
manifest["days"].append(entry)
|
||||
failures.append(entry)
|
||||
log(f" READ FAILED: {exc} - no file written")
|
||||
continue
|
||||
payload = render(rows, newline=newline)
|
||||
blob = gz(payload)
|
||||
(out_dir / name).write_bytes(blob)
|
||||
entry["file"] = name
|
||||
entry["bytes_gz"] = len(blob)
|
||||
entry["bytes_raw"] = len(payload)
|
||||
entry["sha256_raw"] = hashlib.sha256(payload).hexdigest()
|
||||
entry["sha256_gz"] = hashlib.sha256(blob).hexdigest()
|
||||
manifest["days"].append(entry)
|
||||
ng = len(entry.get("gaps", []))
|
||||
log(f" {entry['samples']} samples, {len(blob)} B gz, "
|
||||
f"{ng} gap(s) over {args.gap_s:g} s"
|
||||
+ (f", {len(entry['non_numeric_states'])} non-numeric state(s)"
|
||||
if entry["non_numeric_states"] else ""))
|
||||
if day is not days[-1]:
|
||||
time.sleep(args.delay)
|
||||
|
||||
ok = [d for d in manifest["days"] if d["read"] == "OK"]
|
||||
manifest["summary"] = {
|
||||
"days_requested": len(days),
|
||||
"days_read": len(ok),
|
||||
"days_failed": len(failures),
|
||||
"samples": sum(d["samples"] for d in ok),
|
||||
"bytes_gz": sum(d["bytes_gz"] for d in ok),
|
||||
"empty_days": [d["date"] for d in ok if d["samples"] == 0],
|
||||
}
|
||||
# newline="\n" explicitly: write_text() on Windows emits CRLF, and
|
||||
# the manifest would then differ from a Linux run of the same export
|
||||
# for no reason visible in a diff.
|
||||
with open(args.manifest or (out_dir / "manifest.json"), "w",
|
||||
encoding="utf-8", newline="\n") as fh:
|
||||
fh.write(json.dumps(manifest, indent=2) + "\n")
|
||||
log(f" {manifest['summary']['days_read']}/{len(days)} days, "
|
||||
f"{manifest['summary']['samples']} samples, "
|
||||
f"{manifest['summary']['bytes_gz'] / 1e6:.2f} MB gz")
|
||||
if failures:
|
||||
log(f" {len(failures)} DAY(S) NOT READ - the dataset is incomplete "
|
||||
f"and says so: " + ", ".join(d["date"] for d in failures))
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
def do_verify(args, token, tz, log=print):
|
||||
"""Re-export a committed day by this route and diff it against the file."""
|
||||
base = args.url.rstrip("/")
|
||||
newline = "\r\n" if args.newline == "crlf" else "\n"
|
||||
rc = 0
|
||||
for target in args.verify:
|
||||
path = Path(target)
|
||||
stamp = path.name.split(".")[0].rsplit("-", 3)[-3:]
|
||||
day = datetime(int(stamp[0]), int(stamp[1]), int(stamp[2]), tzinfo=tz)
|
||||
log(f" {path.name} (local day {day.date().isoformat()})")
|
||||
committed = gzip.decompress(path.read_bytes())
|
||||
rows, entry = export_day(base, args.entity, token, day, tz,
|
||||
timeout=args.timeout, retries=args.retries,
|
||||
backoff=args.backoff, gap_s=args.gap_s,
|
||||
newline=newline, log=log)
|
||||
fresh = render(rows, newline=newline)
|
||||
if fresh == committed:
|
||||
log(f" IDENTICAL: {len(fresh)} bytes, {entry['samples']} "
|
||||
f"samples, sha256 {hashlib.sha256(fresh).hexdigest()[:16]}")
|
||||
continue
|
||||
rc = 1
|
||||
cl = committed.split(newline.encode())
|
||||
fl = fresh.split(newline.encode())
|
||||
log(f" DIFFERS: committed {len(committed)} B / {len(cl)} lines, "
|
||||
f"re-export {len(fresh)} B / {len(fl)} lines")
|
||||
shown = 0
|
||||
for i in range(max(len(cl), len(fl))):
|
||||
a = cl[i] if i < len(cl) else b"<absent>"
|
||||
b = fl[i] if i < len(fl) else b"<absent>"
|
||||
if a != b:
|
||||
log(f" line {i}: committed {a!r}")
|
||||
log(f" re-export {b!r}")
|
||||
shown += 1
|
||||
if shown >= args.max_diff:
|
||||
log(f" ... stopping after {shown} differing lines")
|
||||
break
|
||||
return rc
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
p = argparse.ArgumentParser(description=__doc__.split("\n")[0])
|
||||
p.add_argument("--url", default=DEFAULT_URL)
|
||||
p.add_argument("--entity", default=DEFAULT_ENTITY)
|
||||
p.add_argument("--token", help="bearer token; else $HASS_TOKEN")
|
||||
p.add_argument("--tz", default=DEFAULT_TZ,
|
||||
help="local timezone that defines a day boundary")
|
||||
p.add_argument("--days", type=int, default=30)
|
||||
p.add_argument("--end-date", help="last local day to export (YYYY-MM-DD); "
|
||||
"default yesterday")
|
||||
p.add_argument("--out-dir", default=".")
|
||||
p.add_argument("--prefix", default="p1-net-")
|
||||
p.add_argument("--manifest", help="path for the manifest JSON")
|
||||
p.add_argument("--gap-s", type=float, default=DEFAULT_GAP_S)
|
||||
p.add_argument("--newline", choices=("crlf", "lf"), default="crlf",
|
||||
help="line terminator; crlf reproduces the committed files")
|
||||
p.add_argument("--timeout", type=float, default=120.0)
|
||||
p.add_argument("--retries", type=int, default=4)
|
||||
p.add_argument("--backoff", type=float, default=5.0)
|
||||
p.add_argument("--delay", type=float, default=2.0,
|
||||
help="pause between days - this is a live HA")
|
||||
p.add_argument("--verify", nargs="+", metavar="FILE",
|
||||
help="re-export these committed days and diff them")
|
||||
p.add_argument("--max-diff", type=int, default=20)
|
||||
args = p.parse_args(argv)
|
||||
|
||||
token = args.token or __import__("os").environ.get("HASS_TOKEN")
|
||||
if not token:
|
||||
print("no token: pass --token or set HASS_TOKEN", file=sys.stderr)
|
||||
return 2
|
||||
if ZoneInfo is None:
|
||||
print("zoneinfo unavailable", file=sys.stderr)
|
||||
return 2
|
||||
tz = ZoneInfo(args.tz)
|
||||
try:
|
||||
if args.verify:
|
||||
return do_verify(args, token, tz)
|
||||
return do_export(args, token, tz)
|
||||
except ReadFailed as exc:
|
||||
print(f"read failed: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Executable
+95
@@ -0,0 +1,95 @@
|
||||
#!/bin/sh
|
||||
# The house mutation harness (TEST-15). `tools/mutation_run.sh [TREE] [test_*.py ...]`
|
||||
#
|
||||
# WHY THIS EXISTS. Nearly every safety claim in this repository was verified by
|
||||
# mutation: change the shipped module, run the suite, watch it go red, revert,
|
||||
# watch it go green. FCST-03's developer found that the middle two steps can be
|
||||
# a lie. CPython decides a `.pyc` is still valid from (source size, source mtime
|
||||
# TRUNCATED TO WHOLE SECONDS). Revert `self.provisional` to `here.provisional`
|
||||
# and neither term moves - same length, same second - so the interpreter loads
|
||||
# the bytecode it already has. Confirmed by disassembly: the source read `here`,
|
||||
# the running code loaded `self`. The mutation "survived" because it never ran.
|
||||
#
|
||||
# ⚠️ `python3 -B` IS NOT THE FIX, AND NEITHER IS PYTHONDONTWRITEBYTECODE=1.
|
||||
# Both stop bytecode being WRITTEN. Neither stops a stale `.pyc` that is already
|
||||
# on disk from being READ - measured, and graded by test_bytecode.py part 2.
|
||||
# The load-bearing half is the PURGE. `-B` is here so the run leaves no cache
|
||||
# behind for the NEXT mutation to inherit.
|
||||
#
|
||||
# ⚠️ NOT A SLEEP. One-second mtime resolution is the mechanism, not the enemy;
|
||||
# the answer is to stop trusting mtime, not to make every edit wait a second.
|
||||
# A sleep also only covers the edit you remembered to slow down.
|
||||
#
|
||||
# It prints a fingerprint of the tree it is about to grade, because the other
|
||||
# half of a mutation report is WHICH SOURCE produced it: a report that cannot
|
||||
# say what was on disk is the same unverifiable claim in a different dress.
|
||||
# Diff two fingerprints and the mutated file is the line that changed.
|
||||
set -eu
|
||||
|
||||
TREE=""
|
||||
case "${1-}" in
|
||||
"" ) : ;;
|
||||
-h|--help ) sed -n '2,30p' "$0"; exit 0 ;;
|
||||
* ) if [ -d "$1" ]; then TREE=$1; shift; fi ;;
|
||||
esac
|
||||
if [ -z "$TREE" ]; then
|
||||
# Default: the add-on directory this script ships in, so `tools/mutation_run.sh`
|
||||
# works from anywhere. An explicit TREE is what lets the infra repo's replay
|
||||
# harnesses purge $GOODWE_ADDON_REPO before they grade it - see MUTATION.md.
|
||||
TREE=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
fi
|
||||
PY=${PY:-python3}
|
||||
|
||||
cd "$TREE"
|
||||
|
||||
# CI-01's rule, for the same reason: a loop over an empty glob exits 0, and a
|
||||
# green run that examined nothing is worse than a red one.
|
||||
if [ $# -eq 0 ]; then set -- test_*.py; fi
|
||||
if [ ! -f "$1" ]; then
|
||||
echo "mutation_run: no test_*.py under $TREE - NOTHING has been graded." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "== purge"
|
||||
find . -name '__pycache__' -type d -prune -exec rm -rf {} + 2>/dev/null || true
|
||||
find . -name '*.pyc' -type f -exec rm -f {} + 2>/dev/null || true
|
||||
left=$(find . -name '__pycache__' -type d -o -name '*.pyc' -type f | head -5)
|
||||
if [ -n "$left" ]; then
|
||||
# A read-only tree cannot hold a cache written during this run either, so this
|
||||
# is only reachable when the purge itself failed on a tree that HAS one - the
|
||||
# one state where continuing would grade unknown bytecode.
|
||||
echo "mutation_run: could not purge, and a cache remains:" >&2
|
||||
echo "$left" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo " no bytecode cache under $TREE"
|
||||
|
||||
echo "== tree graded (sha256, bytes)"
|
||||
find app -name '*.py' 2>/dev/null | sort | while read -r f; do
|
||||
printf ' %s %8d %s\n' "$(sha256sum "$f" | cut -c1-16)" "$(wc -c < "$f")" "$f"
|
||||
done
|
||||
|
||||
echo "== run ($PY -B)"
|
||||
rc=0
|
||||
for f in "$@"; do
|
||||
start=$(date +%s)
|
||||
if "$PY" -B "$f" > /tmp/mutation_run.out 2>&1; then
|
||||
echo " PASS $f ($(( $(date +%s) - start ))s)"
|
||||
else
|
||||
echo " FAIL $f ($(( $(date +%s) - start ))s)"
|
||||
tail -40 /tmp/mutation_run.out
|
||||
rc=1
|
||||
fi
|
||||
done
|
||||
|
||||
# -B was asked for; check it was honoured rather than assuming. A cache here
|
||||
# would be inherited by the next mutation in the batch, which is exactly the
|
||||
# state this script exists to prevent.
|
||||
after=$(find . -name '__pycache__' -type d -o -name '*.pyc' -type f | head -5)
|
||||
if [ -n "$after" ]; then
|
||||
echo "mutation_run: a bytecode cache appeared DURING the run - the next" >&2
|
||||
echo "mutation in this batch would inherit it:" >&2
|
||||
echo "$after" >&2
|
||||
rc=1
|
||||
fi
|
||||
exit $rc
|
||||
@@ -0,0 +1,303 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run TARIFF-01's and SAFETY-07's AC 3 over a directory of `p1-net-*.jsonl.gz`.
|
||||
|
||||
AC 3, both cards, same words: *"monthly peak held under the soft limit in
|
||||
>= 95 % of intervals over a 30-day simulation replay."* Both cards merged with
|
||||
it UNMET because two days of capture existed. DATA-01 exported thirty. This is
|
||||
the thing that turns those thirty days into the number.
|
||||
|
||||
cd goodwe_controller
|
||||
python3 tools/replay_ac3.py scenarios/p1-net-30d-2026-08
|
||||
|
||||
WHAT IT MEASURES
|
||||
================
|
||||
Two runs over the same telegrams, one file at a time in date order into a
|
||||
SHARED peak store, so the 15-minute blocks accumulate into a real MONTH rather
|
||||
than into 30 disconnected days:
|
||||
|
||||
UNCONTROLLED the recorded meter as it happened. Nothing was shaving peaks on
|
||||
this house during August 2026, so this is not a simulation of
|
||||
anything - it is what the month did. It is TARIFF-01's AC 3.
|
||||
GUARDED the same month with `peakguard.decide()` in the loop and the
|
||||
battery it asks for modelled, closed-loop: the meter the guard
|
||||
sees is the recorded net MINUS the discharge it obtained. That
|
||||
is SAFETY-07's AC 3.
|
||||
|
||||
Both numbers are `quarters <= peak_cap_w` over `quarters closed`, with the cap
|
||||
read out of config.yaml rather than typed. Nothing here exits non-zero on 95 %:
|
||||
a measurement below the criterion is a finding about the house and the guard,
|
||||
and this tool's job is to report it, not to be graded by it.
|
||||
|
||||
FAITHFULNESS TO THE SUITE
|
||||
=========================
|
||||
The replay loop is `test_peakguard.py` part 6's, with `pack=None` (SoC pinned
|
||||
above the floor, so SAFETY-24's energy floor is not the thing deciding the
|
||||
answer). It is not imported from there because that file runs its whole suite on
|
||||
import. The duplication is checked instead of asserted: pointed at `scenarios/`
|
||||
- the two committed days - this tool must reproduce part 6's published totals,
|
||||
and `--expect` makes that a hard check.
|
||||
|
||||
python3 tools/replay_ac3.py scenarios --expect 189/190
|
||||
|
||||
GAPS
|
||||
====
|
||||
Nothing is interpolated. A hole in the export is a hole here: the shipped
|
||||
`meter_max_age_s` is what decides whether a held reading still counts as
|
||||
coverage, so an hour with no telegrams closes no quarters and contributes to
|
||||
neither numerator nor denominator. `--report-gaps` lists them.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import gzip
|
||||
import json
|
||||
import sys
|
||||
import tempfile
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
HERE = Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(HERE))
|
||||
|
||||
from app.p1 import P1Ingest, make_sample, split_signed # noqa: E402
|
||||
from app.peakguard import decide # noqa: E402
|
||||
from app.tariff import PeakStore, PeakTracker, month_key # noqa: E402
|
||||
|
||||
|
||||
def read_option(key: str):
|
||||
"""The shipped default for `key`, out of config.yaml.
|
||||
|
||||
⚠️ `peak_cap_w:` appears TWICE in config.yaml - once under `options:` with
|
||||
the default, once under `schema:` as `int(500,15000)`. The FIRST match is
|
||||
the options block, which is the number an install actually lands on; taking
|
||||
the last would try to float() the schema line. Same rule as the suites.
|
||||
"""
|
||||
for line in (HERE / "config.yaml").read_text(encoding="utf-8").splitlines():
|
||||
if line.strip().startswith(f"{key}:"):
|
||||
try:
|
||||
return float(line.split(":", 1)[1].strip())
|
||||
except ValueError:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def read_schema_max(key: str):
|
||||
for line in (HERE / "config.yaml").read_text(encoding="utf-8").splitlines():
|
||||
s = line.strip()
|
||||
if s.startswith(f"{key}:") and "(" in s and ")" in s:
|
||||
try:
|
||||
return float(s[s.index("(") + 1:s.index(")")].split(",")[-1])
|
||||
except ValueError:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def sample(t: datetime, net_w: float):
|
||||
"""One telegram through the SHIPPED sign derivation - the suites' helper."""
|
||||
imp, exp = split_signed(net_w)
|
||||
return make_sample("ha_signed", imp, exp, phases=1,
|
||||
ingest_ts=t, ingest_mono=t.timestamp())
|
||||
|
||||
|
||||
def rows(path):
|
||||
"""Every sample in one file, in order, with the gaps left as gaps."""
|
||||
with gzip.open(path, "rt", encoding="utf-8") as fh:
|
||||
for line in fh:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
row = json.loads(line)
|
||||
yield datetime.fromisoformat(row["t"]), float(row["w"])
|
||||
|
||||
|
||||
def replay(paths, *, guarded: bool, cap_w, max_w, max_hold_s, cycle_s,
|
||||
soc, soc_floor, tmp: Path, gap_s: float):
|
||||
"""test_peakguard.py part 6's loop, over an arbitrary number of days.
|
||||
|
||||
⚠️ ONE STORE, AND AN INGEST THAT IS RESET ONLY AT A REAL DISCONTINUITY.
|
||||
Neither half of that is a detail.
|
||||
|
||||
The STORE is shared across the files because "monthly peak" is what AC 3 is
|
||||
about and a per-file store cannot express it.
|
||||
|
||||
The INGEST is carried across a file boundary when the next file's first
|
||||
telegram follows the previous file's last one within `gap_s`, and rebuilt
|
||||
when it does not. Both failure modes are real and were measured here:
|
||||
|
||||
* carried across a genuine hole, one averager manufactures quarters out of
|
||||
nothing - streamed straight through the three-day gap between the two
|
||||
committed days this reported 285/286 where the suite reports 189/190;
|
||||
* rebuilt at every file, each day's LAST quarter (21:45-22:00 UTC) never
|
||||
closes, because it closes only when a telegram past the boundary
|
||||
arrives and that telegram is in the next file. That is why the suite's
|
||||
two days give 95 quarters each rather than 96, and it silently discards
|
||||
one quarter per day - 30 of them over a month.
|
||||
|
||||
So contiguous days are joined and non-contiguous ones are not, which gives
|
||||
189/190 on the committed pair and a full 96 quarters a day on a run of
|
||||
consecutive days.
|
||||
"""
|
||||
store = PeakStore(str(tmp / f"ac3-{'g' if guarded else 'u'}.db"))
|
||||
tracker = PeakTracker(store, cap_w=cap_w)
|
||||
engaged = blind = saturated = cycles = n = joins = 0
|
||||
wh = 0.0
|
||||
gaps = []
|
||||
months = set()
|
||||
ing = None
|
||||
batt = 0.0 # delivered discharge, W (positive)
|
||||
next_cycle = None
|
||||
prev_t = None
|
||||
for path in paths:
|
||||
for i, (t, w) in enumerate(rows(path)):
|
||||
if i == 0:
|
||||
contiguous = (prev_t is not None
|
||||
and 0 <= (t - prev_t).total_seconds() <= gap_s)
|
||||
if contiguous:
|
||||
joins += 1
|
||||
else:
|
||||
if ing is not None:
|
||||
months |= {month_key(b.start) for b in ing.blocks}
|
||||
ing = P1Ingest(phases=1, max_age_s=max_hold_s)
|
||||
batt = 0.0
|
||||
next_cycle = None
|
||||
prev_t = None
|
||||
if prev_t is not None:
|
||||
dt = (t - prev_t).total_seconds()
|
||||
if dt > gap_s:
|
||||
gaps.append((prev_t, t, dt))
|
||||
wh += batt * dt / 3600.0
|
||||
prev_t = t
|
||||
n += 1
|
||||
ing.submit(sample(t, w - batt))
|
||||
tracker.sync(ing)
|
||||
if next_cycle is not None and t < next_cycle:
|
||||
continue
|
||||
next_cycle = t + timedelta(seconds=cycle_s)
|
||||
cycles += 1
|
||||
d = decide(PeakTracker.project(ing.averager, t), batt_w=batt,
|
||||
cap_w=cap_w, reading=tracker.peak(t),
|
||||
achievable_w=max_w, max_hold_s=max_hold_s, soc=soc,
|
||||
soc_floor=soc_floor, frozen=False)
|
||||
if d.engaged:
|
||||
blind += 1 if d.blind else 0
|
||||
engaged += 0 if d.blind else 1
|
||||
saturated += 1 if d.saturated else 0
|
||||
if not guarded:
|
||||
continue
|
||||
engaged_floor = d.engaged and d.floor_w is not None
|
||||
batt = max(0.0, d.floor_w) if engaged_floor else 0.0
|
||||
if ing is not None:
|
||||
months |= {month_key(b.start) for b in ing.blocks}
|
||||
out = {m: dict(store.blocks_in(m)) for m in sorted(months)}
|
||||
return {"months": out, "samples": n, "cycles": cycles, "joins": joins,
|
||||
"engaged": engaged, "blind": blind, "saturated": saturated,
|
||||
"wh": wh, "gaps": gaps}
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
p = argparse.ArgumentParser(description=__doc__.split("\n")[0])
|
||||
p.add_argument("directory", help="a directory of p1-net-*.jsonl.gz")
|
||||
p.add_argument("--glob", default="p1-net-*.jsonl.gz")
|
||||
p.add_argument("--expect", help="UNDER/TOTAL the uncontrolled run must "
|
||||
"reproduce, e.g. 189/190")
|
||||
p.add_argument("--report-gaps", action="store_true")
|
||||
args = p.parse_args(argv)
|
||||
|
||||
paths = sorted(Path(args.directory).glob(args.glob))
|
||||
if not paths:
|
||||
print(f"no {args.glob} under {args.directory}", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
CAP_W = read_option("peak_cap_w")
|
||||
MAX_HOLD_S = read_option("meter_max_age_s")
|
||||
CYCLE_S = read_option("cycle_floor_s")
|
||||
SOC_FLOOR = read_option("peak_soc_floor")
|
||||
LIVE_MAX_W = read_schema_max("max_w")
|
||||
if None in (CAP_W, MAX_HOLD_S, CYCLE_S, SOC_FLOOR, LIVE_MAX_W):
|
||||
print("could not read the shipped options out of config.yaml",
|
||||
file=sys.stderr)
|
||||
return 2
|
||||
# The suites' fixture SoC: comfortably above the floor, so SAFETY-24's
|
||||
# energy floor is not what decides an AC 3 that is not about it.
|
||||
SOC_OK = SOC_FLOOR + 30.0
|
||||
|
||||
days = len(paths)
|
||||
span_first = span_last = None
|
||||
print(f"AC 3 - {days} file(s) from {args.directory}")
|
||||
print(f" shipped: peak_cap_w {CAP_W:.0f} W, meter_max_age_s "
|
||||
f"{MAX_HOLD_S:.0f} s, cycle_floor_s {CYCLE_S:.0f} s, "
|
||||
f"max_w schema ceiling {LIVE_MAX_W:.0f} W")
|
||||
|
||||
tmp = Path(tempfile.mkdtemp(prefix="goodwe-ac3-"))
|
||||
kw = dict(cap_w=CAP_W, max_w=LIVE_MAX_W, max_hold_s=MAX_HOLD_S,
|
||||
cycle_s=CYCLE_S, soc=SOC_OK, soc_floor=SOC_FLOOR, tmp=tmp,
|
||||
gap_s=MAX_HOLD_S)
|
||||
u = replay(paths, guarded=False, **kw)
|
||||
g = replay(paths, guarded=True, **kw)
|
||||
|
||||
def flat(run):
|
||||
return [w for m in run["months"].values() for w in m.values()]
|
||||
|
||||
uq, gq = flat(u), flat(g)
|
||||
u_under = sum(1 for w in uq if w <= CAP_W)
|
||||
g_under = sum(1 for w in gq if w <= CAP_W)
|
||||
u_pct = 100.0 * u_under / max(len(uq), 1)
|
||||
g_pct = 100.0 * g_under / max(len(gq), 1)
|
||||
|
||||
print(f" {u['samples']} samples, {len(uq)} closed quarters "
|
||||
f"({len(uq) / 96.0:.1f} days' worth), {days - u['joins']} contiguous "
|
||||
f"run(s) of days")
|
||||
for m in sorted(u["months"]):
|
||||
mu = u["months"][m]
|
||||
mg = g["months"].get(m, {})
|
||||
print(f" month {m}: {len(mu)} quarters, peak "
|
||||
f"{max(mu.values()):.1f} W uncontrolled -> "
|
||||
f"{max(mg.values()) if mg else 0.0:.1f} W guarded")
|
||||
print()
|
||||
print(f" TARIFF-01 AC 3 (UNCONTROLLED, what the month did): "
|
||||
f"{u_under}/{len(uq)} = {u_pct:.2f} % of quarters at or under "
|
||||
f"{CAP_W:.0f} W")
|
||||
print(f" SAFETY-07 AC 3 (GUARDED, peakguard.decide in the loop): "
|
||||
f"{g_under}/{len(gq)} = {g_pct:.2f} %")
|
||||
print(f" guard cycles {g['cycles']}, engaged on the measurement "
|
||||
f"{g['engaged']}, blind {g['blind']}, saturated {g['saturated']}, "
|
||||
f"modelled discharge {g['wh']:.0f} Wh")
|
||||
# AC 3'S WORDS SUPPORT TWO READINGS AND BOTH ARE REPORTED, because they
|
||||
# disagree on this data and picking the flattering one is the failure mode
|
||||
# this whole card exists to correct.
|
||||
u_peak = max(uq) if uq else 0.0
|
||||
g_peak = max(gq) if gq else 0.0
|
||||
print(f" reading A - PERCENTAGE OF INTERVALS under the cap (the reading "
|
||||
f"test_tariff.py part 9 already uses): uncontrolled {u_pct:.2f} %, "
|
||||
f"guarded {g_pct:.2f} %")
|
||||
print(f" reading B - THE MONTHLY PEAK ITSELF under the cap: "
|
||||
f"{u_peak:.1f} W uncontrolled -> {g_peak:.1f} W guarded, against a "
|
||||
f"{CAP_W:.0f} W soft limit "
|
||||
f"({'under' if g_peak <= CAP_W else 'STILL OVER'})")
|
||||
print(f" verdict at the 95 % criterion: uncontrolled "
|
||||
f"{'MEETS' if u_pct >= 95.0 else 'DOES NOT MEET'}, guarded "
|
||||
f"{'MEETS' if g_pct >= 95.0 else 'DOES NOT MEET'} "
|
||||
f"({len(uq) / 96.0:.1f} days of replay)")
|
||||
|
||||
if u["gaps"]:
|
||||
tot = sum(d for _, _, d in u["gaps"])
|
||||
print(f" gaps over {MAX_HOLD_S:.0f} s: {len(u['gaps'])}, "
|
||||
f"{tot:.0f} s total - NOT interpolated; the quarters they fall in "
|
||||
f"simply carry less coverage")
|
||||
if args.report_gaps:
|
||||
for a, b, d in u["gaps"]:
|
||||
print(f" {a.isoformat()} -> {b.isoformat()} {d:.0f} s")
|
||||
|
||||
if args.expect:
|
||||
want_u, want_t = (int(x) for x in args.expect.split("/"))
|
||||
ok = (u_under, len(uq)) == (want_u, want_t)
|
||||
print(f" reproduces test_peakguard.py part 6's published "
|
||||
f"{want_u}/{want_t}: {'yes' if ok else 'NO'} "
|
||||
f"(got {u_under}/{len(uq)})")
|
||||
return 0 if ok else 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user