Skip to content

fix(mpc): DST/timezone audit — coerce planner time indexing to UTC - #97

Merged
frahlg merged 1 commit into
masterfrom
planner-overhaul/timezone-audit
Apr 18, 2026
Merged

frahlg merged 1 commit into
masterfrom
planner-overhaul/timezone-audit

Conversation

@frahlg

@frahlg frahlg commented Apr 18, 2026

Copy link
Copy Markdown
Member

Summary

Phase 1 of 4 in the planner overhaul roadmap.

Fixes a silent DST bug in the MPC planner's predictors. Every time-of-day / day-of-week bucket lookup (price forecast, load model) and every harmonic feature (PV twin) was indexed from whatever time.Location the caller attached to the time.Time — but FitFromHistory already indexed in UTC. Summer vs winter, Predict and Fit ended up addressing different bucket coordinate spaces, shifting the learned EMA by one bucket twice a year.

Matches the pattern in Erik's (xorath) report of the planner charging from expensive grid around 21:00 near DST boundaries.

Fix

Coerce t.UTC() at every leaf that accesses .Hour / .Weekday / .Month:

  • priceforecast/forecast.go — hourOfWeek + Predict
  • loadmodel/model.go — HourOfWeek
  • pvmodel/model.go — Features (harmonic phase)
  • mpc/service.go — UnixMilli conversions feeding predictors

Source-of-truth timestamps stay unix-milli (timezone-agnostic). UI / operator-facing formatting still uses the site's local zone — that's display, not model.

Tests

Added cross-DST regression test per package that asserts the same absolute instant gives identical model output regardless of which time.Location the time.Time carries:

  • priceforecast.TestPredictStableAcrossDST + TestHourOfWeekStableAcrossDST
  • loadmodel.TestHourOfWeekStableAcrossDST
  • pvmodel.TestFeaturesStableAcrossDST

Tests cover:

  • Spring-forward boundary (2026-03-29 01:00 UTC)
  • Fall-back boundary (2026-10-25 01:00 UTC)
  • Summer vs winter evening peaks
  • Erik's ~21:00-local scenario

Test plan

  • go test ./... — all green (including e2e, 27s)
  • go test ./internal/priceforecast/... — cross-DST tests pass
  • go test ./internal/loadmodel/... — cross-DST test passes
  • go test ./internal/pvmodel/... — cross-DST test passes
  • go test ./internal/mpc/... — no regressions
  • Erik tests deploy on affected system once merged

Roadmap context

Part of the unified-planner overhaul (plan in this session). Subsequent PRs:

  • Phase 2 — /api/mpc/diagnose endpoint for per-slot explainability
  • Phase 3 — PowerLimits (time-varying grid limits) + Loadpoint observable skeleton
  • Phase 4 — EV in DP + dispatch + charger capabilities (ONE system: battery + PV + EV)

🤖 Generated with Claude Code

Predictors for price, load, and PV digital twin all index buckets /
harmonic features off time-of-day. The indexing functions claimed "UTC
for determinism" but didn't enforce it — callers passed time.Time values
still attached to local zone, so wall-clock 19:00 Stockholm resolved to
a different bucket in summer (CEST) than winter (CET). Two silent
failure modes resulted:

1. Same absolute instant producing different Predict outputs depending
   on which time.Location the time.Time carried.
2. Fit indexing with UTC (priceforecast/forecast.go:183) but Predict
   indexing with local zone — learned EMA and prediction were addressed
   in different coordinate spaces, so the learned pattern shifted by
   one bucket twice a year.

This is consistent with Erik's report of charging-from-expensive-grid
around 21:00 near DST boundaries.

Fix: coerce to UTC at every leaf that accesses .Hour/.Weekday/.Month:
- priceforecast: hourOfWeek + Predict
- loadmodel: HourOfWeek
- pvmodel: Features (harmonic phase)
- mpc/service.go: UnixMilli conversions feeding predictors

Added cross-DST regression tests per package that assert the same
absolute instant gives identical output regardless of timezone
presentation. Documented the UTC convention in docs/mpc-planner.md.

Part of the planner overhaul roadmap (Phase 1 of 4). Subsequent PRs add
/api/mpc/diagnose (Phase 2), PowerLimits + Loadpoint skeleton
(Phase 3), and unified EV-in-DP optimization (Phase 4).

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: 3255debaaa

ℹ️ 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".

// transitions (wall-clock 19:00 maps to a different bucket in summer
// vs. winter otherwise, silently misaligning the EMA).
func HourOfWeek(t time.Time) int {
u := t.UTC()

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 Invalidate persisted load model after switching to UTC buckets

HourOfWeek now coerces every timestamp to UTC, which changes the meaning of each bucket index, but loadmodel.NewService still restores loadmodel/state as-is (go/internal/loadmodel/service.go, restore path) with no version/migration. On any deployment that previously trained in a non-UTC local timezone, the restored bucket means/samples are immediately interpreted under a different index space after upgrade, so MPC load predictions are shifted by timezone/DST until a long retraining period. Add a model-version gate and reset/migrate persisted buckets when this indexing convention changes.

Useful? React with 👍 / 👎.

Comment on lines +87 to +88
u := t.UTC()
hour := float64(u.Hour()) + float64(u.Minute())/60.0

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 Reset persisted PV coefficients for the new UTC feature phase

Features now derives harmonic phase from t.UTC(), which changes the regression basis for all learned Beta coefficients, but pvmodel.NewService still restores pvmodel/state unchanged (go/internal/pvmodel/service.go, restore path). If existing models were trained before this change in a non-UTC local timezone, those coefficients are evaluated in a different phase space after restart, yielding systematically phase-shifted PV forecasts until significant retraining occurs. This needs a state/version bump with reset or migration of persisted PV model state.

Useful? React with 👍 / 👎.

@frahlg
frahlg merged commit 793ed29 into master Apr 18, 2026
1 check passed
frahlg added a commit that referenced this pull request Apr 18, 2026
Bundles 8 issues Codex flagged across PRs #97-#101. Ordered by what
blocks Erik's hardware testing most.

## P1 — charger kept running after slot ended (#101)

When the current MPC slot had no EV allocation, the dispatch loop
`continue`d without sending any command. Easee would keep drawing at
its previous setpoint — including across a "stop charging" slot
transition. Now we default cmdW=0 and always send the explicit
ev_set_current command so the charger actively stands down.

## P1 — plugin_soc_pct never reached the runtime (#101)

Added to loadpoint.Config in Phase 4.1 but never copied from YAML.
Config knob was a no-op. Plumbed through config.Loadpoint and
centralised the YAML→runtime mapping in a new buildLoadpointConfigs
helper so boot-time init and hot-reload can't drift.

## P1 — TargetSlotIdx assumed 15-min slots (#100)

Hard-coded `int(delta / (15 * time.Minute))` in main's LoadpointProbe,
but Nordic day-ahead prices come as 60-min slots. A 2-hour deadline
on hourly data mapped to slot 8, not slot 2 — DP thought it had 4×
the time it actually did. LoadpointProbe now takes slotLenMin from
the actual plan and mpc.Service passes it in from slots[0].LenMin.

## P1 — race on lastLoadpointID (#100)

SlotDirectiveAt read s.last under RLock then s.lastLoadpointID
outside. A concurrent replan could swap one without the other and
produce a directive keyed under the wrong driver. Snapshot both
under the same lock.

## P1 — infeasible DP states picked full-discharge fallback (#99)

When mode + PowerLimits eliminated every action at a (slot, soc, ev)
state, bestV stayed +Inf but bestPolicy defaulted to 0 — which
encodes (ba=0, ea=0) = "full battery discharge, EV off", the WORST
possible fallback. Now overrides bestPolicy to the closest-to-idle
action index ((A-1)/2 * EA), so forward-sim produces a sane plan
even in operator-induced infeasibility.

## P1 — persisted PV/load models misaligned after UTC switch (#97)

pvmodel's β coefficients were fitted against local-zone hour-of-day
harmonic features; loadmodel's buckets were indexed on local
weekday+hour. After the Phase 1 UTC coercion in Features /
HourOfWeek, restoring the old state silently misaligned both models
against the new coordinate system. Bumped state keys (`pvmodel/state`
→ `pvmodel/state_utc`, `loadmodel/state` → `loadmodel/state_utc`) so
old state is ignored on upgrade — model retrains from telemetry over
a day or so.

## P2 — config hot-reload didn't touch loadpoints (#99)

configreload callback skipped newCfg.Loadpoints entirely. Added a
Load() call on the manager inside the callback — the manager
preserves observed state across reloads, so adding / tuning
loadpoints live no longer needs a process restart.

## P2 — session anchor lost on config reload (#101)

loadpoint.Manager.Load preserved pluggedIn and delivered_wh_session
but not sessionPluginSoCPct. A hot-reload mid-charge would reset
the SoC inference baseline back to PluginSoCPct, making the
estimate jump backward even though the car kept getting energy.
Carry the anchor too.

## Tests

- Added `TestOptimizeInfeasibleStatePicksNearIdle` covering the DP
  fallback.
- All existing tests still pass incl. e2e (27s).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@frahlg
frahlg deleted the planner-overhaul/timezone-audit 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