Repository navigation
fix(arbitrage): cover-load discharge slots chase live grid=0 - #378
Conversation
planner_arbitrage discharge slots come in two flavors: peak-export (PlannedGridW < 0, picked for export price) and cover-load (PlannedGridW ≈ 0 or import, picked to offset expensive import). The energy-allocation dispatch path treated both identically — locking the battery at remainingWh × 3600 / remainingS regardless of live conditions. Operator-report 2026-05-28: plan baseload 1.7 kW, real load 0.9 kW, battery sat at -1.7 kW exporting 800 W at spot, then bought back later at consumer price. Symmetric overshoot when load jumped to 3.2 kW — battery stayed at -1.7 kW and 0.5 kW imported. Add a cover-load carve-out next to the existing passive_arbitrage non-charge carve-out: when state.Mode == planner_arbitrage AND HasPlannedGridW AND BatteryEnergyWh < -50 Wh AND PlannedGridW > -100 W, skip useEnergyPath and fall through to reactive PI on grid=0. Peak-export slots (PlannedGridW < -100 W) stay on the energy path — extra export there is bonus revenue, which is the design the existing comment defended. Charge slots stay on the energy path. Tests cover the operator scenario both directions (undershoot/overshoot), the peak-export regression, the live-PV-surplus case, the HasPlannedGridW=false backcompat fallback, and the existing passive cover-load coverage. Docs: plan-ems-contract.md gets a new "Exception: planner_arbitrage cover-load discharge" section mirroring the planner_self exception. 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: a3a7e024d1
ℹ️ 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".
| coverLoadDischargeSlot := state.Mode == ModePlannerArbitrage && | ||
| dir.HasPlannedGridW && | ||
| dir.BatteryEnergyWh < -idleWhGate && | ||
| dir.PlannedGridW > -coverLoadExportToleranceW |
There was a problem hiding this comment.
Force cover-load slots to bypass legacy PlanTarget
In production main.go wires both SlotDirective and the legacy PlanTarget, and mpc.actionToSlot returns ("self_consumption", a.GridW, true) for every planner_arbitrage discharge. This carve-out only disables the energy path, so the code immediately falls into the !useEnergyPath block and state.SetGridTarget(gridW) uses the planned import/export value rather than the intended grid=0. For cover-load slots with PlannedGridW positive (explicitly included by this predicate), the reactive branch will chase that planned import instead of covering live load; with the 1.7 kW planned-import case it can back discharge off toward +1.7 kW import, and the sign floor then leaves the battery idle rather than covering the house. The new tests miss this because they do not wire PlanTarget.
Useful? React with 👍 / 👎.
…h paths (#379) Adds a path-agnostic per-slot Wh accumulator that runs on EVERY dispatch tick — including the reactive paths the existing slotDelivered bookkeeping doesn't track: * planner_self (idle and participating slots) * planner_passive_arbitrage idle / non-charge slots * the planner_arbitrage cover-load carve-out from PR #378 (PlannedGridW > -100 W AND BatteryEnergyWh < -50 Wh) * manual modes, plain self_consumption At slot rollover the actual fleet delivery is scored against the plan's BatteryEnergyWh; ratios > 1.5 log an over-delivery and bump SlotDeliveryStats.OverDeliveryCount; ratios < 0.5 log under-delivery and bump UnderDeliveryCount. Idle slots (|planned| <= 50 Wh) are skipped — ratio against ~0 is meaningless. Counters surface on /api/status under "slot_delivery_stats". Pure observability: no dispatch decision reads the counters and no hard Wh cap is applied to reactive paths. The point is to measure first so we have data before deciding whether enforcement is needed. Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Lower the reactive replan thresholds and add a third trigger so the planner reacts to twin drift well before the integral-of-error path crosses its window. Why: - PR #378's cover-load reactive carve-out pulled more decisions out of the plan and into the dispatch layer. The plan goes stale during those windows even though the immediate gap is covered. The fix is to replan more readily, not to hold the plan longer. - The PV / load twins already self-correct every cycle via RLS, but the planner only consumed their output every 15 min. Twin RMSE is a cleaner staleness signal than the energy integral — the integral fades briefly to zero when the forecast and reality both swing, while the twin's prediction has by then moved permanently. What changes: - LoadDivergenceWh default 400 → 200 - PVDivergenceWh default 500 → 250 - Reactive integral half-life 15 min → 8 min (480 s) - MinReplanGap default 60 s → 30 s - New TwinDriftPVW (250 W RMSE), TwinDriftLoadW (200 W RMSE), TwinDriftHorizonSlots (16 ≈ 4 h @15-min) — replan when the twin's next-N-slot prediction has RMSE'd past the threshold from the snapshot the active plan was built on. Subject to the same MinReplanGap cooldown. No-op when predictors aren't wired. - replan() now snapshots the planned PV + load predictions per slot so the twin-drift detector has a stable comparison baseline. Why replanning more freely is safe: a full DP solve is ~100 ms on a Pi 4 (51 SoC × 21 action × 193 slots, sub-1 % CPU). Being stingy was the wrong default — the cost is in the noise. What does NOT change: DP grid resolution, terminal-credit math, plan- stability protections (SlotStart anchoring, MaxPlanAge gate, cooldown between reactive replans). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Lower the reactive replan thresholds and add a third trigger so the planner reacts to twin drift well before the integral-of-error path crosses its window. Why: - PR #378's cover-load reactive carve-out pulled more decisions out of the plan and into the dispatch layer. The plan goes stale during those windows even though the immediate gap is covered. The fix is to replan more readily, not to hold the plan longer. - The PV / load twins already self-correct every cycle via RLS, but the planner only consumed their output every 15 min. Twin RMSE is a cleaner staleness signal than the energy integral — the integral fades briefly to zero when the forecast and reality both swing, while the twin's prediction has by then moved permanently. What changes: - LoadDivergenceWh default 400 → 200 - PVDivergenceWh default 500 → 250 - Reactive integral half-life 15 min → 8 min (480 s) - MinReplanGap default 60 s → 30 s - New TwinDriftPVW (250 W RMSE), TwinDriftLoadW (200 W RMSE), TwinDriftHorizonSlots (16 ≈ 4 h @15-min) — replan when the twin's next-N-slot prediction has RMSE'd past the threshold from the snapshot the active plan was built on. Subject to the same MinReplanGap cooldown. No-op when predictors aren't wired. - replan() now snapshots the planned PV + load predictions per slot so the twin-drift detector has a stable comparison baseline. Why replanning more freely is safe: a full DP solve is ~100 ms on a Pi 4 (51 SoC × 21 action × 193 slots, sub-1 % CPU). Being stingy was the wrong default — the cost is in the noise. What does NOT change: DP grid resolution, terminal-credit math, plan- stability protections (SlotStart anchoring, MaxPlanAge gate, cooldown between reactive replans). Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Four findings from Codex on the dispatch / loadmodel changes shipped in v0.107.0. Two are P1 (regressions that defeat their own PR's purpose); two are P2 (defensive predicate + observability gap). P1 (PR #377): SeedHeatingCoef preserves learned value across restarts. main.go called SetHeatingCoef unconditionally at startup, clobbering the persisted online-fit value with the config seed. Every binary update wiped the adaptive learning. New SeedHeatingCoef is a no-op when the model already has samples; operator config is the cold-start prior, observation drives the value once learning has begun. SetHeatingCoef remains for explicit operator override (eg. API endpoint, manual reset). P1 (PR #378): Cover-load carve-out forces grid_target=0. The carve-out only set useEnergyPath=false; production wires PlanTarget alongside SlotDirective, so the !useEnergyPath branch called PlanTarget and then SetGridTarget(plannedImportW). A cover-load slot with 1.7 kW planned import then made PI try to import 1.7 kW — the opposite of the carve-out's purpose. Fix routes both carve-out predicates to SetGridTarget(0) and skips the legacy PlanTarget block. P2 (PR #375): passiveArbitrageIdleSlot predicate tightened. Was `dir.BatteryEnergyWh <= idleWhGate` which matched any negative-energy slot (planned discharge). Tightened to |BatteryEnergyWh| ≤ idleWhGate. The planned-discharge case folds into coverLoadDischargeSlot, which is now extended to planner_passive_arbitrage too (was arbitrage-only). The live-export gate fires on either predicate. P2 (PR #379): SlotDeliveryStats.SignMismatchCount. Planned -425 Wh vs actual +425 Wh would have scored |ratio|=1.0=on-target — the largest possible miss, invisible. New counter fires when planned and actual have opposite signs for non-idle slots; the magnitude over/under counters then only fire on same-sign cases, keeping their semantics clean. Tests: - TestSeedHeatingCoefDoesNotOverwriteLearnedValue - TestSeedHeatingCoefAppliesOnColdStart - TestPlannerArbitrageCoverLoadChasesGridZeroNotPlannedImport - TestCoverLoadDischargeDoesNotAbsorbLiveSurplus (both modes) - TestSlotMetricsDetectsSignMismatch Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Summary
planner_arbitragedischarge slots now distinguish peak-export intent (PlannedGridW < 0— extra export is bonus revenue, keep energy path) from cover-load intent (PlannedGridW ≈ 0or import — DP picked discharge to offset expensive import, not to export). The latter now routes through reactive PI-on-grid=0, identical to theplanner_selfparticipant path and the existingplanner_passive_arbitragenon-charge carve-out.targetTotalW = remainingWh × 3600 / remainingSis otherwise unchanged for charge slots and peak-export slots.Motivating incident
Operator-report 2026-05-28:
Both directions are now reactive — slot Wh budget guides where the battery is generally headed, the live meter decides instantaneous power.
Detection
In
go/internal/control/dispatch.go, next to the existingpassiveArbitrageIdleSlotcarve-out:What does NOT change
PlannedGridW < -100 W) — energy path holds the planned rate; covered byTestPlannerArbitragePeakExportSlotStaysOnEnergyPath.BatteryEnergyWh > 0) — deliberate grid-charge intent honoured.HasPlannedGridW = false(older test fixtures, legacy code paths) — falls through to energy path; covered byTestPlannerArbitrageDischargeSlotWithoutPlannedGridWUsesEnergyPath.planner_passive_arbitragecover-load — already handled by the existingBatteryEnergyWh <= idleWhGatenon-charge carve-out; regression-locked byTestPlannerPassiveArbitrageCoverLoadBacksOffOnLoadUndershoot.Wh budget on the reactive path
Not enforced as a hard cap (matches
planner_self). A 15-min slot ×MaxDischargeWcaps over-delivery at ~1.25 kWh; the reactive replan trigger (load-error integral > 400 Wh) picks up the actual SoC for re-allocation. If field reports show SoC-utarmning on envis last-överskridelse, can promote to a hard cap by reusing the existingslotDeliveredbookkeeping.Test plan
TestPlannerArbitrageCoverLoadBacksOffOnLoadUndershoot— undershoot reproduces operator scenario, target backs off from -1700 W.TestPlannerArbitrageCoverLoadRampsOnLoadOvershoot— overshoot ramps battery beyond planned rate.TestPlannerArbitragePeakExportSlotStaysOnEnergyPath— peak-export regression.TestPlannerArbitrageCoverLoadDoesNotDischargeIntoLiveExport— live PV surplus does not get blindly exported via battery.TestPlannerArbitrageDischargeSlotWithoutPlannedGridWUsesEnergyPath— backcompat forHasPlannedGridW=false.TestPlannerPassiveArbitrageCoverLoadBacksOffOnLoadUndershoot— passive cover-load regression.make verifyclean (vet + full test + build).make verify-allclean (cross-compile for arm64 / amd64 / windows).🤖 Generated with Claude Code