TARIFF-12: a returned degradation is not a refresh
checks / unit (pull_request) Successful in 7m12s

`run_tariff_refresh()` promised in its own docstring that "a failure does
not clear the plan", and enforced it with `except Exception` - a branch a
supplier outage never reaches. `load_prices()` states the reason in its
own words: it "RETURNS, NEVER RAISES, for every failure a site can
actually have", because a degradation arriving as a traceback into the
planning tick would stop the controller regulating over an expired
certificate. So a dead feed RETURNS a §11.4 plan, the `try` succeeds, and
the assignment below it overwrote the good plan unconditionally. With
`static_profile` unset - the shipped default, and the normal state of a
dynamic-tariff site - `_degrade()` returns `TariffPlan(no_data, None,
"none")`: a complete 48-hour plan replaced by nothing, at the FIRST
failed fetch, ~27 minutes after the last good one. `TARIFF_MAX_AGE_S`
(5400 s) never governed anything and there was no serve-stale window at
all.

Fourth card in one family: FCST-04's M4 (`not ok` only), FCST-05's HIGH
(`(JSONDecodeError, OSError)` only), FCST-06 (`not self.ok` only), and
now `except Exception` only, for a path that never raises.

The question is now asked once, after the attempt, from the evidence
that exists - FCST-06's answer, one module over. The evidence is
`TariffPlan.from_feed` (did this resolution observe the configured feed)
and the shipped `fresh_tariff_plan()`, reused rather than transcribed. A
degradation replaces a standing observation only once that observation
has aged out, so `TARIFF_MAX_AGE_S` is now the serve-stale window it
reads like.

A §11.4 static fallback does not replace a fresh provider plan either,
although it carries real prices: every point `_degrade()` builds is
`provisional=True`, so `firm_points()` is empty, `arbitrage()` refuses
and `cheap_now()` is False - everything a consumer may act on is already
off - while a day-ahead price for a given hour does not change once
published. The rule is deliberately not symmetrical: a standing plan
that is itself a degradation IS replaced, or an outage would freeze the
operator's static profile at the window it was first generated for.

`tariff_at` does not move on a kept plan. It is the moment of the fetch
that produced the plan standing, `fresh_tariff_plan()` judges the age
from it, and an unmoved timestamp is the only thing that tells a kept
plan from a freshly fetched one.

test_arbitrage.py section 8b drives the whole chain with nothing stubbed
but the socket: the transport raises the way aiohttp does, load_prices()
returns no_data, _degrade() builds the §11.4 plan, and the shipped
run_tariff_refresh() decides. A check that patched resolve_tariff to
RAISE would have passed against the defect. Ten mutations, ten reds, no
survivors; 29/29 suites green.

Out of scope and unchanged: the persisted price store still does not
back the plan during an outage (FCST-03), and the status banner and the
Arbitrage row's lag are separately carded.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BwRLw7eKYj2byVdwB6kbjU
This commit is contained in:
Claude
2026-09-12 21:06:45 +02:00
parent 88c59a9918
commit c81289527f
6 changed files with 613 additions and 10 deletions
+253 -1
View File
@@ -92,7 +92,9 @@ from app.price import (
PRICE_OPTION_DEFAULTS, Absence, PricePoint, PriceProduct, PriceRead,
Uncertainty, WIDEN_FACTOR, brussels, required_spread, widen_factor,
)
from app.static_tariff import TariffPlan, parse_static_profile, static_plan
from app.static_tariff import (
TariffPlan, parse_static_profile, resolve_tariff, static_plan,
)
from app.validate import validate_startup_config
UTC = timezone.utc
@@ -1284,6 +1286,256 @@ check("main.py reads every arbitrage option through app/arbitrage.py or "
"arbitrage_soc_ceiling")))
# --------------------------------------------------------------------------- #
print()
print("8b. TARIFF-12 - a RETURNED degradation must not clear a fresh plan")
# ⚠️ THE STIMULUS IS A RETURN, NOT A RAISE, AND THAT IS THE WHOLE CHECK.
# `run_tariff_refresh()` guarded the plan with `except Exception` alone, and
# `load_prices()` states in its own docstring that it "RETURNS, NEVER RAISES,
# for every failure a site can actually have" - so the one case the guard was
# written for, a supplier outage, never reached it. Everything below drives the
# SHIPPED chain and stubs nothing but the socket: the transport raises the way
# aiohttp does, `load_prices()` turns that into a `no_data` read, `_degrade()`
# turns THAT into a §11.4 plan, and `run_tariff_refresh()` decides what to do
# with it. A check that patched `resolve_tariff` to raise would have passed
# against the defective code.
import asyncio # noqa: E402
from app import price as _price # noqa: E402
from app.price_history import NoHistory # noqa: E402
class ClientConnectorError(Exception):
"""aiohttp's own class name, so the §11.4 reason this drives is the
sentence the 40 h soak recorded at refresh 56, verbatim."""
_T12_FEED_UP = {"up": True}
async def _t12_transport(url, timeout_s):
"""The socket, and nothing else, is what this replaces."""
if not _T12_FEED_UP["up"]:
raise ClientConnectorError(
"Cannot connect to host api.energy-charts.info:443 ssl:default")
t0 = datetime.now(UTC).replace(minute=0, second=0, microsecond=0)
return json.dumps({
"unix_seconds": [int((t0 + timedelta(hours=i)).timestamp())
for i in range(48)],
"price": [80.0 + 40.0 * (i % 6) for i in range(48)],
"unit": "EUR / MWh"}).encode()
class _T12Controller:
"""Just enough Controller to run the SHIPPED refresh coroutine.
Both methods are bound off the shipped class rather than copied, for
`fresh_tariff_plan()`'s own stated reason: a transcription drifts.
"""
run_tariff_refresh = _main.Controller.run_tariff_refresh
fresh_tariff_plan = _main.Controller.fresh_tariff_plan
def __init__(self, opts):
self.o = opts
self.tariff_plan = None
self.tariff_at = None
self.price_history = NoHistory()
self.stop_event = asyncio.Event()
self.stop_event.set() # so the inter-refresh wait returns
self._ticks = 0
@property
def stopping(self):
self._ticks -= 1
return self._ticks < 0
def refresh_once(self):
self._ticks = 1
asyncio.run(self.run_tariff_refresh())
return self
def _t12_opts(profile=""):
# `price_timeout_s` is read with a plain `.get()` by every plugin, so it
# has to be present - an options dict that relies on price_option()'s
# defaults for it fetches with `float(None)` and this section would grade
# a TypeError instead of an outage.
return {"price_provider": "generic_dayahead", "price_timeout_s": 10,
"price_horizon_h": 48, "static_profile": profile}
_T12_HORIZON_H = 48
_T12_STALE_S = _main.TARIFF_MAX_AGE_S
_t12_saved_transport = _price.https_get
_price.https_get = _t12_transport
# -- the accepted baseline (habit 7): one good fetch, varied one thing at a
# -- time from here.
_T12_FEED_UP["up"] = True
_t12_a = derived(lambda: _T12Controller(_t12_opts()).refresh_once())
_t12_good = derived(lambda: _t12_a.tariff_plan)
check(f"BASELINE: a fetch that succeeds stores an OBSERVATION - "
f"{getattr(_t12_good, 'words', _t12_good)!r}",
getattr(_t12_good, "origin", None) == "provider"
and _t12_good.from_feed is True
and len(_t12_good.read.points) == _T12_HORIZON_H)
# -- the stimulus, graded before it is used on anything (habit 6/7) ----------
_T12_FEED_UP["up"] = False
_t12_now = datetime.now(UTC)
_t12_deg = derived(lambda: asyncio.run(resolve_tariff(
_t12_opts(), _t12_now, _t12_now + timedelta(hours=_T12_HORIZON_H),
now=_t12_now, history=NoHistory())))
check("STIMULUS: a dead feed makes resolve_tariff() RETURN a degraded plan - "
"it does not raise, so `except Exception` is not what was protecting "
"the plan and the defect was never on that branch",
isinstance(_t12_deg, TariffPlan))
check(f"...and the returned plan is the §11.4 no-profile row the soak saw - "
f"{getattr(_t12_deg, 'words', _t12_deg)!r}",
isinstance(_t12_deg, TariffPlan) and _t12_deg.origin == "none"
and _t12_deg.from_feed is False and _t12_deg.has_prices is False
and "ClientConnectorError" in _t12_deg.words)
# -- AC1: the degradation must not replace a plan still inside the bound -----
# ⚠️ 1800 s IS STATED HERE, NOT DERIVED FROM THE MODULE BEING GRADED - section
# 8's own lesson. A probe at `TARIFF_MAX_AGE_S - 1` moves with a mutation of
# the constant; half an hour is inside any reading of a 5400 s bound, and it is
# the interval the soak actually ran at.
_t12_b = derived(lambda: _T12Controller(_t12_opts()))
_t12_b.tariff_plan, _t12_b.tariff_at = _t12_good, datetime.now(UTC) - \
timedelta(seconds=1800)
_t12_at_before = _t12_b.tariff_at
check(f"PRECONDITION: the standing plan is 1800 s old and TARIFF_MAX_AGE_S is "
f"{_T12_STALE_S:.0f} s, so it IS fresh when the failed refresh runs - "
f"without this the next check grades an expired plan",
1800 < _T12_STALE_S
and _t12_b.fresh_tariff_plan(datetime.now(UTC)) is _t12_good)
_t12_b.refresh_once()
check("a RETURNED degradation does not replace a plan still inside "
"TARIFF_MAX_AGE_S - the 48 h series is still there, by identity, and "
"not a 0-point `origin: none` read",
_t12_b.tariff_plan is _t12_good
and _t12_b.tariff_plan.has_prices is True
and len(_t12_b.tariff_plan.read.points) == _T12_HORIZON_H)
check("...and `tariff_at` did NOT move, so the kept plan still ages out from "
"the fetch that produced it and is distinguishable from a freshly "
"fetched one. Re-stamping it here is how a plan freezes at its last "
"value and looks current forever",
_t12_b.tariff_at == _t12_at_before)
check("...and the two timestamps a successful refresh and a kept plan produce "
"really are different values, or the check above compares a number "
"against itself",
_t12_a.tariff_at != _t12_at_before)
# -- AC3: TARIFF_MAX_AGE_S governs - the bound is where the module says ------
_t12_c = derived(lambda: _T12Controller(_t12_opts()))
_t12_c.tariff_plan, _t12_c.tariff_at = _t12_good, datetime.now(UTC) - \
timedelta(seconds=_T12_STALE_S + 5)
_t12_c.refresh_once()
check(f"a plan that has aged PAST {_T12_STALE_S:.0f} s IS replaced by the "
f"degradation - the plan is served stale for the age bound and no "
f"longer, so TARIFF_MAX_AGE_S governs something rather than being "
f"unreachable",
_t12_c.tariff_plan is not _t12_good
and _t12_c.tariff_plan.from_feed is False
and _t12_c.tariff_plan.has_prices is False)
_t12_d = derived(lambda: _T12Controller(_t12_opts()))
_t12_d.tariff_plan, _t12_d.tariff_at = _t12_good, datetime.now(UTC) - \
timedelta(seconds=_T12_STALE_S - 60)
_t12_d.refresh_once()
check("...and one minute SHORT of the bound it is still kept, so the line "
"above is a bound rather than 'the degradation always wins'",
_t12_d.tariff_plan is _t12_good)
_t12_e = derived(lambda: _T12Controller(_t12_opts()).refresh_once())
check("a degradation with NO plan standing at all is stored - §11.4 still "
"reaches an install that has never had a good fetch, and the guard is "
"not 'never overwrite'",
_t12_e.tariff_plan is not None
and _t12_e.tariff_plan.from_feed is False
and _t12_e.tariff_at is not None)
# -- the §11.4 STATIC FALLBACK, which is the judgement this card had to make -
_t12_f = derived(lambda: _T12Controller(_t12_opts(STATIC_BE)))
_t12_fb = derived(lambda: asyncio.run(resolve_tariff(
_t12_opts(STATIC_BE), _t12_now,
_t12_now + timedelta(hours=_T12_HORIZON_H), now=_t12_now,
history=NoHistory())))
check(f"PRECONDITION: with a static_profile configured the SAME dead feed "
f"degrades to a §11.4 FALLBACK carrying real prices, not to the "
f"no-profile row - {getattr(_t12_fb, 'words', _t12_fb)!r}",
isinstance(_t12_fb, TariffPlan) and _t12_fb.origin == "fallback"
and _t12_fb.has_prices is True and _t12_fb.from_feed is False)
check("...and every one of its points is provisional, so firm_points() is "
"empty, arbitrage() refuses and cheap_now() is False - it is a real "
"tariff and nothing may be acted on it. That is why it does not replace "
"a fresh observation",
isinstance(_t12_fb, TariffPlan) and _t12_fb.provisional is True
and _t12_fb.firm_points() == ()
and _t12_fb.arbitrage(peak_guard_active=False, min_spread_eur_kwh=0.0,
uncertainty=NO_WEATHER).kind == "refused")
_t12_f.tariff_plan, _t12_f.tariff_at = _t12_good, datetime.now(UTC) - \
timedelta(seconds=1800)
_t12_f_at = _t12_f.tariff_at
_t12_f.refresh_once()
check("a §11.4 static FALLBACK does not replace a fresh provider plan either, "
"although it has prices - a day-ahead price for an hour does not change "
"once published, so the 30-minute-old observation is no less true and "
"is the only one of the two that carries a firm hour",
_t12_f.tariff_plan is _t12_good and _t12_f.tariff_at == _t12_f_at)
# -- ...and the rule is NOT symmetrical: a degradation replaces a degradation.
_t12_g = derived(lambda: _T12Controller(_t12_opts(STATIC_BE)))
_t12_g.tariff_plan, _t12_g.tariff_at = _t12_fb, datetime.now(UTC) - \
timedelta(seconds=1800)
_t12_g_at = _t12_g.tariff_at
_t12_g.refresh_once()
check("a standing plan that is ITSELF a §11.4 fallback IS replaced by the "
"next one, and its timestamp moves - otherwise an outage would freeze "
"the operator's static profile at the window it was first generated "
"for, and the guard would be 'never overwrite' wearing a bound's name",
_t12_g.tariff_plan is not _t12_fb and _t12_g.tariff_plan.origin ==
"fallback" and _t12_g.tariff_at != _t12_g_at)
# -- ...and a recovered feed replaces a kept plan, which is the third term ---
_T12_FEED_UP["up"] = True
_t12_h = derived(lambda: _T12Controller(_t12_opts()))
_t12_h.tariff_plan, _t12_h.tariff_at = _t12_good, datetime.now(UTC) - \
timedelta(seconds=1800)
_t12_h_at = _t12_h.tariff_at
_t12_h.refresh_once()
check("when the feed answers again the observation replaces the kept plan and "
"`tariff_at` moves - the guard keeps a plan against a DEGRADATION, not "
"against a fetch that worked",
_t12_h.tariff_plan is not _t12_good
and _t12_h.tariff_plan.from_feed is True
and _t12_h.tariff_at != _t12_h_at)
# -- the vocabulary, graded on its own so a mutation of it has a named home --
check("TariffPlan.from_feed is true of exactly the observation - a §11.4 "
"fallback, a no-data read and a CONFIGURED static profile are all false, "
"and it is not a synonym for has_prices",
_t12_good.from_feed is True and _t12_fb.from_feed is False
and _t12_deg.from_feed is False
and static_plan({"static_profile": STATIC_BE}, D0,
D0 + timedelta(days=2), now=D0).from_feed is False
and static_plan({"static_profile": STATIC_BE}, D0,
D0 + timedelta(days=2), now=D0).has_prices is True)
# ⚠️ A SHAPE CLAIM, AND IT IS ALLOWED TO BE ONE (FCST-06's precedent). "The age
# is judged in ONE place" is a claim about the code, not about a behaviour: a
# transcribed copy of the same comparison behaves identically until the day the
# two drift. Every other check in this section is driven.
check("run_tariff_refresh() asks fresh_tariff_plan() rather than re-deriving "
"the age bound - one place judges it, which is what that method's own "
"docstring is for",
_refresh is not None
and {n.func.attr for n in ast.walk(_refresh)
if isinstance(n, ast.Call) and isinstance(n.func, ast.Attribute)}
>= {"fresh_tariff_plan"})
_price.https_get = _t12_saved_transport
# --------------------------------------------------------------------------- #
print()
print("9. the startup gate - the configurations that cannot work are refused")