Repository navigation
feat(control): default to energy-allocation dispatch - #124
Conversation
…opt-out The plan/EMS contract (docs/plan-ems-contract.md) has been sitting half-wired behind an opt-in flag since its design PR. This PR flips the default: every planner-mode cycle now uses the energy-allocation path where the plan allocates battery Wh per slot and the EMS derives instantaneous power from live telemetry. `planner.legacy_dispatch: true` opts back to the old PI-on-grid-target path for emergency rollback only. Why this matters — observed incidents that the legacy path produced but the energy path prevents: - xorath (2026-04-17): forecast PV 700 W, actual 4.8 kW, arbitrage mode. Legacy PI drove grid toward the plan's target and absorbed the PV surprise into the battery instead of exporting at peak price. Existing TestEnergyDispatchDoesNotAbsorbPVSurprise already pins this regression. - Fredrik (2026-04-19 morning, self_consumption): plan forecasted load 3.2 kW but actual was ~300 W. Under legacy PI the battery eventually backed off toward 0 to pin grid to 0, fighting the plan's intent. New test TestEnergyDispatchHoldsPlanWhenLoadForecastWrong asserts the energy path maintains the plan's battery setpoint and lets grid be whatever physics dictates. - Erik's -8 kW peak export (2026-04-18 22:00): arbitrage plan set a highly negative grid_target via actionToSlot. PI chased it, dumping 8 kW of battery output to grid regardless of live SoC depletion. Energy path replaces this with "plan says discharge X Wh total for the slot", which the EMS clamps naturally against per-driver max-discharge and SoC floor every tick. Config migration: the YAML key renames from `use_energy_dispatch` (opt-in) to `legacy_dispatch` (opt-out). Previously the zero-value meant "legacy" — still the zero-value, but now means "energy", so existing configs silently upgrade to the correct path. Anyone who had explicitly set `use_energy_dispatch: true` also upgrades (the field is ignored; the default is already what they wanted). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a7bf5395c3
ℹ️ 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".
| // respects the principle "plan allocates energy, EMS reacts to | ||
| // live data" and is the correct architecture (see | ||
| // docs/plan-ems-contract.md). | ||
| LegacyDispatch bool `yaml:"legacy_dispatch,omitempty" json:"legacy_dispatch,omitempty"` |
There was a problem hiding this comment.
Keep accepting legacy planner dispatch config key
This change removes planner.use_energy_dispatch entirely, but config parsing still uses non-strict yaml.Unmarshal in Parse, so old configs are silently accepted while that field is ignored. Combined with the new default in main.go (UseEnergyDispatch now true unless legacy_dispatch is set), any existing deployment that explicitly set use_energy_dispatch: false will unexpectedly flip to energy-allocation dispatch after upgrade with no warning. Please keep a backward-compatible alias (or explicit migration/error) so prior operator intent is preserved.
Useful? React with 👍 / 👎.
Five issues surfaced by the chatgpt-codex-connector bot across the batch of planner-overhaul PRs shipped earlier today. None catastrophic on Fredrik's current Pi, but all real bugs we'd hit as soon as a second deployment wanted to behave differently. PR #119 P2 — reasonFor() "absorb PV surplus" branch Condition was `!gridExports` which missed both edges: - partial PV absorption (battery charges, grid still exports residual) got labelled generic "charge" - over-charging (battery pulls more than PV provides, grid actually imports) got labelled "absorb PV surplus" Flipped to `!gridImports`. Added two test cases tracing both scenarios (reason_test.go). PR #121 P1 — hot-reload doesn't propagate capacity to MPC `buildMPC` computed totalCap/maxCharge/maxDischarge inline and stored them in `Service.Defaults`. Adding or removing an EV loadpoint via config-reload updated the dispatch-side capacity map but the planner kept optimising against the startup snapshot; SoC% and terminal credit went stale until process restart. - Hoisted the aggregation into `aggregateBatteryLimits()` in main.go so the reload closure can reuse it. - Added `mpc.Service.UpdateCapacity()` which takes the service mutex and swaps Defaults.CapacityWh / Max{Charge,Discharge}W. - Reload closure now calls it after the capacities map is rewritten. PR #121 P2 — invalid loadpoints still exclude drivers `driverCapacitiesFrom` treated any non-empty `driver_name` as an EV reference, but `loadpoint.Manager.Load` rejects rows with empty `id`. Means a malformed config row could silently drop a real battery from the MPC pool. Now requires `lp.ID != ""` before using the driver_name. Same guard applied to `warnIfEVHasBatteryCapacity`. Added regression test. PR #122 P1 — strict SC bias breaks EV deadline priority The 3× multiplier on self_consumption import cost applied to the TOTAL gridKWh (house + EV). Deadline shortfall is penalised at 4× meanPrice. At slot price > 4/3 × meanPrice the DP preferred missing the deadline over charging the EV at peak-hour prices. Rewrote the bias as a +2× effPrice additive penalty on the HOUSE portion of grid import only (load + PV + battery). EV import keeps its plain cost so deadline math stays honest. New test reproduces a 3-slot peak-deadline scenario that starves under the old bias and succeeds under the new one. PR #124 P1 — removed use_energy_dispatch without back-compat Renamed the opt-in field to an opt-out (`legacy_dispatch`) but dropped the old key entirely. Non-strict yaml.Unmarshal silently ignores unknown fields → an operator who explicitly set `use_energy_dispatch: false` (picked legacy on purpose) would silently flip to the energy path on upgrade. Added the field back as `*bool` so main.go can distinguish "unset" (nil) from "explicitly false" and honor prior intent, with a deprecation WARN on startup. Full `go test ./...` incl. e2e stays green. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Five issues surfaced by the chatgpt-codex-connector bot across the batch of planner-overhaul PRs shipped earlier today. None catastrophic on Fredrik's current Pi, but all real bugs we'd hit as soon as a second deployment wanted to behave differently. PR #119 P2 — reasonFor() "absorb PV surplus" branch Condition was `!gridExports` which missed both edges: - partial PV absorption (battery charges, grid still exports residual) got labelled generic "charge" - over-charging (battery pulls more than PV provides, grid actually imports) got labelled "absorb PV surplus" Flipped to `!gridImports`. Added two test cases tracing both scenarios (reason_test.go). PR #121 P1 — hot-reload doesn't propagate capacity to MPC `buildMPC` computed totalCap/maxCharge/maxDischarge inline and stored them in `Service.Defaults`. Adding or removing an EV loadpoint via config-reload updated the dispatch-side capacity map but the planner kept optimising against the startup snapshot; SoC% and terminal credit went stale until process restart. - Hoisted the aggregation into `aggregateBatteryLimits()` in main.go so the reload closure can reuse it. - Added `mpc.Service.UpdateCapacity()` which takes the service mutex and swaps Defaults.CapacityWh / Max{Charge,Discharge}W. - Reload closure now calls it after the capacities map is rewritten. PR #121 P2 — invalid loadpoints still exclude drivers `driverCapacitiesFrom` treated any non-empty `driver_name` as an EV reference, but `loadpoint.Manager.Load` rejects rows with empty `id`. Means a malformed config row could silently drop a real battery from the MPC pool. Now requires `lp.ID != ""` before using the driver_name. Same guard applied to `warnIfEVHasBatteryCapacity`. Added regression test. PR #122 P1 — strict SC bias breaks EV deadline priority The 3× multiplier on self_consumption import cost applied to the TOTAL gridKWh (house + EV). Deadline shortfall is penalised at 4× meanPrice. At slot price > 4/3 × meanPrice the DP preferred missing the deadline over charging the EV at peak-hour prices. Rewrote the bias as a +2× effPrice additive penalty on the HOUSE portion of grid import only (load + PV + battery). EV import keeps its plain cost so deadline math stays honest. New test reproduces a 3-slot peak-deadline scenario that starves under the old bias and succeeds under the new one. PR #124 P1 — removed use_energy_dispatch without back-compat Renamed the opt-in field to an opt-out (`legacy_dispatch`) but dropped the old key entirely. Non-strict yaml.Unmarshal silently ignores unknown fields → an operator who explicitly set `use_energy_dispatch: false` (picked legacy on purpose) would silently flip to the energy path on upgrade. Added the field back as `*bool` so main.go can distinguish "unset" (nil) from "explicitly false" and honor prior intent, with a deprecation WARN on startup. Full `go test ./...` incl. e2e stays green. Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
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]>
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]>
Summary
Flips the dispatch-layer default: every planner-mode cycle now uses the energy-allocation path where the plan allocates battery Wh per slot and the EMS derives instantaneous power from live telemetry. Closes the architectural gap the user surfaced on 2026-04-19: "EMS ska ju ALLTID reagera i realtid på riktig data. Den ska ALDRIG reagera på vad planeraren säger. Planeringen är ju just vad den är. En planering som sätter STRATEGI till EMS."
The infrastructure has been sitting behind an opt-in flag since the design PR. This lights it up.
Why this matters
Three field incidents the legacy PI-on-grid-target produced but the energy path prevents:
+ "TestEnergyDispatchDoesNotAbsorbPVSurprise" +.+ "TestEnergyDispatchHoldsPlanWhenLoadForecastWrong" +.Config migration
YAML key renames from
+ "use_energy_dispatch" +(opt-in) to+ "legacy_dispatch" +(opt-out). Zero-value meaning stays the same ("don't set it and you get the right behavior"). No-op for existing production configs.Test plan
+ "go test ./..." +incl. e2e stays green🤖 Generated with Claude Code