Skip to content

feat: plan allocates energy, EMS converts to power (opt-in) - #79

Merged
frahlg merged 4 commits into
masterfrom
plan/reactive-dispatch-on-pv-divergence
Apr 17, 2026
Merged

frahlg merged 4 commits into
masterfrom
plan/reactive-dispatch-on-pv-divergence

Conversation

@frahlg

@frahlg frahlg commented Apr 17, 2026

Copy link
Copy Markdown
Member

Summary

Implements the three-principle dispatch rework described in docs/plan-ems-contract.md:

  1. Planner allocates energy per slot (Wh), not instantaneous power.
  2. EMS converts energy to power in real time per tick from remaining Wh / remaining seconds.
  3. Grid flow is the residual — no PI loop chasing a grid target on the plan-driven path.

Opt-in via planner.use_energy_dispatch: true in config. Default off — zero behavior change for anyone not flipping the flag. Legacy PI-on-grid path untouched.

Why

Operator report (2026-04-17): plan said grid_target_w = −51, actual grid was −18, battery charging ~3.9 kW during a high-price window. Forecast PV = 700 W; reality = 4.8 kW. Instead of exporting the 4 kW surplus at peak price, the PI drove the battery to absorb it — because the plan's intent reached the EMS as "drive grid to −51 W", not as "charge ~800 W from the available PV".

Under the new path: plan emits BatteryEnergyWh = 200 for the slot. EMS computes battery_w = (200 − delivered_wh) × 3600 / remaining_s ≈ 800 W. Grid absorbs the 4 kW surplus naturally. Plan's intent respected. No PI fighting reality.

What changes

  • mpc.SlotDirectiveAt(now) (SlotDirective, bool) — non-breaking addition alongside SlotAt. Returns {SlotStart, SlotEnd, BatteryEnergyWh, SoCTargetPct, Strategy}.
  • control.State:
    • New fields SlotDirective, UseEnergyDispatch, internal currentDirective, slotDelivered, lastTickTs.
    • ComputeDispatch gains a second code path gated on UseEnergyDispatch + SlotDirective set. Falls back to legacy when the directive is unavailable.
  • config.Planner.UseEnergyDispatch (YAML: use_energy_dispatch).
  • main.go wires mpcSvc.SlotDirectiveAt into control via a thin adapter.

Tests

Four new tests in control_test.go:

  • TestEnergyDispatchConvertsWhToW — core formula: 200 Wh, 15 min → 800 W.
  • TestEnergyDispatchDoesNotAbsorbPVSurprise — the motivating scenario: 4.8 kW actual PV vs 700 W forecast, plan allocates 200 Wh charge → battery stays at ~800 W instead of ~3.9 kW absorption.
  • TestEnergyDispatchResetsOnSlotRollover — delivered accumulator resets at slot boundary.
  • TestEnergyDispatchFallsBackToLegacyWhenDirectiveUnavailable — stale plan routes through the existing plan-stale branch.

Plus five new SlotDirectiveAt tests in mpc/service_test.go (happy path, discharge, stale plan, out-of-window, nil service).

Rollout

  1. Merge this PR — nothing changes in production since the flag defaults off.
  2. Flip planner.use_energy_dispatch: true on a single site (homelab-rpi) and observe for a day or two.
  3. If clean, flip for other sites; eventually retire the legacy path and drop the flag.

Design note

Full rationale + mode taxonomy + migration notes + open questions in docs/plan-ems-contract.md (223 lines). Read that first if you want the thinking behind the change.

Not addressed here (follow-ups)

  • Divergence detector reads SoC target (currently plan-pv / plan-load only).
  • New mode taxonomy (strategy × ems_state) — the doc covers it; implementation is a separate PR.
  • /api/mpc/diagnose for ops introspection — separate PR.

🤖 Generated with Claude Code

frahlg and others added 4 commits April 17, 2026 12:01
Captures the three-principle redesign of the dispatch layer:

1. Planner allocates energy per slot (Wh), not instantaneous power (W)
2. EMS converts energy to power in real time via delivered-vs-target
   bookkeeping — battery setpoint is derived per tick
3. Grid flow is the residual; no PI loop tracking grid target from
   the plan-driven path

Motivated by the 2026-04-17 incident where the plan's grid target
caused the battery to absorb a 4.1 kW PV surprise instead of letting
it export during a high-price window.

Also proposes a cleaner two-axis mode taxonomy:
  - planner strategy: self_consumption | arbitrage | cheap_charge
  - EMS state:        follow_plan | manual | idle | auto_fallback

Peak shaving, SoC floor/ceiling, backup reserve, and multi-battery
split rules move out of the mode enum into always-on constraints or
parameters where they belong.

Not yet implemented — this is a proposal for team reaction before
code. Migration notes, wire contract, and open questions included.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Non-breaking addition alongside existing SlotAt. SlotDirective is the
per-slot energy-allocation instruction from planner → EMS under the new
dispatch contract (docs/plan-ems-contract.md):

- BatteryEnergyWh: total energy for the slot (site-signed)
- SlotStart / SlotEnd: window for EMS bookkeeping
- SoCTargetPct: plan's expected SoC at slot end — feeds divergence detector
- Strategy: planner mode echoed for logging / API

SlotAt stays for the legacy grid-target path until that's retired. The
control loop will switch to SlotDirectiveAt in a follow-up commit; this
one only adds the API surface so tests and the dispatch refactor can
start assuming it exists.

Tests cover the 200-Wh charge slot, discharge slot (negative energy),
stale-plan fallback, out-of-window, and nil-service safety.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…ispatch)

Adds the new plan→EMS contract as a second code path in ComputeDispatch,
gated on State.UseEnergyDispatch. Legacy PI-on-grid-target remains the
default and is untouched for anyone not flipping the flag.

When UseEnergyDispatch=true AND the operator is in a planner mode:

  - SlotDirective callback returns (battery_energy_wh, slot window, SoC
    target, strategy). Directive per slot, not per tick.
  - Each tick integrates live battery power × dt into slotDelivered (Wh).
  - Target total battery power = (remaining_wh × 3600) / remaining_s.
  - Distributed across online batteries by the existing proportional
    rule. Slew, SoC clamp, fuse guard — all unchanged.
  - No PI on grid. Grid flow is the residual; PV surprises naturally
    leak to grid without battery "absorbing" them.

Falls back to the legacy path when SlotDirective returns ok=false.
This preserves today's behavior for a stale plan and means the flag
can be flipped in production without a separate stale-plan handler.

Tests:
  - Wh → W conversion (200 Wh, 15 min → 800 W).
  - Xorath scenario: 4.8 kW actual PV vs 700 W forecast, plan allocates
    200 Wh charge → battery stays at ~800 W instead of ~3.9 kW
    absorption. This is the fix.
  - Slot rollover resets delivered accumulator.
  - Stale-directive fallback routes through the legacy plan-stale branch.

Not yet wired in main.go; UseEnergyDispatch defaults to false. Next
commit adds the wiring + config toggle.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
main.go now wires both plan→EMS callbacks:
  - PlanTarget      → mpcSvc.SlotAt       (legacy grid-target path)
  - SlotDirective   → mpcSvc.SlotDirectiveAt (energy-allocation path)

The control loop picks which one is actually used based on
State.UseEnergyDispatch, which is loaded from
config.Planner.UseEnergyDispatch. Default off — no behavior change for
existing deploys. Operators enabling it opt in with:

  planner:
    use_energy_dispatch: true

Once the new path is validated in production the legacy path can be
removed and this flag retired.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@frahlg
frahlg force-pushed the plan/reactive-dispatch-on-pv-divergence branch from 6193066 to 17b9c12 Compare April 17, 2026 10:02
@frahlg
frahlg merged commit acc572d into master Apr 17, 2026
1 check passed
@frahlg
frahlg deleted the plan/reactive-dispatch-on-pv-divergence branch April 17, 2026 10:04

@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: 6193066093

ℹ️ 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/control/dispatch.go Outdated
Comment on lines +375 to +376
state.GridTargetW = 0
state.PI.Reset()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep PI setpoint in sync on energy-dispatch cycles

The energy-dispatch branch zeroes GridTargetW with a direct assignment and resets only the PI integral, but it never updates PI.Setpoint. If the controller later leaves planner mode (for example via /api/mode), the legacy PI path will compute output from a stale setpoint while deadband/error checks use GridTargetW=0, which can produce incorrect corrections (including no correction when export should be absorbed). This is a behavioral regression introduced by bypassing SetGridTarget here.

Useful? React with 👍 / 👎.

frahlg added a commit that referenced this pull request Apr 17, 2026
The energy-dispatch branch in ComputeDispatch was setting GridTargetW=0
via direct assignment and calling PI.Reset() (which only zeros the
integral, not the setpoint). Result: if the operator later left a
planner mode — e.g. via POST /api/mode — the legacy PI path would
compute error against a stale PI.Setpoint while deadband/error checks
used GridTargetW=0. Under those conditions the controller could issue
no correction when one was needed (or the wrong correction).

Use SetGridTarget(0) so both fields move in lockstep. This mirrors
every other caller in the package.

Regression test pre-poisons PI.Setpoint + GridTargetW to 3000, runs one
energy-dispatch cycle, and asserts both are 0 afterward.

Caught by Codex on PR #79.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
frahlg added a commit that referenced this pull request Apr 17, 2026
…#84)

The energy-dispatch branch in ComputeDispatch was setting GridTargetW=0
via direct assignment and calling PI.Reset() (which only zeros the
integral, not the setpoint). Result: if the operator later left a
planner mode — e.g. via POST /api/mode — the legacy PI path would
compute error against a stale PI.Setpoint while deadband/error checks
used GridTargetW=0. Under those conditions the controller could issue
no correction when one was needed (or the wrong correction).

Use SetGridTarget(0) so both fields move in lockstep. This mirrors
every other caller in the package.

Regression test pre-poisons PI.Setpoint + GridTargetW to 3000, runs one
energy-dispatch cycle, and asserts both are 0 afterward.

Caught by Codex on PR #79.

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
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