Skip to content

fix(control): planner_self executes as reactive self-consumption - #131

Merged
frahlg merged 1 commit into
masterfrom
130-planner-self-reactive
Apr 19, 2026
Merged

frahlg merged 1 commit into
masterfrom
130-planner-self-reactive

Conversation

@frahlg

@frahlg frahlg commented Apr 19, 2026

Copy link
Copy Markdown
Member

Closes #130.

Summary

  • planner_self now runs reactive PI-on-gridW=0 (identical to manual self_consumption) with a plan-driven per-slot idle gate. When the DP allocated average battery power < mpc.IdleGateThresholdW (= 100 W) for the current slot the EMS holds the battery at 0; otherwise it participates reactively and the live meter drives the power.
  • planner_cheap / planner_arbitrage are unchanged — they keep the energy-allocation path (UseEnergyDispatch=true default) where Wh-per-slot is the optimisation variable.
  • Regression guards added to go/internal/control/control_test.go; docs updated.

Root cause (from #130)

Since #124 defaulted every planner mode to energy-allocation dispatch, planner_self honoured the plan's BatteryEnergyWh regardless of live grid flow. The DP enforces ModeSelfConsumption's grid-crossing invariant only on forecast — so when the PV forecast over-estimated vs actual, the battery kept chasing the planned charge rate and pulled the shortfall from the grid, breaking the UI tooltip's "never imports to charge, never exports via the battery" promise.

The EMS must enforce the self-consumption invariant on the live meter, not on the plan. For that mode specifically, the plan becomes a participation schedule, not a power trajectory.

Architecture note

Three execution paths now live in ComputeDispatch:

Mode Execution
planner_self Reactive PI → gridW=0 + per-slot idle gate from SlotDirective.BatteryEnergyWh
planner_cheap / planner_arbitrage w/ UseEnergyDispatch=true (default) Energy-allocation (grid is the residual)
planner_cheap / planner_arbitrage w/ legacy_dispatch: true Legacy PI on grid_target_w — rollback only

See the new §Exception in docs/plan-ems-contract.md.

EV dispatch

Out of scope for this PR — ev_dispatch reads SlotDirective.LoadpointEnergyWh unconditionally and is orthogonal to the battery branch. A separate follow-up may be needed if forecast-overestimate causes the EV charger to import grid; call it out if observed in the field.

Test plan

  • go test ./... — all green (including 6 new planner_self tests + 1 repurposed energy-dispatch test)
  • make e2e — green (27 s)
  • Smoke on the Pi: flip mode to Smart self-consumption, watch /api/status + grid meter; confirm battery tracks live meter and never imports beyond baseline across a sunny slot + a cloudy slot.
  • Confirm idle-gate behaviour: during a slot the DP picks to skip, battery should ramp to 0 and grid should export full PV surplus.

Files

  • go/internal/control/dispatch.go — new planner_self switch branch, plannerSelfIdleGate short-circuit
  • go/internal/control/control_test.go — 6 new tests + 1 renamed
  • go/internal/mpc/mpc.go — exported IdleGateThresholdW constant
  • go/internal/control/CLAUDE.md, go/internal/mpc/CLAUDE.md — updated execution-path table + §What NOT to do
  • docs/plan-ems-contract.md — §Exception: planner_self
  • docs/mpc-planner.md — §Execution differs by strategy

🤖 Generated with Claude Code

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 08702e951f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +233 to +236
case state.Mode == ModePlannerSelf:
effectiveMode = ModeSelfConsumption
state.SetGridTarget(0)
planFresh := false

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Reset slot energy state when entering planner_self

This new planner_self branch bypasses the energy-allocation path but leaves state.currentDirective, state.slotDelivered, and state.lastTickTs unchanged. If an operator switches planner_cheap/arbitrage -> planner_self -> planner_cheap/arbitrage within the same 15-minute slot, the later energy cycle can skip its rollover reset (SlotStart still matches) and compute remainingWh from stale delivery state, which can over-command charge/discharge for the rest of the slot. Reset the slot-energy bookkeeping when entering planner_self (or whenever leaving the energy path) to prevent cross-mode bleed-through.

Useful? React with 👍 / 👎.

Closes #130.

Under the energy-allocation dispatch path defaulted by #124, planner_self
honoured the plan's per-slot BatteryEnergyWh regardless of live grid flow.
When the PV forecast overestimated vs actual, the battery followed the
planned charge rate and pulled the shortfall from the grid — breaking the
mode's contract ("never imports to charge, never exports via the battery")
and the UI tooltip's promise.

The DP enforces ModeSelfConsumption's grid-crossing invariant only on
forecast. The EMS must enforce it on the live meter.

planner_self now runs reactive PI-on-gridW=0 (same as manual
self_consumption), with a per-slot idle gate read off the plan: when
|SlotDirective.BatteryEnergyWh| / slot_hours < mpc.IdleGateThresholdW
the EMS holds the battery at 0, honouring the DP's decision to save SoC
for a later, more profitable slot. Otherwise the battery participates
reactively — absorbs whatever surplus actually exists, covers whatever
load actually exists. Plan stale → falls back to manual
self_consumption. planner_cheap and planner_arbitrage keep the
energy-allocation path unchanged — Wh-per-slot is the whole point there.

Tests:
- TestPlannerSelfReactsToForecastOverestimate — regression guard for the
  operator-reported bug
- TestPlannerSelfIdleGateHoldsBatteryAtZero — plan says idle, live
  surplus exists, battery stays at 0
- TestPlannerSelfParticipatesReactivelyCoveringImport — reactive
  discharge bounded by live import, not by the planned Wh magnitude
- TestPlannerSelfIdleGateRampsBatteryToZeroOverCycles — multi-cycle
  steady-state, slew respected, no integral wind-up
- TestPlannerSelfRespectsEVChargingSignal — EV subtraction still works
- TestPlannerSelfWithoutPlanActsLikeManual — plan-stale fallback
- TestEnergyDispatchHoldsPlanUnderArbitrage — existing test repurposed
  to the mode where hold-plan semantics actually apply

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@frahlg
frahlg force-pushed the 130-planner-self-reactive branch from 08702e9 to 5c02235 Compare April 19, 2026 17:37
@frahlg
frahlg merged commit 3e5afee into master Apr 19, 2026
1 check passed
@frahlg
frahlg deleted the 130-planner-self-reactive branch April 19, 2026 17:38
frahlg added a commit that referenced this pull request Apr 20, 2026
## control — slot-energy bookkeeping reset on planner_self (Codex P2 on #131)

The new planner_self branch bypasses the energy-allocation path but
previously left state.currentDirective / slotDelivered / lastTickTs
untouched. A mode hop cheap → self → cheap within the same 15-minute
slot would find SlotStart still matching on the return, skip its own
rollover-reset, and compute remainingWh off a stale slotDelivered —
over-commanding battery power for the rest of the slot.

Clear the three fields whenever the planner_self branch fires so a
later energy-path cycle always takes its intended rollover-reset
branch.

Regression test: TestPlannerSelfResetsEnergyBookkeepingOnEntry in
control_test.go exercises the three-step mode hop and asserts the
state is clean after the self cycle.

## pvmodel — freeze row/column 0 of covariance matrix (Codex P1 on #136)

With Features[0] pinned to 0.0 (dead slot since #134), the standard RLS
covariance update still divided P[0][0] by λ=0.995 every tick. Growth
compounds at ~1.005× per sample, so after ~140k successful Updates
P[0][0] overflows to +Inf; the next tick computes
  Px[0] = sum_k P[0][k] * x[k] = Inf * 0 = NaN
and the poison cascades to K, β, and every downstream prediction. At
the 1-minute daytime cadence that's months — long enough to bite in
production but easy to miss in CI.

Skip i=0 and j=0 in the covariance update loop. The two dead arrays
naturally decay to zero (the newP zero value), which matches the
desired invariant (a dead feature's covariance is zero). No growth,
no NaN, no coupling into the live coefficients.

Regression test: TestUpdatePKeepsDeadInterceptFinite runs 2000
Updates and asserts every P cell + every β coefficient stays finite;
also asserts row 0 and column 0 stay at zero so a future refactor
can't silently re-introduce the growth path.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
frahlg added a commit that referenced this pull request Apr 20, 2026
## control — slot-energy bookkeeping reset on planner_self (Codex P2 on #131)

The new planner_self branch bypasses the energy-allocation path but
previously left state.currentDirective / slotDelivered / lastTickTs
untouched. A mode hop cheap → self → cheap within the same 15-minute
slot would find SlotStart still matching on the return, skip its own
rollover-reset, and compute remainingWh off a stale slotDelivered —
over-commanding battery power for the rest of the slot.

Clear the three fields whenever the planner_self branch fires so a
later energy-path cycle always takes its intended rollover-reset
branch.

Regression test: TestPlannerSelfResetsEnergyBookkeepingOnEntry in
control_test.go exercises the three-step mode hop and asserts the
state is clean after the self cycle.

## pvmodel — freeze row/column 0 of covariance matrix (Codex P1 on #136)

With Features[0] pinned to 0.0 (dead slot since #134), the standard RLS
covariance update still divided P[0][0] by λ=0.995 every tick. Growth
compounds at ~1.005× per sample, so after ~140k successful Updates
P[0][0] overflows to +Inf; the next tick computes
  Px[0] = sum_k P[0][k] * x[k] = Inf * 0 = NaN
and the poison cascades to K, β, and every downstream prediction. At
the 1-minute daytime cadence that's months — long enough to bite in
production but easy to miss in CI.

Skip i=0 and j=0 in the covariance update loop. The two dead arrays
naturally decay to zero (the newP zero value), which matches the
desired invariant (a dead feature's covariance is zero). No growth,
no NaN, no coupling into the live coefficients.

Regression test: TestUpdatePKeepsDeadInterceptFinite runs 2000
Updates and asserts every P cell + every β coefficient stays finite;
also asserts row 0 and column 0 stay at zero so a future refactor
can't silently re-introduce the growth path.

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
frahlg added a commit that referenced this pull request May 28, 2026
Mirror what preparePlannerSelf already does (dispatch.go:797-804): when
the planner_arbitrage cover-load or planner_passive_arbitrage idle carve-
out fires, call resetEnergyDispatchBookkeeping alongside the existing
SetGridTarget(0). Otherwise slotDelivered / lastTickTs / currentDirective
keep values left over from a previous energy-path tick in the same slot,
and a future mid-slot transition back to the energy path (plan refine,
mode hop) miscomputes remainingWh.

Pure defence-in-depth — no change in steady-state cover-load reactive
behaviour. Same forward-transition risk preparePlannerSelf has guarded
against since PR #131.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
frahlg added a commit that referenced this pull request May 28, 2026
#386)

Mirror what preparePlannerSelf already does (dispatch.go:797-804): when
the planner_arbitrage cover-load or planner_passive_arbitrage idle carve-
out fires, call resetEnergyDispatchBookkeeping alongside the existing
SetGridTarget(0). Otherwise slotDelivered / lastTickTs / currentDirective
keep values left over from a previous energy-path tick in the same slot,
and a future mid-slot transition back to the energy path (plan refine,
mode hop) miscomputes remainingWh.

Pure defence-in-depth — no change in steady-state cover-load reactive
behaviour. Same forward-transition risk preparePlannerSelf has guarded
against since PR #131.

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
frahlg added a commit that referenced this pull request Sep 25, 2026
…1419)

Moves the bundled-driver pin from d44fda1 to srcfl/device-drivers
489c937 (#131). easee_cloud 1.3.3 omits power_observed_at while the
power is unchanged since the last poll, so Core stamps the reading on
arrival instead of treating a steady charge as a stale charger (#1417).

The same range brings nibe_local 1.2.0, whose Solar PV surplus feed is
off by default and triple-gated; this also closes the pin lag in #1274.


Claude-Session: https://claude.ai/code/session_01MuerPFZFG88kgu8sWVHeq7

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

planner_self imports grid when PV forecast overestimates (regression from #124)

1 participant