Skip to content

fix(planner): keep replan inputs consistent and demand history on the tariff rule - #1451

Merged
frahlg merged 3 commits into
masterfrom
fix/planner-hardening
Sep 27, 2026
Merged

frahlg merged 3 commits into
masterfrom
fix/planner-hardening

Conversation

@frahlg

@frahlg frahlg commented Sep 27, 2026

Copy link
Copy Markdown
Member

Round 2 of the multi-agent hardening and refactor review. A skeptic confirmed each finding against the code, and a second reviewer checked this diff and ran its tests. Removals follow the owner decisions of 2026-09-26.

Changes

  • drivers: port Victron Energy GX Modbus driver #25 Moved the fuse, export ceiling, export bonus/fee/floor, VAT, demand tariff and timezone into an embedded mpc.SiteEconomics struct. Added Service.UpdateSiteEconomics, a setter that holds the lock, and the main.go hot reload now makes one call to it instead of writing fields directly. With no price section, every tariff input now resets to zero, as it does at startup. MinArbitrageSpreadOreKwh now goes through UpdatePlannerScalars. beginReplanLocked copies site economics, PVForecastSafetyK and the arbitrage spread into replanRequest, and runReplan, onlineFleetParams (which now takes a fuse argument) and demandChargesFor(site, ...) read only that copy.
    • Test: go/internal/mpc/site_economics_test.go TestReplanKeepsSiteEconomicsFromItsStart. A reload lands mid-replan through the ForecastSnapshot hook, and the test asserts that the slot limits, battery clamp and export bonus all come from the old values, then from the new values on the next replan. When I …
  • Drivers: port Sofar HYD-ES/HYD-EP to Lua v2.1 #26 SetMode(mode) and SetSafetyK(k) no longer take a ctx. They go through a new requestReplan(reason, change) that applies the change and bumps the generation under one lock, then queues the background worker that RequestReplan already uses (context.Background, bursts coalesce). Updated the callers: the API mode handler, applyPlannerPrefs (unused ctx dropped), the HA callbacks (unused ctx dropped from haCallbacks), and app_link (no goroutine or WithoutCancel needed now). At startup, main.go now sets Defaults.Mode and restores the persisted diagnostic before mpcSvc.Start, so the first scheduled solve uses the restored mode and replaces the restored plan. Before, a synchronous SetMode ran after Start. I adjusted two latest-wins tests to wait for the background solve.
    • Test: go/internal/mpc/service_requested_replan_test.go TestSetModeAndSafetyKReplanInBackground. SetMode and SetSafetyK must return while the optimizer is blocked, and the published plan must come from the optimizer (not a fallback) with mode arbitrage, k 0.5 and reason safety_k_changed. With the old …
  • Drivers: port Solis hybrid inverter #27 In bindDemandCharges, each earlier hour this month (AlreadyKW) is now multiplied by its clock-hour weight (the Ellevio night weight; 0 means 1) and reduced to one maximum per local day, the same key the planned hours use as Group.
    • Test: go/internal/mpc/demand_test.go TestEllevioAlreadyKWWeighsNightsAndKeepsOnePeakPerDay. With an 8 kWh then 7 kWh night on 8 September at weight 0.5, the test expects 9 entries (1–9 September), 4 kW on the 8th and 1 kW on the other days. The old code sent one unweighted entry per hour.
  • fix: 5 Go-side P1 bugs from Codex review #46 SavePrices now deletes, in the same transaction, the rows of the zone that each new row overlaps before upserting it. The lookback is bounded by maxSlotPadMs (1 day), the same pad the cost reads use. The cache can no longer hold an overlapping timeline, and an hourly refetch of today and tomorrow cleans up legacy overlaps inside the plan horizon. The ENTSO-E parseXML now drops a row that overlaps a finer one (keepFinestRows), so the PT15M series wins over PT60M. I also changed two existing tests that could only be built from overlapping stored rows. TestDailyCostBreakdown_FlatAverageIsHalfOpenAndTimeWeighted now checks the half-open end with a shorter query range. TestReplanRejectsTimelineItCannotRestore now writes the legacy overlap directly into cache.db, so the planner's chronology guard is still tested.
    • Test: go/internal/state/prices_test.go TestSavePricesReplacesOverlappingRows (fails without the delete: the hourly row sat alongside the old quarters) and go/internal/prices/prices_test.go TestENTSOEMixedResolutionKeepsFinestRows (a mixed PT60M/PT15M document gives 4 quarters plus the uncovered hour).

Not done

  • Driver: port GoodWe hybrid inverter (ET-Plus / EH) to Lua v2.1 #28 The current clock hour cannot be sent when the first slot starts after the hour. Fixing that means changing the Energyplan demand-hour contract (an hour that starts before the horizon, or an explicit duration) and bumping the worker pin. The worker source is not in this repo, and the finding itself calls for a paired cross-repo change, so the owner has to decide. TestBindDemandChargesSkipsUnalignedCurrentHour still pins the current behaviour.

Evidence

All run from go/ with PATH=/go/bin and GOTMPDIR=$HOME/.cache/go-tmp:

  • gofmt -l on every changed Go file: no output (PASS)
  • go build ./...: PASS
  • go vet ./internal/mpc ./internal/api ./internal/state ./internal/prices ./cmd/ftw: PASS
  • go test -count=1 ./... (the full Go suite, after fetching the drivers with scripts/sync-bundled-drivers.sh; they are not committed): PASS
  • go test -race -count=1 ./internal/mpc ./internal/prices: PASS
  • go test -race -count=5 on the new SetMode/SafetyK and site-economics tests plus the two changed latest-wins tests: PASS
  • FTW_E2E=1 go test ./test/e2e -count=1 -timeout 300s: PASS (27.8s)
  • npm test: not run, because web/ was not changed.
  • Checks that the new tests fail without their fix: TestReplanKeepsSiteEconomicsFromItsStart FAILED with the live-field reads temporarily restored, and TestSavePricesReplacesOverlappingRows FAILED with the overlap delete disabled. Both changes were reverted before the commit.

Review

The planner hardening is sound. Every new test fails without its fix. The skip of #28 is justified: fixing it needs an Energyplan contract change and a pin bump, which is cross-repo.

#25: every hot-reload writer of the economics fields now goes through UpdateSiteEconomics or UpdatePlannerScalars under s.mu. Grep finds the remaining direct writes to mpcSvc fields only at startup, before Start. beginReplanLocked copies the site economics, safetyK and minSpread, and runReplan, onlineFleetParams and demandChargesFor read only that copy. Hot reload with no price section now zeroes the tariff inputs, which matches startup.

#26: SetMode and SetSafetyK apply their change and bump the generation under one lock, then run on the existing coalescing background worker with context.Background(). A client disconnect can therefore no longer publish a fallback plan. When SetSafetyK supersedes SetMode, the service cancels the first solve (canceledByService), so no fallback is published. The window where ctrl.Mode has changed but the plan has not also existed before, because the handler sets ctrl.Mode before calling SetMode.

On the reordered startup: the mode is set and the persisted plan …

🤖 Generated with Claude Code

https://claude.ai/code/session_01MuerPFZFG88kgu8sWVHeq7

frahlg and others added 2 commits September 27, 2026 08:01
… tariff rule

- #25 Config reload swaps fuse, export ceiling, export prices, VAT, demand
  tariff and timezone in one locked UpdateSiteEconomics call. Each replan
  copies them, k and the arbitrage spread with its params, so one plan never
  mixes old and new values and the hot-reload data race is gone.
- #26 SetMode and SetSafetyK change the setting and queue a background replan
  under one lock instead of solving on the caller's context. A disconnecting
  HTTP client no longer cancels the solve into a fallback plan, and saving
  planner prefs no longer runs two solves under configWriteMu. Startup sets
  the restored mode and restores the persisted plan before the planner starts.
- #27 Demand-charge history (AlreadyKW) applies the Ellevio night weight and
  keeps one peak per local day, like the planned hours.
- #46 SavePrices removes cached rows that a new row overlaps, and the ENTSO-E
  parser keeps the finer series where PT15M and PT60M overlap, so a mixed
  resolution no longer stops every replan.
- #28 unchanged: covering the current clock hour needs an Energyplan contract
  change and pin bump.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01MuerPFZFG88kgu8sWVHeq7
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 27, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-27T06:36:30.041615Z e2ed139 PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

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

ℹ️ 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 on lines +443 to +446
if o.SlotLenMin < r.SlotLenMin && o.SlotStart.Before(end) &&
r.SlotStart.Before(o.SlotStart.Add(time.Duration(o.SlotLenMin)*time.Minute)) {
finer = true
break

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 Preserve partially uncovered coarse price slots

When an ENTSO-E document contains a coarse slot that is only partly covered by finer rows—for example, one 60-minute row plus a single overlapping 15-minute row—this marks the entire coarse row as superseded and drops the remaining 45 minutes of valid coverage. The resulting price timeline has a gap where dispatch cannot obtain a planned action; split the coarse row around finer coverage or remove it only when finer rows cover its full interval.

Useful? React with 👍 / 👎.

@frahlg
frahlg merged commit 6f32dd8 into master Sep 27, 2026
15 checks passed
@frahlg
frahlg deleted the fix/planner-hardening branch September 27, 2026 07:08
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