TARIFF-15: your own tariff card, as two coefficients the card itself grades
checks / unit (pull_request) Successful in 7m14s

A Belgian dynamic contract prices energy as `B x index + A`, and the two
coefficients exist on exactly one artefact: the customer's own tariff card.
There is no machine-readable source for them anywhere - CREG's consumer
tariff-card pages 404, CREG Scan is a JS wizard, the annual report has the
supplier list without per-product coefficients, VREG was unreachable, and
every coefficient found in research came off a supplier's own PDF, one
image-only. So nothing can be scraped and a per-supplier plugin would have no
source for its numbers, which is why TARIFF-07 withdrew three of them. The
customer is the only party who can see their own coefficients; they type them.

New provider `custom_formula`, one new option `price_formula` (a JSON string,
the `static_profile` precedent exactly), and a new module
`app/custom_formula.py`. The index path is `generic_dayahead`'s, not a second
one: the URL/override decision is now one shared `dayahead_feed_url()` both
plugins call, same feed, same Brussels-calendar range, same columnar parser,
same declared egress hosts.

It declares {ENERGY, MARKUP}, NOT ALL_IN. A card's Tariefformule line is the
energy component alone - Eneco tabulates network tariffs and levies
separately, ENGIE states the formula excludes network, distribution,
transport, levies and excise - so ALL_IN would lie for every operator who
typed what their card says and would drop the taxes from every hour
(0.2125 -> 0.1555 EUR/kWh, measured).

THE CARD IS THE GRADER, and that is why this is safe to ship. The framework
already mechanises that a PLUGIN cannot double-count. This introduces a risk
none of those guards can see because it is config, not code: the OPERATOR
double-counting, by folding network charges into `offset` while
price_taxes_eur_kwh carries them too. So validate.py recomputes the card's own
printed price from the operator's coefficients at startup and refuses to start
unless the two agree to within 0.01, naming the discrepancy. An inflated
offset cannot pass: 15.55 becomes 28.27. The same check catches VAT omitted,
VAT doubled, a transposed digit and a unit mismatch between the two sides.

And the limit, in the same sentence as the claim: it grades the coefficients
against the card, NOT the card against reality. A consistent-but-wrong pair
passes. A second refusal covers the one unit error the first cannot see - the
one applied to both sides at once - by bounding the card's own point to
0.02-1.00 EUR/kWh. Its FLOOR is applied to the energy figure rather than the
all-in one because the shipped 0.06 of taxes is three times that floor and
would carry a hundredfold error over it alone; found by writing the mutation,
not by review (M10, +0 B).

The market's own arithmetic, reproduced through the shipped code:

  Eneco (0.102 x 133.9905 + 1) x 1.06 = 15.5471   card prints 15,55
  ENGIE (0.1   x  61.96   + 0.9) x 1.06 = 7.5218  card prints 7,522

NO EXPRESSION EVALUATION OF ANY KIND. The string is settable over HTTP through
the add-on's own ingress page, so eval on it is RCE in a root container
holding SUPERVISOR_TOKEN and driving an inverter over RS485 - but the deciding
argument is that an expression is UNVERIFIABLE: two coefficients can be graded
against the card, an arbitrary expression cannot be graded against anything,
so it would make the invisible-wrong-coefficient problem strictly worse. An
unknown field is REFUSED rather than ignored, so `"expr"` is told it does not
exist. Future shapes become named fields, never a grammar. test_price.py 15f
walks the module's AST for eval/exec/compile/__import__/literal_eval and
exercises the scanner's red direction on every run.

Refused at startup: card absent or out by >0.01; `units` absent (no default);
factor == 0 (every spread 0, arbitrage silently never fires - the message
points at static_profile); factor < 0 (inverts the market); vat_pct outside
0-30 (0 stays legitimate); non-finite or non-numeric; unknown field, index or
resolution; the plausibility band. A card older than ~6 months WARNS and does
not refuse - ENGIE freezes coefficients for a contract's duration. Negative
output prices are not refused anywhere.

A startup preview logs the next 24 h as `index EUR/MWh -> all-in EUR/kWh` with
min/median/max and the day's spread, through a new default-silent
`PriceProvider.startup_preview()` hook - only the plugin knows what went in to
its own arithmetic. Emitted once per process, and a preview that raises cannot
cost the site its prices.

`custom_formula` joins the config.yaml enum through the DERIVED set
PROVIDERS | RETIRED_PROVIDERS | {"off"}, not a hardcoded list. Both
translations describe the option and the new id. DOCS.md replaces the
"planned" sentence with the shape, a worked example from a real card, a real
startup transcript and the limit of the check stated beside the claim.

22 mutations, one per check added, no survivors - MUTATION.md carries the
ledger. M13 (the preview's index column) was a -13 B survivor of the whole
suite on the first attempt because the check graded the HEADING and not the
row; it is graded on a rendered row now. All 29 suites green.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BwRLw7eKYj2byVdwB6kbjU
This commit is contained in:
Claude Opus 5
2026-09-13 03:49:08 +02:00
parent aade2c79fd
commit ac9854886b
15 changed files with 2316 additions and 103 deletions
+632 -15
View File
@@ -69,6 +69,12 @@ from app.price import (
export_price_eur_kwh, load_prices, plan_is_provisional, register,
volatility_regime, uncertainty_of, widen_factor, Uncertainty,
)
from app.custom_formula import (
CARD_TOLERANCE, FormulaInvalid, INDEXES, PLAUSIBLE_HI_EUR_KWH,
PLAUSIBLE_LO_EUR_KWH, RESOLUTIONS, UNITS, card_discrepancy,
implausible_all_in, in_card_units, parse_price_formula, preview_lines,
price_eur_kwh, stale_card, to_resolution)
from app import custom_formula as _cf
from app import price as _price
from app import arbitrage as _arb
from app import main as _main
@@ -376,6 +382,27 @@ def columnar_feed(values, provisional_at=None, unit="EUR / MWh",
return json.dumps(doc).encode()
# TARIFF-15. THE TWO REAL TARIFF CARDS, as the operator would type them.
# ⚠️ THESE ARE NOT INVENTED. Both suppliers print the formula, the reference
# index they assumed AND the resulting price on the same card, so section 13
# can grade the SHIPPED code against a number somebody else published - which
# is the only kind of expectation this file is allowed to have (2b's rule,
# applied to arithmetic rather than to bytes).
ENECO_CARD = {"index": "epex_be", "resolution": "quarter_hourly",
"factor": 0.102, "offset": 1.00, "units": "c_eur_per_kwh",
"vat_pct": 6,
"card": {"month": "2026-09", "index_eur_per_mwh": 133.9905,
"expect_incl_vat": 15.55}}
ENGIE_CARD = {"index": "epex_be", "resolution": "quarter_hourly",
"factor": 0.100, "offset": 0.90, "units": "c_eur_per_kwh",
"vat_pct": 6,
"card": {"month": "2026-09", "index_eur_per_mwh": 61.96,
"expect_incl_vat": 7.522}}
# The energy+markup component of the shared EPEX fixture under Eneco's card,
# spelled out here as the card spells it: c EUR/kWh, then /100 to EUR/kWh.
FORMULA_EUR_KWH = [(0.102 * v + 1.00) * 1.06 / 100.0 for v in EPEX_EUR_MWH]
CSV_BODY = ("start,eur_per_kwh,provisional\n"
"2026-01-15T00:00:00+01:00,0.1834,false\n"
"2026-01-15T01:00:00+01:00,-0.0210,true\n"
@@ -390,12 +417,13 @@ CSV_BODY = ("start,eur_per_kwh,provisional\n"
FIXTURES = {
"generic_dayahead": (columnar_feed(EPEX_EUR_MWH),
[v / 1000 for v in EPEX_EUR_MWH]),
"custom_formula": (columnar_feed(EPEX_EUR_MWH), FORMULA_EUR_KWH),
"manual_csv": (None, [0.1834, -0.0210, 0.3115]),
}
check(f"the two plugins that survive TARIFF-07 are registered "
check(f"the plugins that ship after TARIFF-07 and TARIFF-15 are registered "
f"{sorted(PROVIDERS)}",
set(PROVIDERS) == {"generic_dayahead", "manual_csv"})
set(PROVIDERS) == {"generic_dayahead", "custom_formula", "manual_csv"})
check(f"...and the three withdrawn ids resolve to NOTHING "
f"{sorted(RETIRED_PROVIDERS)}",
set(RETIRED_PROVIDERS) == {"engie_dynamic", "totalenergies_dynamic",
@@ -453,6 +481,13 @@ def load_any(pid):
body, _ = FIXTURES[pid]
if pid == "manual_csv":
return load(pid, {"price_csv_path": CSV_PATH}, transport=refuse_transport)
if pid == "custom_formula":
# ⚠️ THE SAME BODY AS generic_dayahead, ON PURPOSE. Both read the same
# feed, so feeding them different bytes would hide the fact that what
# differs between them is the ARITHMETIC and the declaration - which
# is exactly what section 3 grades.
return load(pid, {"price_formula": json.dumps(ENECO_CARD)},
transport=canned(body))
return load(pid, transport=canned(body))
@@ -744,7 +779,11 @@ check("...and a feed announcing deprecated=true says so WHILE IT STILL WORKS - "
# sixth supplier cannot be added without this line noticing.
_networked = sorted(pid for pid, cls in PROVIDERS.items()
if cls.capabilities().egress_hosts)
_replayed = ["generic_dayahead"]
# ⚠️ TARIFF-15 PUT A SECOND PLUGIN ON THIS LIST AND IT IS REPLAYED FROM THE
# SAME CAPTURED BYTES (section 13c), because it reads the same endpoint with
# the same parser. A networked plugin with no capture is what this line exists
# to forbid.
_replayed = ["custom_formula", "generic_dayahead"]
check(f"the networked plugins are {_networked}, and EVERY one of them is "
f"replayed from a captured real body ({_replayed}) - no shipped plugin "
f"reaches a network this file has never seen answer (TARIFF-07)",
@@ -1012,9 +1051,9 @@ def _uses_range(cls):
_uses = sorted(pid for pid, cls in PROVIDERS.items() if _uses_range(cls))
check(f"the plugins that CONSUME their `since`/`until` are {_uses}; the rest "
f"take the range and ignore it, which is what TARIFF-09 fixed for "
f"generic_dayahead - and after TARIFF-07 the only one left that does not "
f"is the offline plugin, for the honest reason below",
_uses == ["generic_dayahead"])
f"generic_dayahead - and after TARIFF-07 and TARIFF-15 the only one left "
f"that does not is the offline plugin, for the honest reason below",
_uses == ["custom_formula", "generic_dayahead"])
check("...and `manual_csv` is honestly among the ones that do not: it reads a "
"whole file and the fill windows it downstream, so a range parameter "
"would have nowhere to go",
@@ -1094,21 +1133,29 @@ check(f"a negative day-ahead price passes through, all-in {_neg}",
# from it would mean feeding it an invented body carrying an invented flag,
# which is exactly the closed loop TARIFF-08 exists to remove. It is graded on
# what its real body can grade instead, immediately below.
for pid in sorted(set(READS) - {"generic_dayahead"}):
# ⚠️ `custom_formula` IS EXCLUDED FOR THE SAME REASON AND NOT FOR A NEW ONE
# (TARIFF-15): it reads the SAME columnar document, which has no per-point
# flag, and applies arithmetic to it - arithmetic cannot invent a provenance
# the document never carried.
_SETTLED_FEED = {"generic_dayahead", "custom_formula"}
for pid in sorted(set(READS) - _SETTLED_FEED):
read = READS[pid]
flags = derived(lambda r=read: [p.provisional for p in r.points])
check(f"{pid}: provisional is per point and mixed {flags}",
isinstance(flags, list) and any(flags) and not all(flags))
check(f"...so plan_is_provisional is derived from those points",
derived(lambda r=read: plan_is_provisional(r)) is True)
_gen_flags = derived(lambda: [p.provisional
for p in READS["generic_dayahead"].points])
check(f"generic_dayahead's settled auction comes out settled at every point "
f"{_gen_flags}",
isinstance(_gen_flags, list) and len(_gen_flags) == len(EPEX_EUR_MWH)
and not any(_gen_flags))
check("...so plan_is_provisional is False for it, derived from the same points",
derived(lambda: plan_is_provisional(READS["generic_dayahead"])) is False)
for pid in sorted(_SETTLED_FEED):
_gen_flags = derived(lambda p=pid: [pt.provisional
for pt in READS[p].points])
check(f"{pid}'s settled auction comes out settled at every point "
f"{_gen_flags}",
isinstance(_gen_flags, list)
and len(_gen_flags) == len(EPEX_EUR_MWH)
and not any(_gen_flags))
check(f"...so plan_is_provisional is False for {pid}, derived from the "
f"same points",
derived(lambda p=pid: plan_is_provisional(READS[p])) is False)
# ...and the same function says False when nothing is provisional. Without this
# arm, "always True" would pass every check above.
_settled = PriceRead.series(
@@ -3150,6 +3197,576 @@ check("...and it never invents a neighbour: the instant one second before the "
for _d in _tmpdirs_t10:
shutil.rmtree(_d, ignore_errors=True)
# --------------------------------------------------------------------------- #
print()
print("15. TARIFF-15 - the operator's own tariff card, as two coefficients")
#
# WHAT THIS SECTION IS DEFENDING. `custom_formula` lets an operator type the
# `B x index + A` line off their own supplier's tariff card, because there is
# no machine-readable source of Belgian tariff coefficients anywhere and the
# customer is the only party who can see their own. That makes the card the
# ONLY artefact that can grade them - which is exactly what the startup check
# does, and what the checks below grade it doing.
#
# ⚠️ EVERY EXPECTATION HERE IS SOMEBODY ELSE'S PUBLISHED NUMBER. The two cards
# print the formula, the reference index they assumed AND the resulting price,
# so this file compares the SHIPPED code against 15,55 and 7,522 rather than
# against its own restatement of the same arithmetic. That is section 2b's
# rule - grade against something nobody here wrote - applied to arithmetic.
print()
print("15a. the two REAL cards reproduce their PRINTED prices, through the "
"shipped code")
# ⚠️ NON-DEGENERACY FIRST (habit 1). Two cards that agreed on every field
# would be one card counted twice, and the pair is what says the arithmetic is
# general rather than tuned to one supplier.
check(f"the two cards really are two - factor {ENECO_CARD['factor']} vs "
f"{ENGIE_CARD['factor']}, offset {ENECO_CARD['offset']} vs "
f"{ENGIE_CARD['offset']}, index "
f"{ENECO_CARD['card']['index_eur_per_mwh']} vs "
f"{ENGIE_CARD['card']['index_eur_per_mwh']}",
ENECO_CARD["factor"] != ENGIE_CARD["factor"]
and ENECO_CARD["offset"] != ENGIE_CARD["offset"]
and ENECO_CARD["card"]["index_eur_per_mwh"]
!= ENGIE_CARD["card"]["index_eur_per_mwh"]
and ENECO_CARD["card"]["expect_incl_vat"]
!= ENGIE_CARD["card"]["expect_incl_vat"])
# The suppliers' own printed prices, transcribed from the cards and from
# nowhere in app/.
PRINTED = {"Eneco (0.102 x 133.9905 + 1) x 1.06": (ENECO_CARD, 15.55),
"ENGIE (0.1 x 61.96 + 0.9) x 1.06": (ENGIE_CARD, 7.522)}
for _what, (_card, _printed) in sorted(PRINTED.items()):
_spec = derived(lambda c=_card: parse_price_formula(json.dumps(c)))
_got = derived(lambda sp=_spec: in_card_units(
sp, sp.card_index_eur_per_mwh))
check(f"{_what} = {_got} c EUR/kWh through the shipped module, which "
f"rounds to the {_printed} the card prints",
isinstance(_got, float)
and round(_got, len(str(_printed).split('.')[-1])) == _printed)
# ...and the same two cards end to end through `load_prices()`, i.e. through
# the registered plugin, the columnar parser and `assemble()` - not through a
# module function this file called directly. The feed body carries the card's
# OWN index value, so the point that comes out must be the card's own printed
# price in EUR/kWh plus the framework's taxes and nothing else.
for _what, (_card, _printed) in sorted(PRINTED.items()):
_idx = _card["card"]["index_eur_per_mwh"]
_read = derived(lambda c=_card, i=_idx: load(
"custom_formula", {"price_formula": json.dumps(c)},
transport=canned(columnar_feed([i]))))
_all_in = derived(lambda r=_read: r.points[0].eur_per_kwh)
_want = round(_printed / 100.0 + TAXES, 6)
check(f"{_what}: end to end through load_prices() the hour comes out at "
f"{_all_in} EUR/kWh all-in, which is the card's printed "
f"{_printed} c EUR/kWh plus price_taxes_eur_kwh and nothing else",
isinstance(_all_in, float) and abs(_all_in - _want) < 5e-5)
print()
print("15b. the card self-check REFUSES at startup, naming the discrepancy")
# ⚠️ THIS IS THE WHOLE SAFETY ARGUMENT AND IT IS GRADED ON THE REASON, NOT THE
# VERDICT (MUTATION.md, TEST-16). Several rules here can refuse the same blob -
# a wrong `units`, a missing key, a bad number - so a check that only asked
# "was it refused" would pass on a tree where the card comparison is deleted.
def spoilt(**over):
"""Eneco's card with one field replaced. Everything else is the real one."""
c = json.loads(json.dumps(ENECO_CARD))
for k, v in over.items():
if k.startswith("card_"):
c["card"][k[5:]] = v
else:
c[k] = v
return c
def refusal(blob):
return _reason(lambda: parse_price_formula(json.dumps(blob)))
_honest = refusal(ENECO_CARD)
check("the CONTROL first: the real card is NOT refused, or every refusal "
"below would be graded against a rule that refuses everything",
_honest == "")
# ⚠️ THE EXPENSIVE ONE, AND THE REASON THIS PROVIDER IS SAFE TO SHIP. A
# Belgian card's Tariefformule line is the ENERGY component alone; the add-on
# adds price_taxes_eur_kwh on top. An operator who folds ~12 c EUR/kWh of
# network charge into `offset` is billed for it twice, and `code_leaks()`
# cannot see it because it is CONFIG, not code. The card is what catches it:
# the printed estimate is the energy component, so the inflated offset cannot
# reproduce it.
_NETWORK_C_KWH = 12.0
_double = refusal(spoilt(offset=ENECO_CARD["offset"] + _NETWORK_C_KWH))
_double_price = derived(lambda: in_card_units(
_cf.FormulaSpec(index="epex_be", resolution="hourly", factor=0.102,
offset=ENECO_CARD["offset"] + _NETWORK_C_KWH,
units="c_eur_per_kwh", vat_pct=6, card_month="2026-09",
card_index_eur_per_mwh=133.9905,
card_expect_incl_vat=15.55), 133.9905))
check(f"network charges folded into `offset` move the card's own price to "
f"{_double_price} c EUR/kWh against a printed 15.55, so it CANNOT pass "
f"- the counterfactual first, or the refusal below grades nothing",
isinstance(_double_price, float) and abs(_double_price - 15.55) > 10)
check(f"...and it is refused, by the CARD rule, naming the discrepancy and "
f"the network-charge cause ({_double[:60]!r})",
"does not reproduce its own card" in _double and "OUT BY" in _double
and "folded into `offset`" in _double)
_CORRUPTIONS = {
"VAT left out (vat_pct 0)": spoilt(vat_pct=0),
"VAT applied twice (the card's price already carries it)":
spoilt(card_expect_incl_vat=round(15.55 * 1.06, 4)),
"the coefficients in c EUR and the expected price in EUR":
spoilt(card_expect_incl_vat=0.1555),
"the index typed in EUR/kWh instead of EUR/MWh":
spoilt(card_index_eur_per_mwh=0.1339905),
"a transposed digit in the expected price (15.05 for 15.55)":
spoilt(card_expect_incl_vat=15.05),
"a transposed digit in the factor (0.120 for 0.102)":
spoilt(factor=0.120),
}
for _name, _blob in sorted(_CORRUPTIONS.items()):
_why = refusal(_blob)
check(f"{_name}: refused, and by the CARD rule rather than by another one "
f"({_why[:48]!r})",
"does not reproduce its own card" in _why and "OUT BY" in _why)
# ⚠️ THE TOLERANCE IS A REAL EDGE AND IT IS GRADED FROM BOTH SIDES, or
# "within 0.01" and "within anything" would be the same check.
_inside = refusal(spoilt(card_expect_incl_vat=round(
in_card_units(parse_price_formula(json.dumps(ENECO_CARD)), 133.9905)
+ CARD_TOLERANCE * 0.5, 6)))
_outside = refusal(spoilt(card_expect_incl_vat=round(
in_card_units(parse_price_formula(json.dumps(ENECO_CARD)), 133.9905)
+ CARD_TOLERANCE * 2.0, 6)))
check(f"half a tolerance out passes and twice a tolerance out does not, so "
f"{CARD_TOLERANCE} is the number being enforced rather than a shape",
_inside == "" and "does not reproduce its own card" in _outside)
# A card that is absent is refused, and NOT by the generic unknown-field rule.
check(f"a formula with NO card block is refused, and the message says why the "
f"card is required rather than merely that a field is missing",
"no \"card\" block" in refusal({k: v for k, v in ENECO_CARD.items()
if k != "card"}))
print()
print("15c. the index path is generic_dayahead's, replayed from the SAME "
"captured bytes")
# A networked plugin with no capture is what section 2b's roster forbids. This
# one reads the same endpoint with the same parser, so it is replayed from the
# same real bodies rather than from a fixture written here.
_CF_OPTS = {"price_formula": json.dumps(ENECO_CARD)}
_cf_replay = {n: load("custom_formula", _CF_OPTS, transport=canned(b))
for n, b in _REAL.items()}
check(f"the SHIPPED custom_formula parses all three captured real bodies "
f"{[r.words for r in _cf_replay.values()]}",
all(r.kind == "series" for r in _cf_replay.values()))
_cf_counts = derived(lambda: {n: len(r.points)
for n, r in _cf_replay.items()})
check(f"...and emits one point per published instant at quarter_hourly "
f"{_cf_counts}",
_cf_counts == {n: len(json.loads(b.decode("utf-8"))["price"])
for n, b in _REAL.items()})
# The URL is the same one, derived from the same helper. Behaviour, off the
# injected transport, not source text.
_cf_t = canned(_REAL[_TD])
run(load_prices(opts(price_provider="custom_formula", **_CF_OPTS),
_w0, _w0 + timedelta(hours=48), transport=_cf_t))
check(f"...and asks for the same Brussels range generic_dayahead asks for "
f"{_cf_t.calls[0][0]!r}",
_cf_t.calls[0][0] == asked_url(_w0, _w0 + timedelta(hours=48)))
# The price at each instant is the document's own index through the card's
# arithmetic - computed HERE from the captured bytes, by different arithmetic.
_doc = json.loads(_REAL[_QH].decode("utf-8"))
_want_cf = [round((0.102 * v + 1.00) * 1.06 / 100.0 + TAXES, 6)
for v in _doc["price"]]
_got_cf = derived(lambda: [p.eur_per_kwh
for p in _cf_replay[_QH].points])
check(f"every one of the {len(_want_cf)} points is (0.102 x index + 1) x 1.06 "
f"c EUR/kWh plus taxes, against the captured document's own index "
f"column (first three {_got_cf[:3] if isinstance(_got_cf, list) else _got_cf})",
_got_cf == _want_cf)
# ...and the index really varies over that day, or one constant would grade the
# whole column.
check(f"...and the captured index really varies across the day "
f"({min(_doc['price'])} .. {max(_doc['price'])} EUR/MWh), so that "
f"comparison is 96 different numbers and not one repeated",
len(set(_doc["price"])) > 50)
print()
print("15d. resolution: the contract's series, not the feed's")
# ⚠️ THIS IS NOT TARIFF-14's HOURLY ASSUMPTION COMING BACK. It decides how many
# points are EMITTED; the window each one covers is still derived from its
# neighbours by _cover_table(). Both halves are graded.
_hourly_card = dict(ENECO_CARD, resolution="hourly")
_h_read = load("custom_formula", {"price_formula": json.dumps(_hourly_card)},
transport=canned(_REAL[_QH]))
_q_read = _cf_replay[_QH]
check(f"the same 96-point body is 24 points at `hourly` and 96 at "
f"`quarter_hourly` ({len(_h_read.points)} vs {len(_q_read.points)}), so "
f"the option is doing something",
len(_h_read.points) == 24 and len(_q_read.points) == 96)
# The hourly value is the MEAN of that hour's quarters, computed here from the
# captured document rather than from the module.
_by_hour = {}
for _t, _v in zip(_doc["unix_seconds"], _doc["price"]):
_by_hour.setdefault(
datetime.fromtimestamp(_t, UTC).replace(minute=0), []).append(_v)
_want_h = [round((0.102 * (sum(v) / len(v)) + 1.00) * 1.06 / 100.0 + TAXES, 6)
for _k, v in sorted(_by_hour.items())]
_got_h = derived(lambda: [p.eur_per_kwh for p in _h_read.points])
check(f"...and each hourly point is the MEAN of its four quarters through the "
f"card's arithmetic (first three {_got_h[:3] if isinstance(_got_h, list) else _got_h})",
_got_h == _want_h)
# ⚠️ NON-DEGENERACY: an hour whose four quarters were equal would make "the
# mean" and "the first quarter" the same number, and the check above would
# grade nothing.
_differs = sum(1 for _k, v in _by_hour.items() if len(set(v)) > 1)
check(f"...and {_differs} of the {len(_by_hour)} hours really have quarters "
f"that DIFFER, so the mean is distinguishable from taking the first one",
_differs >= 20)
# An already-hourly feed averages one member per hour - the identity - so the
# option cannot silently assume the granularity it was handed.
_h1_pairs = [(datetime.fromtimestamp(t, UTC), v) for t, v in
zip(json.loads(_REAL[_H1].decode("utf-8"))["unix_seconds"],
json.loads(_REAL[_H1].decode("utf-8"))["price"])]
check("an ALREADY hourly feed is the identity under `hourly`, so the option "
"assumes nothing about the granularity it was handed",
derived(lambda: to_resolution(_h1_pairs, "hourly")) == _h1_pairs)
# and TARIFF-14: the window is still the neighbours', not an assumed hour.
_h_pts = _h_read.points
check("...and the hourly series' coverage is still DERIVED from the "
"neighbours - at() answers 59 minutes into a point and the next point "
"at 60, which is _cover_table()'s rule and not a rule this card added",
derived(lambda: _h_read.at(_h_pts[0].start + timedelta(minutes=59))
is _h_pts[0]) is True
and derived(lambda: _h_read.at(_h_pts[0].start + timedelta(minutes=60))
is _h_pts[1]) is True)
print()
print("15e. every refusal in the table, and the two that are WARNINGS")
_TABLE = {
"units absent": (spoilt(units=""), "units", "is REQUIRED"),
"units not one of the enumerated ones":
(spoilt(units="cents"), "units", "must be one of"),
"factor == 0 (every spread becomes 0, arbitrage never fires)":
(spoilt(factor=0), "factor", "static_profile"),
"factor < 0 (the dearest hour becomes the cheapest)":
(spoilt(factor=-0.102), "factor", "inverts the market"),
"vat_pct above 30 (the 6 / 1.06 / 106 confusion)":
(spoilt(vat_pct=106), "vat_pct", "between 0 and 30"),
"vat_pct below 0": (spoilt(vat_pct=-6), "vat_pct", "between 0 and 30"),
"a non-numeric coefficient": (spoilt(factor="0.102"), "factor",
"not a number"),
"a coefficient that is an EXPRESSION rather than a number":
(spoilt(factor="0.1*x"), "factor", "evaluates nothing"),
"a non-finite coefficient": (spoilt(offset=float("inf")), "offset",
"not finite"),
"an unknown index": (spoilt(index="belpex_h"), "index", "cannot get it"),
"an unknown resolution": (spoilt(resolution="daily"), "resolution",
"must be one of"),
"an unknown top-level field (which is how 'expr' is answered)":
(spoilt(expr="0.102*spot+1"), "expr", "NO field that takes an "
"expression"),
"an unknown field inside the card": ({**ENECO_CARD,
"card": dict(ENECO_CARD["card"],
vat="6")},
"vat", "no field(s)"),
}
for _name, (_blob, _names, _needle) in sorted(_TABLE.items()):
_why = refusal(_blob)
check(f"{_name}: refused, naming the field and the consequence "
f"({_why[:48]!r})",
_names in _why and _needle in _why)
# ⚠️ AND THE ARM THAT MAKES THOSE MEAN SOMETHING: a NaN is not merely refused
# by "not a number", and `True` is an int in Python.
check("NaN is refused as NOT FINITE rather than as not a number, so the two "
"rungs are distinguishable",
"not finite" in refusal(spoilt(factor=float("nan"))))
check("...and a bool is refused as not a number, because `True` is an int "
"here and would price the whole day at the index",
"not a number" in refusal(spoilt(factor=True)))
# The plausibility band. ⚠️ IT IS A SEPARATE QUANTITY FROM THE CARD CHECK: a
# unit error applied to BOTH sides cancels out of the card comparison and
# cannot cancel out of this one.
_both_sides = spoilt(factor=0.00102, offset=0.01,
card_expect_incl_vat=0.1555)
_bs_spec = derived(lambda: parse_price_formula(json.dumps(_both_sides)))
check("a unit error applied to BOTH sides passes the card self-check - stated "
"as a check, because it is the limit of that guard and not a bug in it",
not isinstance(_bs_spec, _Raised)
and abs(card_discrepancy(_bs_spec)) <= CARD_TOLERANCE)
_band = derived(lambda: implausible_all_in(_bs_spec, 0.0))
check(f"...and the all-in band is what catches it, naming the band "
f"({str(_band)[:48]!r})",
isinstance(_band, str) and "plausible band" in _band)
check("...and the REAL card is inside the band, so the band is not simply "
"refusing everything",
implausible_all_in(parse_price_formula(json.dumps(ENECO_CARD)),
0.06) is None)
check(f"...and the band really is {PLAUSIBLE_LO_EUR_KWH}-"
f"{PLAUSIBLE_HI_EUR_KWH} EUR/kWh at both ends, graded from inside and "
f"outside each",
implausible_all_in(parse_price_formula(json.dumps(ENECO_CARD)),
PLAUSIBLE_HI_EUR_KWH) is not None
and implausible_all_in(parse_price_formula(json.dumps(
spoilt(factor=0.0001, offset=0.0009,
card_expect_incl_vat=round((0.0001 * 133.9905 + 0.0009)
* 1.06, 6)))), 0.0) is not None)
# ⚠️ A STALE CARD IS A WARNING AND MUST NEVER BECOME A REFUSAL: ENGIE freezes
# a contract's coefficients for its duration, so a two-year-old card can be
# exactly right and a site refused over one is a site that cannot start.
_old_card = spoilt(card_month="2019-01")
check("an OLD card is not refused - the parse succeeds",
refusal(_old_card) == "")
check("...and it is warned about, naming the month and saying why it is not "
"refused",
"2019-01" in (stale_card(parse_price_formula(json.dumps(_old_card)))
or "")
and "Not refused" in (stale_card(
parse_price_formula(json.dumps(_old_card))) or ""))
check("...while a card from this month draws no warning, so the rule is the "
"AGE and not the presence of the field",
stale_card(parse_price_formula(json.dumps(ENECO_CARD)),
today=date(2026, 9, 13)) is None)
print()
print("15f. NO EXPRESSION EVALUATION OF ANY KIND - and the check that says so")
# WHY THIS IS A CHECK AND NOT A PROMISE. This string is settable over HTTP: the
# add-on serves `POST config/save` -> `POST /addons/self/options` on its own
# ingress page, so `eval` on it is remote code execution in a root container
# holding SUPERVISOR_TOKEN, with homeassistant_api and hassio_api, driving an
# inverter over RS485. And the deciding argument is not security: two
# coefficients can be GRADED against the card's printed price and an arbitrary
# expression cannot be graded against anything, so an expression would make
# the invisible-wrong-coefficient problem strictly worse.
_EVAL_NAMES = ("eval", "exec", "compile", "__import__", "literal_eval",
"eval_expr", "evaluate", "Interpreter", "simple_eval")
def eval_calls(source):
"""Every call in `source` whose target NAME is an evaluator. AST, not grep.
⚠️ IT WALKS THE TREE RATHER THAN MATCHING TEXT, so `eval` inside a comment
or a docstring - and this file's own prose about eval - is not a hit, and
`ast.literal_eval(...)` written as `literal_eval(...)` is.
"""
found = []
for node in ast.walk(ast.parse(source)):
if not isinstance(node, ast.Call):
continue
fn = node.func
name = (fn.id if isinstance(fn, ast.Name)
else fn.attr if isinstance(fn, ast.Attribute) else "")
if name in _EVAL_NAMES:
found.append(name)
return sorted(set(found))
_CF_SRC = open(os.path.join(HERE, "app", "custom_formula.py"),
encoding="utf-8").read()
check(f"app/custom_formula.py evaluates NOTHING: {eval_calls(_CF_SRC) or '[]'}",
eval_calls(_CF_SRC) == [])
check("...and neither does the plugin class that reads it",
eval_calls(dedent(inspect.getsource(PROVIDERS["custom_formula"]))) == [])
# ⚠️ THE RED DIRECTION, EXERCISED ON EVERY RUN. A scanner that found nothing
# because it scans nothing is the third failure mode in MUTATION.md, and this
# is the cheap way to keep it honest.
check("...and the scanner CAN go red: planted `eval` and `literal_eval` calls "
"are both found",
eval_calls("def f(s):\n return eval(s)\n") == ["eval"]
and eval_calls("import ast\ndef f(s):\n"
" return ast.literal_eval(s)\n") == ["literal_eval"])
# and the structural half: the coefficients are NUMBERS, so there is nothing
# for an evaluator to be reached from even if one appeared.
check("the spec carries only fixed scalars - no field holds a string that is "
"later interpreted",
derived(lambda: sorted(
type(v).__name__ for v in vars(parse_price_formula(
json.dumps(ENECO_CARD))).values())) ==
["float"] * 5 + ["str"] * 4)
check("...and a field that LOOKS like an expression is refused as not a "
"number rather than parsed as one",
"not a number" in refusal(spoilt(factor="0.102 * spot")))
print()
print("15g. it declares {ENERGY, MARKUP}, so the framework adds taxes ONCE")
_cf_caps = PROVIDERS["custom_formula"].capabilities()
check(f"custom_formula sources {sorted(c.value for c in _cf_caps.sources)} - "
f"a Belgian card's Tariefformule line is the ENERGY component and the "
f"contract's own markup, and nothing else",
_cf_caps.sources == frozenset({Component.ENERGY, Component.MARKUP}))
check(f"...so the framework adds exactly "
f"{sorted(c.value for c in _cf_caps.adds)}",
_cf_caps.adds == frozenset({Component.TAXES}))
# THE COST OF THE ALTERNATIVE, MEASURED, so the declaration is not grading
# itself. Declaring ALL_IN would drop the taxes silently - on every hour, on
# behalf of an operator who typed exactly what their card says.
_as_declared = derived(lambda: assemble(
_cf_caps, [RawPoint(T0, 0.1555, False)], MARKUP, TAXES)[0].eur_per_kwh)
_as_all_in = derived(lambda: assemble(
ProviderCapabilities(product=PriceProduct.DAY_AHEAD, sources=ALL_IN),
[RawPoint(T0, 0.1555, False)], MARKUP, TAXES)[0].eur_per_kwh)
check(f"declaring ALL_IN would price every hour {_as_declared} -> "
f"{_as_all_in} EUR/kWh, exactly one taxes component low, on behalf of "
f"an operator who typed what their card said",
isinstance(_as_declared, float) and isinstance(_as_all_in, float)
and abs((_as_declared - _as_all_in) - TAXES) < 1e-9)
check("and the configured markup is reported as IGNORED under it, because the "
"contract's formula already IS the markup",
(lambda: (lambda b, h: (
logging.getLogger("goodwe.price").addHandler(h),
load_any("custom_formula"),
logging.getLogger("goodwe.price").removeHandler(h),
"custom_formula" in b.getvalue()
and "double-count" in b.getvalue())[-1])(
*(lambda b: (b, logging.StreamHandler(b)))(io.StringIO())))())
print()
print("15h. the startup preview - a factor of 1000 visible in one line")
_prev_buf = io.StringIO()
_prev_h = logging.StreamHandler(_prev_buf)
_prev_log = logging.getLogger("goodwe.price")
_prev_level = _prev_log.level
# ⚠️ THE PREVIEW IS AT INFO AND THE DEFAULT ROOT LEVEL IS WARNING, so a check
# that forgot this line would grade an empty buffer and read as "the preview
# is missing". main.py runs the add-on at INFO - that is where `tariff
# refreshed: %s` is emitted from - so this makes the check's logger match the
# shipped one rather than relaxing anything.
_prev_log.setLevel(logging.INFO)
_prev_log.addHandler(_prev_h)
_price._PREVIEWED.discard("custom_formula")
load("custom_formula", _CF_OPTS, transport=canned(_REAL[_QH]))
_first_run = _prev_buf.getvalue()
load("custom_formula", _CF_OPTS, transport=canned(_REAL[_QH]))
_second_run = _prev_buf.getvalue()[len(_first_run):]
_prev_log.removeHandler(_prev_h)
_prev_log.setLevel(_prev_level)
check("the preview says it prints the index in EUR/MWh beside the all-in "
"EUR/kWh",
"index EUR/MWh -> all-in EUR/kWh" in _first_run)
# ⚠️ AND THE ROW, NOT ONLY THE HEADING. The check above was the whole of this
# for one draft, and deleting the index column from the ROW was a -13 B
# SURVIVOR of the entire suite: the sentence stayed true while the thing it
# describes was gone. MUTATION.md's third failure mode, in the check written
# to close it. The expectation is built here from the captured document.
_row_index = _doc["price"][0]
_row_price = (0.102 * _row_index + 1.00) * 1.06 / 100.0 + TAXES
_want_row = f"{_row_index:9.3f} -> {_row_price:9.5f}"
check(f"...and each ROW really carries the index BESIDE its own price "
f"({_want_row!r}), which is the pair a heading alone does not print",
_want_row in _first_run)
check("...and the min/median/max and the day's spread, in one line",
"min " in _first_run and "median " in _first_run
and "max " in _first_run and "spread " in _first_run)
_want_min = round(min((0.102 * v + 1.00) * 1.06 / 100.0 + TAXES
for v in _doc["price"][:96]), 5)
check(f"...and the figures are the SERIES' own, not a restatement: the "
f"minimum printed is {_want_min:.5f}, computed here from the captured "
f"document",
f"min {_want_min:.5f}" in _first_run)
check("...and it is emitted ONCE per process, not on every half-hourly "
"refresh - a log line must not become a log flood on the one path "
"§11.4 already makes hard to read",
"index EUR/MWh -> all-in EUR/kWh" not in _second_run)
# ⚠️ AND IT CANNOT STOP A BATTERY. A preview that raises is a log line that
# failed, not a fetch that failed.
class _BoomPreview(PriceProvider):
"""A plugin whose preview raises. AC: prices are unaffected.
SOURCES: energy
The framework ADDS: markup, taxes
"""
id = "_preview_boom"
@classmethod
def capabilities(cls):
return ProviderCapabilities(product=PriceProduct.DAY_AHEAD,
sources=frozenset({Component.ENERGY}))
async def fetch(self, opts, since, until, transport):
return [RawPoint(T0, 0.1, False)]
def startup_preview(self, points):
raise RuntimeError("the preview is broken")
PROVIDERS["_preview_boom"] = _BoomPreview
_boom_read = derived(lambda: load("_preview_boom", transport=refuse_transport))
del PROVIDERS["_preview_boom"]
check("a preview that RAISES does not cost the site its prices - the series "
"still comes back",
not isinstance(_boom_read, _Raised) and _boom_read.kind == "series")
print()
print("15i. the startup gate refuses it, so nothing is discovered at 03:00")
check("custom_formula with a correct card starts",
validate_startup_config(vbase(price_provider="custom_formula",
price_formula=json.dumps(ENECO_CARD)),
-5000, 5000) == [])
check("custom_formula with NO formula is refused, naming the option and "
"showing the shape",
why(validate_startup_config(vbase(price_provider="custom_formula"),
-5000, 5000),
"price_formula is empty"))
check("a formula that does not reproduce its card is refused AT STARTUP, "
"with the discrepancy named",
why(validate_startup_config(
vbase(price_provider="custom_formula",
price_formula=json.dumps(spoilt(offset=13.0))),
-5000, 5000), "does not reproduce its own card"))
check("...and a formula that is not JSON at all is refused with the shape it "
"wanted, rather than with a traceback",
why(validate_startup_config(
vbase(price_provider="custom_formula", price_formula="0.102*spot+1"),
-5000, 5000), "not valid JSON"))
check("...and a card outside the plausible band is refused too, WITH THE "
"SHIPPED taxes in place - the flat 0.06 must not be able to carry a "
"hundredfold error over the floor",
why(validate_startup_config(
vbase(price_provider="custom_formula",
price_formula=json.dumps(_both_sides)),
-5000, 5000), "plausible band"))
_masked = implausible_all_in(_bs_spec,
PRICE_OPTION_DEFAULTS["price_taxes_eur_kwh"])
check(f"...and that is a REAL trap, measured: the same card plus the shipped "
f"{PRICE_OPTION_DEFAULTS['price_taxes_eur_kwh']} of taxes totals "
f"{price_eur_kwh(_bs_spec, _bs_spec.card_index_eur_per_mwh) + PRICE_OPTION_DEFAULTS['price_taxes_eur_kwh']:.5f} "
f"EUR/kWh, which is INSIDE the band - a floor applied to the all-in "
f"figure would have passed it",
isinstance(_masked, str)
and PLAUSIBLE_LO_EUR_KWH <= (
price_eur_kwh(_bs_spec, _bs_spec.card_index_eur_per_mwh)
+ PRICE_OPTION_DEFAULTS["price_taxes_eur_kwh"])
<= PLAUSIBLE_HI_EUR_KWH)
# ⚠️ AND THE ONE ROW OF THE TABLE THAT IS A WARNING RATHER THAN A REFUSAL,
# graded AT THE GATE and not only at the parser - which is where the two could
# quietly become the same thing.
check("...while a card older than six months still STARTS: ENGIE freezes a "
"contract's coefficients for its duration, so an old card is often "
"exactly right and a site refused over one is a site that cannot run",
validate_startup_config(
vbase(price_provider="custom_formula",
price_formula=json.dumps(_old_card)), -5000, 5000) == [])
# ⚠️ THE ID IS IN THE SCHEMA, or the Supervisor refuses the options blob before
# the add-on runs and none of the sentences above is ever reached.
check("the id is offered by config.yaml's schema, so a site configured on it "
"reaches these messages rather than a Supervisor schema error",
"custom_formula" in _schema_ids)
print()
if fails:
print(f"{len(fails)} FAILED: " + "; ".join(fails))