Skip to content

Serve per-slot reaction rules with storage schedules - #2905

Merged
Flix6x merged 35 commits into
mainfrom
feat/recourse-rules-v2
Nov 27, 2026
Merged

Flix6x merged 35 commits into
mainfrom
feat/recourse-rules-v2

Conversation

@Flix6x

@Flix6x Flix6x commented Nov 24, 2026 •

Copy link
Copy Markdown
Member

Description

Storage schedules can now come with per-slot reaction rules, which tell a device how to react locally when the power at the connection deviates from what the plan is balanced against, so a site keeps to the plan's intent between two schedule triggers. The planner computes the rules; the client evaluates them (FlexMeasures/flexmeasures-client#299).

  • The rule. For each slot, a reacting device's setpoint is clip(p - react * deviation, band), with p the scheduled value and deviation = (meter - Σ device power) - reference, where meter is the measured net power at the connection and Σ device power the realised power of the reacting devices.

  • The opt-in. A single new public field: the boolean flex-model field react (default false). A device with react: true gets reaction rules; it is storable on the asset's flex-model and offered by the flex-model editor in the UI. Reacting devices form a chain in flex-model order, each absorbing what the devices before it could not.

  • The served array. GET /api/v3_0/sensors/<id>/schedules/<uuid> gains a top-level reaction array for each device with react: true (and only for those), with one entry per schedule value: {"reference": <number>, "react": 0 or 1, "band": [[lo, hi], ...]}, in the schedule's unit and sign convention, at the plan's full precision.

    • reference is the uncontrolled power the plan is balanced against. Usually that is the forecast: the sum of the inflexible-device forecasts, without any flexible device's plan (0.0 without inflexible devices, never null). Where the device's operation modes keep the plan from balancing the connection exactly, it is the balance point instead, so the deviation is non-zero for a house exactly as forecast and the client's rounding brings it back to the plan.
    • react is 1 where the price kink is within the device's reach, and 0 only where the band is a single point. The price kink is the bend in the cost of the connection as a function of net power: at 0 kW where importing costs the consumption price and exporting earns only a lower production price (or the production price is at or below zero), or at a capacity that binds. Shares between 0 and 1 are reserved for a later version.
    • band lists every power range the device may use in that slot with the rest of the plan still feasible: its operation modes cut to its own limits, each narrowed so that every later state-of-charge limit stays reachable, soft ones included. Shared limits such as the site capacity do not narrow it. Every side is a finite number. Whether a device changes operation mode within a slot is the controller's policy. Off the kink, the band only extends from p towards the kink, so the device absorbs deviations that would push the connection across it and follows the plan against deviations that push it further away; where nothing is left on that side (a charger already at full power while importing), the slot gets react: 0 with [[p, p]].
    • On a sensor coarser than the scheduling resolution, a slot gets the rule of its sub-slots where they agree and the served value lies in the band, and otherwise react: 0 with [[v, v]].
  • The controller's duty. Absorbing a deviation costs the device energy that nothing in the rules gives back, so a controller following the rules must retrigger after absorbing: once the state of charge has drifted by a set amount from the plan, and in any case before a target. The rules live in the job's meta and expire with the job.

  • Byte-for-byte compatible. A trigger without any react: true device gets today's payload (asserted by the API test).

  • Kept internal for now (implemented and unit-tested through the scheduler, not accepted by the public schemas, not in the API docs or OpenAPI spec): a device's reaction directions, a reaction time as a sanity bound, and a retrigger-on-band-exit flag (default true, carried in the job meta, not served).

  • Solve time (27-hour, 5-minute schedule, battery with three operation-mode ranges, 5-minute uncontrolled forecast, HiGHS): about 0.5 s with and without the opt-in. The rule computation adds nothing measurable.

  • The July prototype (feat/recourse-rules) is merged as is and then reworked; the code now uses the "reaction" vocabulary throughout.

  • Added changelog item in documentation/changelog.rst (and documentation/api/change_log.rst)

Look & Feel

Trigger with the opt-in:

{
  "start": "2026-01-01T00:00:00+01:00",
  "duration": "PT4H",
  "flex-model": {"soc-at-start": "5 kWh", "soc-min": "0 kWh", "soc-max": "20 kWh", "power-capacity": "10 kW", "react": true},
  "flex-context": {"consumption-price": {"sensor": 1}, "production-price": {"sensor": 2}, "site-power-capacity": "15 kW", "inflexible-consumption": [{"sensor": 3}]}
}

Schedule GET for a charger with modes idle and 1.4 to 7.4 kW (excerpt, kW), around midday with a forecast PV surplus:

{
  "values": [4.4, 1.4, 0.0, 7.4],
  "reaction": [
    {"reference": -4.4, "react": 1, "band": [[0.0, 0.0], [1.4, 7.4]]},
    {"reference": -1.4, "react": 1, "band": [[0.0, 0.0], [1.4, 2.0]]},
    {"reference": 0.0, "react": 1, "band": [[0.0, 0.0], [1.4, 7.4]]},
    {"reference": -4.4, "react": 0, "band": [[7.4, 7.4]]}
  ]
}

Slot 2 shows a balance-point reference: a 1.2 kW surplus against a 1.4 kW minimum charge. Slot 3 shows an idle plan under a surplus below the minimum power. Slot 4 is a car that must charge at full power to make its target.

How to test

  • flexmeasures/data/models/planning/tests/test_reaction.py (both solver backends, 48 cases): a hand-verified site, the house-as-forecast property, the kink-within-reach classes, operation-mode bands, the balance point, soft state-of-charge limits narrowing the band, a plan just below the fuse, one-sided bands off the kink (at the power limit, inside the range, and exporting), a device without react, the closed loop of absorbing and retriggering, the internal keys, and the no-opt-in case.
  • flexmeasures/api/v3_0/tests/test_reaction_response.py and the API round trips in test_sensor_schedules_fresh_db.py and test_asset_schedules_fresh_db.py, including a 15-minute sensor next to a 5-minute one.
  • Schema tests in flexmeasures/data/schemas/tests, the OpenAPI spec test.
  • Every new test was proven to fail by reverting what it covers.

Further Improvements

  • Expose the reaction directions, reaction time and retrigger flag once their shape has settled.
  • The first slot's reference from the latest posted measurements instead of the forecast.
  • react shares from the optimizer's duals, which also see preferences the reach criterion cannot (breach prices, cycling cost).
  • Rules for a schedule read from sensor data, beyond the job's lifetime.

Related Items

Closes #2894. Its follow-ups (listed there) are not part of this PR.


Sign-off

  • I agree to contribute to the project under Apache 2 License.
  • To the best of my knowledge, the proposed patch is not based on code under GPL or other license that is incompatible with FlexMeasures

🤖 Generated with Claude Code

https://claude.ai/code/session_01WGt2vUmJ4goxUYxexuArDE

Flix6x and others added 13 commits July 11, 2026 23:29
Opt-in via StorageScheduler.include_response: after solving, compute()
(with return_multiple) also returns one "recourse_rule" entry per
flexible device, with per-slot values for the affine rule
setpoint(m) = clip(p + gain * (m - reference), band_min, band_max):

- band: the device's power capacity, intersected with the EMS/site
  capacity headroom of its commodity (other devices held to plan) and
  with stock-reachability bounds from a one-slot deviation analysis
  (backward-propagated safe SoC sets);
- gain: v1 rule-based classification (K=-1 for the widest-band storage
  device of a commodity where the site capacity binds, prices are
  asymmetric or negative; K=0 otherwise);
- reference: the net planned flow of the device's commodity, including
  the device's own planned power (m == reference implies setpoint == p).

Implements v1 of SeitaBV/ems#231 (design: SeitaBV/ems#230 Part A).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
- New flex-model field `include-response` (StorageFlexModelSchema, works in
  both the single-sensor and the multi-device asset trigger paths) enables
  the StorageScheduler's recourse-rule computation.
- New optional flex-context field `reference-sensor` (per commodity) names
  the commodity's main-meter sensor; it is serialized through to the API
  payload (null when absent). No meter discovery is attempted.
- make_schedule stores the computed rules in the job meta (not as sensor
  data); GET /sensors/<id>/schedules/<uuid> then adds one "response" object
  per schedule value: {"reference-sensor", "reference", "gain", "band",
  "retrigger-on-band-exit": true}, aligned with the served window and
  converted to the same unit and sign convention as the schedule values.
  Unconstrained band sides serialize as null. Responses without the opt-in
  are unchanged (backwards compatible).
- API-level round-trip test plus changelog and API changelog entries.

Implements item 4 of SeitaBV/ems#231.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
End-to-end testing (FM + flexmeasures-client) showed respond(reference) != p
for kW sensors: the rule data was rounded to round_to_decimals decimals in MW,
while schedule values are rounded in the sensor's own unit, so a band side
could clip the planned power by up to half a rounding step (e.g. 0.27 kW band
vs 0.270463 kW schedule value). Keep the rule data at full precision; the API
converts it to the same unit as the served schedule values.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Add .github/workflows/hems-integration.yml (manual dispatch): postgres+redis
services, FlexMeasures installed from the checkout, DB init + toy account,
live server and scheduling worker, then flexmeasures-client installed from a
configurable git ref (input client-ref, default main) and the client's
examples/hems_saldering_transition.py run against the stack with a hard
timeout; the job fails on nonzero exit. The example exercises the full
recourse-rules contract (include-response opt-in, reference-sensor,
K classification, band feasibility, mode projection, band-exit debounce).

Note: passing on CI requires a flexmeasures-client release containing the cem
subpackage (branch feat/cem-recourse); the step sequence was validated locally
against a live stack.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The v1 K-classifier already evaluates its three rules per slot (vectorized
over the horizon): a slot only gets K=-1 if, in that slot, the commodity's
hard site capacity binds at the optimum, consumption != production price,
or a price is negative. Add a mixed-day test (symmetric prices in slots 0
and 2, production price 0 in slots 1 and 3) asserting the gain flips per
slot ([0, -1, 0, -1]); no production change was needed.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
…) into main

Revive the July prototype of per-slot recourse rules on current main, keeping main's structure.
The July hooks in storage.py now live alongside main's grouped-output helpers,
the `include-response` opt-in is read from the device inventory's flex-models,
and the recourse-rule outputs stay out of the per-sensor output deduplication,
since they name a device's sensor without saving a schedule to it.
The API round-trip test expects the 202 that schedule triggers return on main.
Both changelogs keep the July entries under the unreleased version, to be reworded with the agreed contract.

The HEMS integration workflow from July is merged as is, and removed in the next commit.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WGt2vUmJ4goxUYxexuArDE
Signed-off-by: F.N. Claessen <claessen@seita.nl>
…nger exists

The workflow ran examples/hems_saldering_transition.py from flexmeasures-client against a live stack.
That example never reached the client's main branch (its examples/HEMS/ folder is a different setup),
so the manually dispatched job could only fail.
The joint test with a home controller replaces it as the integration check of the reaction rules.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WGt2vUmJ4goxUYxexuArDE
Signed-off-by: F.N. Claessen <claessen@seita.nl>
Replace the July prototype's opt-in and semantics with the contract agreed on 23 November (issue #2894):

- The flex-context opts in with `reference-sensor` (a sensor reference object, no longer a bare ID),
  orders the responding devices with `response-order` (each entry must be a flex-model device, or validation fails),
  may switch `retrigger-on-band-exit`, and may give the current uncontrolled reading as `reference-at-start`,
  which replaces the first slot's reference and is momentary like `soc-at-start`.
- Each flex-model device describes its `response` (`directions` and `response-time`),
  replacing the boolean `include-response`.
- The reference is the uncontrolled power the plan assumed (the inflexible forecasts, without any device's plan),
  so a connection behaving as forecast leaves every setpoint at the plan; without inflexible devices it is 0.
- The gain is -1 for devices of the response-order where the site capacity binds,
  where the planned connection power is zero while the production price is below the consumption price,
  and where the production price is zero or negative; 0 otherwise.
  A device slower than one scheduling step, or without room to move, gets 0.
- The band is a list of ranges from the device's own limits only (power capacity, operation modes,
  stock reachability), cut to the directions it can respond in; shared limits no longer narrow it.

The scheduling service keeps each device's rules in the job meta as gain, reference and band (a list of [min, max] ranges).
The auth loader reads the sensor reference object under the `reference-sensor` key,
where it used to expect a bare ID under every key ending in `-sensor`.
The stored flex-context keeps `reference-sensor` and `response-order`, which the UI editor offers
as a sensor reference and a list of sensor references.

Tests: each planning test was proven to fail by mutating what it covers
(reference including device plans, each gain rule, the operation-mode split, the direction gating,
the response-time bound, the response-order gate and validation, the opt-in, reference-at-start,
and the stock reachability).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WGt2vUmJ4goxUYxexuArDE
Signed-off-by: F.N. Claessen <claessen@seita.nl>
GET /api/v3_0/sensors/<id>/schedules/<uuid> now accompanies each schedule value with
{"reference", "gain", "band"} when the trigger opted in through `reference-sensor`,
where `band` is a list of [min, max] ranges in the schedule's unit and sign convention,
at the plan's full precision, with null only for a side the device has no limit on.
The per-slot `reference-sensor` and `retrigger-on-band-exit` of the July prototype are gone,
as both live at the flex-context level now.
A trigger without `reference-sensor` gets today's response.

The API test was proven to fail by not serving the key, and by opting in unconditionally.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WGt2vUmJ4goxUYxexuArDE
Signed-off-by: F.N. Claessen <claessen@seita.nl>
Drop the flex-context fields `reference-sensor` and `reference-at-start`, as decided after review:
the connection's meter is already named by `aggregate-consumption` and `aggregate-production`,
and a signed net sensor was a leftover of the July per-phase design.
A non-empty `response-order` now opts in; without it the payload is today's.

The first slot's reference stays the uncontrolled forecast.
Deriving it from the latest measurements of the aggregate and device sensors is left out:
those sensors also hold scheduler output, so it would need source filtering,
sign handling across three sensor conventions and alignment of readings taken at different times.

The auth loader change that let a `-sensor` key hold a sensor reference object goes with the field,
as does its test.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WGt2vUmJ4goxUYxexuArDE
Signed-off-by: F.N. Claessen <claessen@seita.nl>
Rename the served `gain` to `react`, the share of the surprise the device absorbs, in [0, 1]:
setpoint = clip(p - react * residual, band), with residual the measured uncontrolled power minus the reference.
This version emits 0 (follow the plan) or 1 (absorb the surprise one to one);
shares in between are reserved for a later version, as the API docs and the docs section say.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WGt2vUmJ4goxUYxexuArDE
Signed-off-by: F.N. Claessen <claessen@seita.nl>
…ion array

The only new public field is the boolean flex-model field `react` (default false),
which opts a device in to the reaction rules; it is also storable on the asset and offered by the flex-model editor.
The flex-context fields `response-order` and `retrigger-on-band-exit` and the flex-model `response` block leave the public schemas:
reacting devices form a chain in flex-model order, which the planning code documents.
The served schedule's top-level key is now `reaction`, with entries {"reference", "react", "band"} as before.

The reaction directions, the reaction time and the retrigger flag stay implemented,
read from internal keys of the deserialized flex config (`reaction_directions`, `reaction_time`, `retrigger_on_band_exit`),
with their defaults being any direction, no time bound and retrigger true.
They are not accepted by the public schemas and not documented in the API docs or the OpenAPI spec;
their unit tests set the keys on the deserialized config and exercise the scheduler directly.
The retrigger flag travels with each rule entry into the job meta, but is not served.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WGt2vUmJ4goxUYxexuArDE
Signed-off-by: F.N. Claessen <claessen@seita.nl>
Bring the branch up to date with main before opening the pull request; the merge is clean.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WGt2vUmJ4goxUYxexuArDE
Signed-off-by: F.N. Claessen <claessen@seita.nl>
@Flix6x Flix6x added this to the 1.2.0 milestone Nov 24, 2026
@Flix6x Flix6x self-assigned this Nov 24, 2026
Flix6x and others added 2 commits November 24, 2026 17:23
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WGt2vUmJ4goxUYxexuArDE
Signed-off-by: F.N. Claessen <claessen@seita.nl>
I, F.N. Claessen <claessen@seita.nl>, hereby add my Signed-off-by to this commit: fdf6f3a
I, F.N. Claessen <claessen@seita.nl>, hereby add my Signed-off-by to this commit: 26afcbb
I, F.N. Claessen <claessen@seita.nl>, hereby add my Signed-off-by to this commit: 4c707b2
I, F.N. Claessen <claessen@seita.nl>, hereby add my Signed-off-by to this commit: aa1bc3f
I, F.N. Claessen <claessen@seita.nl>, hereby add my Signed-off-by to this commit: bd148c9

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WGt2vUmJ4goxUYxexuArDE
Signed-off-by: F.N. Claessen <claessen@seita.nl>
@read-the-docs-community

read-the-docs-community Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

The scheduler requires a power capacity for every device, so a band side is never unbounded,
and the null side the API docs and serializer allowed for was a contract case that cannot occur.
The serializer now converts plain floats and raises a ValueError naming the device and slot
should a non-finite value ever appear, which would be a scheduler bug.
The job meta stores plain floats, and the docs and API test say every side is a finite number.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WGt2vUmJ4goxUYxexuArDE
Signed-off-by: F.N. Claessen <claessen@seita.nl>
Flix6x and others added 4 commits November 25, 2026 12:50
The near-zero class of the reaction rules used the 1e-6 MW numerical tolerance,
which a plan held at zero by the LP meets, but a plan shaped by operation modes rarely does:
such a device cannot cancel a small load exactly, so the connection stays a step off zero.
A named 50 W tolerance now decides the class; the numerical tolerance stays for the band arithmetic.
The test is proven to fail at the old tolerance.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WGt2vUmJ4goxUYxexuArDE
Signed-off-by: F.N. Claessen <claessen@seita.nl>
A device with operation modes cannot always balance the connection exactly:
its smallest step may leave the plan a little off zero, or off the binding capacity.
Such a slot is now classified when the plan's miss stays within the dead zone of the reacting devices' bands
(the widest gap between two of their ranges, or the float tolerance for a device without modes),
which replaces the 50 W constant of the previous commit.

In a classified slot the served reference is the balance point of the plan,
the intended connection power minus the planned power of the reacting devices,
rather than the uncontrolled forecast; for a continuous device the two coincide.
The served band is the plan's own range only, since the mode is fixed per slot
and the plan must be the setpoint at zero deviation from the balance point:
with the house as forecast the raw setpoint lands outside the range on the side of the unconstrained optimum,
and the clip returns the plan.

Tests: a mode-shaped plan 0.2 kW off zero (balanced at -1.4 kW, band [1.4, 2] kW, and the client rule checked for the house as forecast and for extra sun),
a miss beyond the dead zone that is not classified, and the plan's own range within the modes;
each proven to fail with the shift removed.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WGt2vUmJ4goxUYxexuArDE
Signed-off-by: F.N. Claessen <claessen@seita.nl>
…ly for a mode-shaped miss

Three corrections to the balance-point commit:

- A slot gets react 1 when there is a price kink to hold (a production price below the consumption price or at or below zero,
  or a binding capacity), the device could reach the power that balances the connection at it regardless of its stock,
  and the plan's own range is not a point. The plan no longer has to sit on the kink,
  so the negative-price class no longer requires the connection to be held at zero.
- The reference is shifted to the balance point (intended minus the planned power of the reacting devices)
  only where the miss is caused by the device's modes: the balancing power falls in a gap between two ranges
  and the plan sits at the gap's edge. A deliberate deviation, such as importing for a target, keeps the forecast.
- The band stays the plan's own range in every reacting slot; a point range gives react 0 with the plan as band.

Tests: clouds where sun was planned with a target this evening (deliberate imports keep the forecast,
the band's lower bound rises with reachability, 1 kW of extra sun gives 6.0 kW), a negative feed-in price without a forecast
(reference 0.0, reacting away from zero, a point range in the idle slot), the mode-shaped miss and the out-of-reach miss kept;
each proven to fail with its correction removed.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WGt2vUmJ4goxUYxexuArDE
Signed-off-by: F.N. Claessen <claessen@seita.nl>
The mode policy moved to the controller, so a reacting device's band again lists every range the plan leaves feasible:
its operation modes cut to its own limits, each narrowed by state-of-charge reachability and dropped when reachability empties it.
Whether and when the device changes mode is the controller's policy; a reacting device rounds a value in a hole
to the edge on the side of its current mode, which at the start of a slot is the plan's range.

The reachability analysis now narrows by the state-of-charge limits as given, before relaxation turns any of them into
priced commitments: a reaction must not breach a target the planner stayed under, even where the plan may breach it at a price.
The plan's own relaxation is unchanged.

A device reacts when the price kink is within its reach and its band is more than a single point,
so an idle plan with a charging range left feasible reacts, against the balance point when its miss is mode-shaped.

Tests: an idle charger facing a surplus (balance point 0.0, every range served, the client rule rounding a value in the hole
to the plan's side), the same with a soft soc-max the charging would breach (a one-point band, no reaction),
and the earlier scenarios with every feasible range listed; each proven to fail with its item reverted.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WGt2vUmJ4goxUYxexuArDE
Signed-off-by: F.N. Claessen <claessen@seita.nl>

@Flix6x Flix6x left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Self-review after running this end to end with the client (FlexMeasures/flexmeasures-client#299) on a home after saldering: one phase of 25 A (site-power-capacity 5.75 kW), house load and PV forecasts, hourly prices with the production price below the consumption price all day, and a V2G charger with the Quasar's dead zone as operation-modes and react: true stored on its asset. The opt-in works from the stored flex-model on an asset-level trigger, a trigger with react: false gets today's payload exactly, and the client parses all 288 rules (react 1 in 278 slots). Replaying a day with seven scripted surprises through the client's react() cut the cost at the meter from € 1.66 to € 0.57 and the slots over the fuse from 16 to 4. Three bugs and two contract points to fix before asking for review:

Bugs

  1. A capacity counts as binding whenever the plan is within the dead zone of it, and that overrides the price kink. _intended_connection_power marks the site capacity as binding when net >= emax - tolerance (storage.py:3857), and the tolerance is widened to the widest gap in a reacting device's band (storage.py:3972), 1.4 kW for the Quasar. At 11:00–11:20 and 15:40–15:55 the plan imports 4.4–4.6 kW against the 5.75 kW fuse while production is cheaper, so the intended power should be 0. It becomes 5.75 instead, the power that would reach it (8.5 kW) is out of the charger's reach, and those 9 slots get react 0 with a band of just the plan. A passing cloud at 11:00 then keeps the meter at 6.49 kW, over the fuse, for 4 slots, where a reacting slot would have backed off; these are the only slots over the fuse in a day with seven surprises, so this bug is what stands between the rules and zero. Please fix all three parts: test "binds" with the float tolerance, use the gap tolerance only for a mode-shaped miss (_mode_shaped_miss), and keep the price kink where the capacity is out of reach; and add a test for a plan less than the dead zone below the fuse with production cheaper (expect react 1). Only falling back to the kink when the capacity is out of reach would fix this day, but would still call the fuse binding with up to 1.4 kW of headroom: with the charger planned a bit lower, 5.75 kW becomes reachable, the slot keeps aiming at the fuse, and where the modes make the plan miss, the reference becomes the capacity minus the plan, so a house exactly as forecast looks like a surprise of over 1 kW and the charger is pushed up towards the fuse.
  2. A device without react still gets a reaction array. Once any device opts in, the rules of every flexible device go into the job meta (scheduling.py:1127) and the API serves them. A home battery without react got 96 entries, all react 0. The OpenAPI text (sensors.py:1424) says the array is "only present when the device's flex-model set react to true", and #2894's acceptance says such a device has no rules; test_device_without_react_gets_no_share pins the react-0 entries instead. Please serve reaction only for devices with react: true, as the docs and #2894 promise, and turn that test into one that checks the key is absent.
  3. Rules on a sensor coarser than the scheduling resolution. _build_recourse_response forward-fills the stored 5-minute rules onto the served index (sensors.py:159), so a 15-minute slot gets its first sub-slot's rule. For the battery above (15-minute sensor next to a 5-minute charger) the band is the point of the first sub-slot while the value is the 15-minute mean: the plan lies outside its own band in 21 of 96 slots. V2G-Liberty's parser (V2G-liberty/addon-v2g-liberty#529) refuses that and drops the whole array. Please aggregate the rules per served slot, or serve react 0 with [[v, v]] where the sub-slots differ, and add a test with a sensor coarser than the scheduling resolution that checks every served value lies in its band.

Contract

  1. The reference is shifted where the operation modes make the plan miss the kink. At 07:00 the house is forecast at 1.15 kW, the plan sits at −1.4 kW (the dead zone's edge), and the reference is 1.4 kW, so a house exactly as forecast shows a surprise of −0.25 kW. react() rounds that back to the plan, so the setpoint is right, and the docs explain it; but the contract in #2894 and in V2G-Liberty's fixtures says "the uncontrolled power the plan assumed", and V2G-Liberty's shadow sensor will show a surprise when nothing happened. Keep the shift, but fix the interpretation: as it stands, a house exactly as forecast produces a "surprise", an expected surprise, which is a contradiction in terms (and one we feared during development). Define reference as the uncontrolled power the plan is balanced against, and call m_uncontrolled − reference the deviation from that balance point rather than the surprise; where the modes make the plan miss the kink, that deviation is expected to be non-zero and react() rounds it back to the plan. Please write this into #2894's contract, the docs, the OpenAPI text and the client's docs (FlexMeasures/flexmeasures-client#299), and tell V2G-Liberty (its fixtures README repeats the old wording), whose shadow sensor should not show m_uncontrolled − reference as a surprise (if a real surprise is wanted there, the rules would also need to carry the forecast, or the miss).
  2. Define "the price kink". The docs (flexibility-configuration.rst:520), the OpenAPI text (sensors.py:1437) and the changelog all say react is 1 "where the price kink is within the device's reach", and list when there is one, but never say what it is: the bend in the cost of the connection as a function of net power, at 0 kW where importing costs the consumption price and exporting earns only the lower production price (or at a capacity that binds), so the plan sits there and a surprise is best absorbed. A sentence or a small picture in the docs before the term is used.
  3. Absorbing a surprise costs the device energy, and nothing in the rules gives it back. In the walk (open loop: no retrigger, no fuse guard) the car got 24.6 kWh instead of the plan's 28.3, the energy the clouds and the oven took, so it would miss its 50 kWh at 07:00. The design leaves that to a retrigger, but the contract and docs do not say so. Please state that a controller following the rules must retrigger after it absorbs (and when, e.g. once the SoC drifts by some amount, and before a target), and add a test or example that closes the loop: react, retrigger, target met. Otherwise a missed retrigger leaves a car short in the morning without anything flagging it.
  4. The PR description is stale: it still says a band side is null where the device has no limit (since de6adf4 every side is finite), and describes the earlier react classifier rather than "the price kink is within the device's reach".

Smaller

  • One thing, three names: recourse_rules / "recourse_rule" / _build_recourse_response in the code and job meta, reaction in the API, include_response and RESPONSE_DIRECTIONS. Settling on "reaction" in the code too would help readers.
  • The rules live only in the job meta, so they expire with the job; worth a line in the docs, and a follow-up if a controller needs the rules of a schedule it read from sensor data.

The tests I ran (test_recourse.py, the API round trip, the two schema tests: 43 passed) do not cover the three bugs.

Flix6x and others added 15 commits November 26, 2026 22:56
The capacity counted as binding whenever the plan sat within a reacting device's widest mode gap of it,
which on a one-phase connection with a charger's 1.4 kW dead zone made every slot importing near the fuse a capacity slot,
with a balancing power beyond the charger's reach: react 0 and a point band, exactly where the price kink was within reach.

The capacity now binds only where the plan sits on it within the float tolerance;
the mode gap matters only to tell a mode-shaped miss (see _mode_shaped_miss);
and a capacity kink the device cannot reach falls back to the price kink, where there is one.

A new test keeps a plan 0.35 kW below a 5.75 kW fuse reacting at the price kink against the forecast,
and the hand-verified test keeps a plan exactly at the fuse on the capacity kink.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WGt2vUmJ4goxUYxexuArDE
Signed-off-by: F.N. Claessen <claessen@seita.nl>
Once one device opted in, every flexible device's rules went into the job meta and were served,
so a device without `react` got a reaction array of nothing but zeros.
The scheduler now emits rules only for the devices whose flex-model set `react`,
as the API docs promise; the others get no `reaction` key.

Tests: the planning test asserts the second battery gets no rules at all,
and an API round trip over a two-device asset schedule asserts the key is present for the opted-in device only.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WGt2vUmJ4goxUYxexuArDE
Signed-off-by: F.N. Claessen <claessen@seita.nl>
Rules are stored at the scheduling resolution, and were forward-filled onto the served index,
so a 15-minute sensor scheduled at 5 minutes got the rule of its first sub-slot,
whose band need not contain the served value, which is the mean of three sub-slot plans.

Per served slot, the rules overlapping it are now gathered.
Where they all agree (the same react, the same reference and identical bands) and the served value lies within that band,
that rule is served; otherwise the slot gets react 0, the mean of the sub-slot references, and the served value as its band.
The band check allows for the scheduler's rounding of the plan to 1e-6 MW, converted to the served unit.

Tests: unit tests of the aggregation (agreeing, disagreeing and out-of-band slots on a coarser sensor, and a finer sensor),
and an API round trip with a 15-minute battery next to a 5-minute one, asserting every served value lies within its band
and agreeing slots keep react 1. Both fail with the forward-fill behaviour restored, and with agreement never recognized.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WGt2vUmJ4goxUYxexuArDE
Signed-off-by: F.N. Claessen <claessen@seita.nl>
… the retrigger duty

Context:
- The self-review of PR #2905 found the reaction docs called m_uncontrolled - reference the surprise,
  although in a mode-shaped slot it is non-zero for a house exactly as forecast;
  used "the price kink" without defining it;
  and left implicit that absorbing a deviation drains (or fills) the device with nothing in the rules to make up for it.

Change:
- Define the price kink before its first use.
- Define the reference as the uncontrolled power the plan is balanced against, and name m_uncontrolled - reference the deviation from the balance point,
  explaining why it is non-zero in a mode-shaped slot and how the client's rounding returns the plan.
- State the retrigger obligation: once the state of charge has drifted by a set amount from the plan, and in any case before a target.
- Describe how rules are served on a sensor coarser than the scheduling resolution.
- Note that the rules live in the job's meta and expire with the job.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WGt2vUmJ4goxUYxexuArDE
Signed-off-by: F.N. Claessen <claessen@seita.nl>
…ce point

Context:
- The API text called m_uncontrolled - reference the surprise, used "the price kink" without defining it,
  and said nothing about retriggering after absorbing a deviation (self-review of PR #2905).

Change:
- OpenAPI text of the schedule response: define the price kink, the reference as the uncontrolled power the plan is balanced against,
  and m_uncontrolled - reference as the deviation from the balance point, non-zero in a mode-shaped slot for a house exactly as forecast;
  state the retrigger obligation and how a sensor coarser than the scheduling resolution is served.
- Same wording in the scheduler docstring, the `react` field description and a test docstring.
- Regenerated OpenAPI spec (wording only).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WGt2vUmJ4goxUYxexuArDE
Signed-off-by: F.N. Claessen <claessen@seita.nl>
Context:
- The docs and API text now define the reference, the deviation from the balance point and the price kink (self-review of PR #2905).

Change:
- Main changelog: a deviation at the connection, with the price kink explained in passing.
- API changelog: the deviation formula with m_uncontrolled, and the retrigger after absorbing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WGt2vUmJ4goxUYxexuArDE
Signed-off-by: F.N. Claessen <claessen@seita.nl>
…nd retriggering

Context:
- Absorbing a deviation costs the device energy that nothing in the rules makes up for,
  so the docs now oblige a controller to retrigger after absorbing (self-review of PR #2905).

Change:
- A new test absorbs 2 kW of missing sun in the first slot of a plan with a hard target, following the served rules,
  asserts the state of charge ends that slot 2 kWh short and that the rest of the old plan would miss the target by as much,
  then re-schedules from the second slot with the lower soc-at-start and asserts the target is met.
- `_compute_recourse` takes an optional start for that re-schedule.

Re-scheduling from the planned instead of the reached state of charge turns the test red.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WGt2vUmJ4goxUYxexuArDE
Signed-off-by: F.N. Claessen <claessen@seita.nl>
Context:
- The API and docs speak of reaction rules, while the code still said recourse and response (self-review of PR #2905).

Change:
- _compute_recourse_rules -> _compute_reaction_rules, the "recourse_rule" result name -> "reaction_rule",
  the "recourse_rules" job-meta key -> "reaction_rules", _build_recourse_response -> _build_reaction_response,
  include_response -> include_reaction, RESPONSE_DIRECTIONS -> REACTION_DIRECTIONS.
- Test module test_recourse.py -> test_reaction.py, with its helper, site and source names;
  test_trigger_and_get_schedule_with_recourse_response -> test_trigger_and_get_schedule_with_reaction.
- No behaviour change; the job-meta key is new in this unreleased PR, so no stored jobs depend on the old one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WGt2vUmJ4goxUYxexuArDE
Signed-off-by: F.N. Claessen <claessen@seita.nl>
Context:
- Since 47deda1 the scheduler emits reaction rules only for devices that set `react`,
  but two docstrings still promised an entry per flexible device; one also called the reference the power the plan assumed.

Change:
- Docstring wording only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WGt2vUmJ4goxUYxexuArDE
Signed-off-by: F.N. Claessen <claessen@seita.nl>
…commits

I, F.N. Claessen <claessen@seita.nl>, hereby add my Signed-off-by to this commit: fdf6f3a
I, F.N. Claessen <claessen@seita.nl>, hereby add my Signed-off-by to this commit: 26afcbb
I, F.N. Claessen <claessen@seita.nl>, hereby add my Signed-off-by to this commit: 4c707b2
I, F.N. Claessen <claessen@seita.nl>, hereby add my Signed-off-by to this commit: aa1bc3f
I, F.N. Claessen <claessen@seita.nl>, hereby add my Signed-off-by to this commit: bd148c9

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DWv6v3Si6BJGYopSg6tSDk
Signed-off-by: F.N. Claessen <claessen@seita.nl>
…band

A reacting slot is at the kink when its planned connection power equals the intended power,
when it misses it only because of the device's operation modes, or when a capacity binds.
Off the kink, absorbing a deviation that pushes the connection further away from the kink is neutral at best,
and harmful at the device's power limit (e.g. cutting charging under a cloud, to buy the energy back later at a higher price),
so the band keeps only the side of the plan that absorbs deviations towards the kink.
Where that leaves a single point, the device gets react 0.

Narrowing a band to a direction now goes through one helper, also used for the internal reaction directions.
Two existing expectations change: the negative feed-in charger at its full stock and the charger just below the fuse at its power limit are both off the kink, with nothing left on the kink's side, so they get react 0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WGt2vUmJ4goxUYxexuArDE
Signed-off-by: F.N. Claessen <claessen@seita.nl>
State in the reaction-rules docs, the OpenAPI description of the band and the #2905 changelog entries that off the kink the device absorbs deviations that would push the connection across the kink, and follows the plan against deviations that push it further away,
so that a deviation away from the kink leaves a residual outside the band: an expected band exit, which a controller may treat as a reason to re-plan.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WGt2vUmJ4goxUYxexuArDE
Signed-off-by: F.N. Claessen <claessen@seita.nl>
… the symmetric band at it

Off the kink the band is one-sided on either side of the kink, and fixed around the plan rather than a ratchet:
a discharging battery at its limit while exporting now mirrors the charger at its limit while importing,
the importing and exporting tests check that the setpoint returns to the plan once the deviation is gone,
and the clouds test checks that a cloud is not absorbed off the kink, while its first slot, at the kink, absorbs a deviation either way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WGt2vUmJ4goxUYxexuArDE
Signed-off-by: F.N. Claessen <claessen@seita.nl>
The stored plan is rounded (to 6 decimals in the sensor's unit) while the reaction rules keep full precision,
so a band side that equals the plan, as in every react-0 band and at the plan's edge of a one-sided band off the kink,
was served up to a rounding step away from the served value (0.4 mW below a one-sided band on the demo home).
Such a side is now set to the served value, so the plan lies in its own band exactly, without relying on a client's tolerance.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DWv6v3Si6BJGYopSg6tSDk
Signed-off-by: F.N. Claessen <claessen@seita.nl>
@Flix6x
Flix6x merged commit 757d767 into main Nov 27, 2026
11 checks passed
@Flix6x
Flix6x deleted the feat/recourse-rules-v2 branch November 27, 2026 12:36
Flix6x added a commit that referenced this pull request Dec 1, 2026
The only conflict was in the changelog's Bugfixes list: keep main's lines and drop this PR's own line,
since react is new in 1.2.0, so no release ever had this bug.
Instead, the New features entry for react (#2905) now also links this PR.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: F.N. Claessen <claessen@seita.nl>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Serve per-slot recourse rules with schedules: reference, gain and band for a home controller

1 participant