Repository navigation
fix(mpc): reasonFor branches on gridW + replan log breadcrumbs (investigation PR 1/4) - #119
Conversation
## Incident C — label said "cover local load" while grid exported hard Erik's 2026-04-18 22:00 arbitrage plan showed battery -8 kW discharge + grid -6.6 kW export, reason "discharge — cover local load". The old label logic branched only on `baseline = load + pv`, never on the post-action grid direction. Any discharge-that-results-in-export mislabelled as cover-load. Made Erik unable to judge whether the behaviour was correct arbitrage or a bug. New reasonFor(slot, actW, gridW, meanPrice) branches on the gridW resulting from the action: - discharge + grid exports + price > mean × 1.1 → "export at peak" - discharge + grid exports (any price) → "export" - discharge + price > mean × 1.1 (no export) → "price above horizon mean" - discharge + baseline importing (grid > 100) → "cover local load" - discharge (other) → "discharge" - charge + grid imports + price < mean × 0.9 → "charge from cheap grid" - charge + grid imports → "charge — import" - charge + baseline exporting → "absorb PV surplus" - idle + grid imports/exports/zero as before ## Replan log breadcrumbs Post-hoc debugging of "why did the planner decide X?" previously required pulling the full Diagnostic JSON. Now one INFO line per replan surfaces the three factors that explain 90 % of surprises: horizon mean_price_ore + mean_confidence, terminal_soc_price_ore, capacity_wh, max_charge_w / max_discharge_w. Cheap — already had the inputs in scope at the log point. ## Tests TestReasonForLabelsBranchOnGridW — 7 cases covering Incident C plus the complementary branches (cheap-grid charge, peak-shave without export, idle variants). `go test ./...` incl. e2e green. Part of the planner-logic investigation round — see the plan file. PR 2 (Sungrow PV), PR 3 (EV-capacity split), PR 4 (strict self_consumption) follow. 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: 5580bab4b1
ℹ️ 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".
| case batteryW > chargeThresh && baseline < -chargeThresh: | ||
| // Exporting baseline, battery charging → absorbing PV surplus. | ||
| // --- charging branches --- | ||
| case batteryW > chargeThresh && baseline < -chargeThresh && !gridExports: |
There was a problem hiding this comment.
Fix charge label branch to match resulting grid direction
The new grid-based reason classifier uses !gridExports for the "absorb PV surplus" branch, which inverts the intended flow classification: charging while still exporting now falls through to generic "charge", while charging that has already flipped to import is still labeled as PV absorption and can never reach "charge — import" / "charge from cheap grid". This makes the per-slot explanation misleading in common midday PV scenarios and undermines the operator-facing diagnosis this change is trying to improve.
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]>
Summary
Part 1 of 4 in the planner-logic investigation round (see plan file). Ships independently.
Incident C — "cover local load" label for a heavy export
Erik @erikarenhill's 2026-04-18 22:00 arbitrage plan: battery -8 kW discharge + grid -6.6 kW export, reason "discharge — cover local load". The old label logic branched on baseline (
load + pv) only, never on the post-action gridW. Any discharge-that-results-in-export got mislabelled. Made Erik unable to tell defensive discharge from peak-export arbitrage.Fix
reasonFor(slot, actW, gridW, meanPrice)— new signature takes gridW, branches on it:discharge — export at peakdischarge — exportdischarge — price above horizon meandischarge — cover local loadcharge from cheap gridcharge — importabsorb PV surplusidle — import to cover loadidle — export PV surplusOld behaviour where baseline-direction decided is gone.
Replan log breadcrumbs
Post-hoc "why did the planner decide X?" previously required pulling the full Diagnostic JSON. Now one INFO line per replan surfaces:
The three fields that explain 90 % of surprises (horizon mean price, confidence-weighting, terminal SoC valuation) are always visible now.
Tests
TestReasonForLabelsBranchOnGridW— 7 cases, incl. the exact Incident C numbers.go test ./...incl. e2e — green.What this does NOT do
🤖 Generated with Claude Code