Repository navigation
feat(mpc): strict self_consumption — discharge before grid import (investigation PR 4/4) - #122
Conversation
## Incident B Fredrik, 2026-04-19 08:19, self_consumption mode, SoC ~50% of a (then inflated) 99.8 kWh pool. Plan: battery = 0 W, grid = 2.09 kW import at 166 öre. Operator intent: "I picked self_consumption, USE my battery." DP's behaviour: preserve SoC because horizon mean is higher and imports get cheaper later — classic cost-minimising arbitrage reasoning dressed up as self_consumption. ## Fix In the DP inner loop, when Mode == ModeSelfConsumption and the current-slot battery SoC is above SoCMinPct + 20, multiply the slot import cost by 3 before adding to the cumulative DP objective. Result: any action that REDUCES import (discharge-to-cover-load) is strictly cheaper than idle regardless of the terminal-SoC credit arithmetic. - `soc > p.SoCMinPct + 20` floor prevents the DP from draining a near-empty battery to cover a big load on a cloudy morning. - Factor 3 is tuned so `import_cost × 3` beats `terminal_credit × discharge_eff` for any reasonable `TerminalSoCPrice ≤ retail_mean` (the realistic regime). - Applied throughout the horizon, not just the first few slots — operator intent is persistent, not transient. If SoC drops below the floor, the DP naturally reverts to ordinary cost reasoning. ## Tests - `TestStrictSelfConsumptionDischargesWhenSoCHealthy` — Fredrik's 08:19 scenario (50 % SoC, 166 öre, baseline 2.09 kW import). Expect: first-slot BatteryW < -100 W. - `TestStrictSelfConsumptionBacksOffNearSoCFloor` — 15 % SoC (floor+5). Expect: DP doesn't force aggressive discharge. - `TestOptimizeSelfConsumptionDischargesDespiteHighTerminal` — repurposes the old "OLD behaviour" guardrail that was documenting the exact issue we're now fixing. Inverted expectation: strict SC discharges even when terminal = retail mean. - `go test ./...` incl. e2e — green. ## What this DOES NOT do - Doesn't change arbitrage or cheap_charge behaviour — only self_consumption. The operator asked for a strict "use my battery" policy; the other modes stay optimisation-driven. - Doesn't eliminate confidence-blend effects on forecasted slots — those still pull toward horizon mean. (Follow-up: C5 in the investigation plan.) 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: 217516fe43
ℹ️ 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".
| if p.Mode == ModeSelfConsumption && | ||
| gridKWh > 0 && | ||
| soc > p.SoCMinPct+20 { | ||
| cost *= 3.0 |
There was a problem hiding this comment.
Limit strict-SC import penalty to battery-driven import
This multiplies the cost of every importing action in self_consumption whenever SoC is above the floor, including grid import required for EV/loadpoint charging. In deadline slots, the shortfall penalty is still 4 * meanPrice per kWh, so for high-price slots (slot price > 4/3 * meanPrice) the DP can now prefer missing a feasible EV target over charging it, because the tripled import term dominates. That breaks the deadline-priority behavior described in this function and can leave vehicles undercharged in real high-price windows; the multiplier should only apply to battery-caused import reduction logic, not total gridKWh.
Useful? React with 👍 / 👎.
PR #121 filtered EV drivers from the MPC battery-pool aggregation by matching against `loadpoints[].driver_name`. That works when the operator has migrated to a `loadpoints:` config block, but Fredrik's production Pi has no loadpoints section — so the easee driver's `battery_capacity_wh: 75000` (vehicle capacity) still inflates the MPC pool from ~24.8 kWh to ~99.8 kWh, which is the root cause of the "morning grid import at 50% SoC" incident the strict self_consumption bias (PR #122) was supposed to address. Add a narrow filename-prefix allowlist (easee, ocpp, ctek, chargestorm) as a fallback so the filter fires even without a loadpoints block. Applies the same check to `warnIfEVHasBatteryCapacity` with a slightly different WARN wording so operators know whether the detection came from config reference or filename heuristic. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
) PR #121 filtered EV drivers from the MPC battery-pool aggregation by matching against `loadpoints[].driver_name`. That works when the operator has migrated to a `loadpoints:` config block, but Fredrik's production Pi has no loadpoints section — so the easee driver's `battery_capacity_wh: 75000` (vehicle capacity) still inflates the MPC pool from ~24.8 kWh to ~99.8 kWh, which is the root cause of the "morning grid import at 50% SoC" incident the strict self_consumption bias (PR #122) was supposed to address. Add a narrow filename-prefix allowlist (easee, ocpp, ctek, chargestorm) as a fallback so the filter fires even without a loadpoints block. Applies the same check to `warnIfEVHasBatteryCapacity` with a slightly different WARN wording so operators know whether the detection came from config reference or filename heuristic. 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]>
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]>
Summary
Part 4 of 4 in the planner-logic investigation round. Closes the gap between operator intent ("I picked self_consumption — use my battery") and DP behaviour ("preserve SoC for tomorrow's peak").
The bug (Incident B, confirmed live)
Fredrik 2026-04-19 08:19, mode =
self_consumption, SoC ≈ 50 % of a then-inflated 99.8 kWh pool (PR #121 fixes the pool inflation separately), first-slot load 3.48 kW, PV -1.39 kW, price 166 öre. Plan:battery = 0 W,grid = 2.09 kW import.The DP's arithmetic: terminal credit at ~107 öre/kWh × 0.5 kWh discharge ≈ 54 öre saved terminal, vs ~83 öre import avoided. Discharge should have won. It didn't — because forecasted-horizon mean is 183 öre, and the DP sees cheaper future slots to preserve SoC for. Classic arbitrage reasoning that happens to be dressed up as self_consumption.
Fix
Bias the DP cost function so that whenever
Mode == ModeSelfConsumptionANDsoc > SoCMinPct + 20, grid-import slots cost 3× what the DP would otherwise see. Discharge-to-cover-load stays at normal cost. Consequence: any action that reduces import beats idle, regardless of terminal arithmetic.Properties:
SoC ≥ SoCMinPct + 20 %— stops the DP from draining a near-empty battery to cover a big morning load.import_cost × 3beats any reasonableTerminalSoCPrice × discharge_eff × kWh. Well above the 5 % efficiency loss of cycling.self_consumption.arbitrageandcheap_chargeare untouched — those modes are the operator saying "do what's cheapest".Tests
TestStrictSelfConsumptionDischargesWhenSoCHealthy— Fredrik's exact 08:19 scenario (50 % SoC, 166 öre, baseline 2.09 kW import). Asserts first-slotBatteryW < -100 W.TestStrictSelfConsumptionBacksOffNearSoCFloor— 15 % SoC (floor+5). DP doesn't force aggressive discharge.TestOptimizeSelfConsumptionDischargesDespiteHighTerminal— repurposed guardrail: now asserts DP discharges even whenTerminalSoCPrice = retail_mean. (Old version documented that exactly this case was broken.)go test ./...incl. e2e — green.What this does NOT do
modeAllows— self_consumption still forbids grid-to-battery charging and battery-to-grid export.After deploy
Fredrik's next self_consumption replan should show
battery_w < 0for every slot where SoC > 30 % and grid is importing. Compare with the pre-deploy diag snapshot already persisted — delta should be measurable.🤖 Generated with Claude Code