Skip to content

fix(mpc): reasonFor branches on gridW + replan log breadcrumbs (investigation PR 1/4) - #119

Merged
frahlg merged 1 commit into
masterfrom
fix/mpc-reason-label-gridw
Apr 19, 2026
Merged

frahlg merged 1 commit into
masterfrom
fix/mpc-reason-label-gridw

Conversation

@frahlg

@frahlg frahlg commented Apr 19, 2026

Copy link
Copy Markdown
Member

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:

Battery Grid Price Label
discharge exports > mean×1.1 discharge — export at peak
discharge exports (any) discharge — export
discharge ~zero > mean×1.1 discharge — price above horizon mean
discharge imports (any) discharge — cover local load
charge imports < mean×0.9 charge from cheap grid
charge imports (any) charge — import
charge exports (any) absorb PV surplus
idle imports idle — import to cover load
idle exports idle — export PV surplus

Old 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:

mpc: replanned slots=193 soc_start=50 cost_ore=8201 reason=scheduled
  mean_price_ore=183.5 mean_confidence=0.73
  terminal_soc_price_ore=106.7 capacity_wh=99800
  max_charge_w=11040 max_discharge_w=11040

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

  • No DP behaviour change — the DP still picks the same action, it's now labelled correctly.
  • Incident B (self_consumption morning import) requires PR 3 (capacity split) + PR 4 (strict mode).

🤖 Generated with Claude Code

## 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]>

@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: 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".

Comment thread go/internal/mpc/mpc.go
case batteryW > chargeThresh && baseline < -chargeThresh:
// Exporting baseline, battery charging → absorbing PV surplus.
// --- charging branches ---
case batteryW > chargeThresh && baseline < -chargeThresh && !gridExports:

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 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 👍 / 👎.

@frahlg
frahlg merged commit 6dc0fea into master Apr 19, 2026
1 check passed
frahlg added a commit that referenced this pull request Apr 19, 2026
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]>
frahlg added a commit that referenced this pull request Apr 19, 2026
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]>
@frahlg
frahlg deleted the fix/mpc-reason-label-gridw branch August 7, 2026 08:18
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.

1 participant