Skip to content

feat(savings): pure-Go backwards reconstruction package - #198

Merged
frahlg merged 2 commits into
masterfrom
savings-reconstruct
May 26, 2026
Merged

frahlg merged 2 commits into
masterfrom
savings-reconstruct

Conversation

@frahlg

@frahlg frahlg commented Apr 26, 2026

Copy link
Copy Markdown
Member

Summary

PR 1 of 3 in the historical savings feature track. This drops in
a pure-Go package that re-prices a past day's measured power flows
with the same cost model the live MPC planner uses
(mpc.SlotGridCostOre) and compares actual cost to a no-battery
counter-factual.

No DB plumbing, no API endpoints, no frontend — those land in PR 2
and PR 3 once the math is reviewed.

What's inside

  • ComputeDay(history, prices, params, startMs, endMs) DaySavings
    — pure function; caller passes []state.HistoryPoint and
    []state.PricePoint.
  • Slot-level breakdown for the "HOW we saved" drill-down view:
    self-consumption, direct-export, PV→battery, battery→home,
    battery→grid, grid→home, grid→battery (kWh per channel).
  • Per-direction pricing inside a slot (a slot that imports for
    30 min and exports for 30 min is scored as 0.5 kWh × import + 0.5
    kWh × export, not 0 kWh net).
  • MaxGapMs (20 min) caps stale-row attribution so an outage doesn't
    silently inflate cost in either direction; coverage stays honest.

Why this design

Cost is delegated entirely to mpc.SlotGridCostOre — the same
function the live planner and ComputeBaselines already share. This
keeps "savings yesterday" comparable with "vs no battery" on the
live MPC card; if we re-implemented the import/export math here we'd
inevitably drift out of sync with the planner.

The integration convention (W × (ts − prev_ts) summed left-Riemann,
clipped to slot edges) matches state.DailyEnergy so daily Wh
totals computed two different ways agree by construction.

What's NOT in this PR

  • API endpoint — /api/savings/{daily,intraday,summary} lands
    in PR 2 along with a small MPC.LatestParams() getter, the daily
    cache, and an e2e test exercising the full SQLite → handler path.
  • Frontend — web/savings.js + KPI card + drill-down land in
    PR 3.
  • Predicted vs actual overlay — already designed (joins
    planner_diagnostics JSON per slot). Slot in PR 2.
  • Self-consumption-only counter-factual (DP replay over
    historical inputs) — deferred to PR 4 once we have evidence the
    no-battery baseline is the one operators read.

Test plan

  • go test ./internal/savings/... — 13 tests cover empty
    inputs, flat-load zero savings, perfect arbitrage, perfect
    self-consumption, mixed-direction slot, large-gap rejection,
    no-history-but-prices, day-boundary clipping, unsorted-input
    tolerance, and four decomposition cases.
  • go test ./... — full suite green (602 tests across 39
    packages); no regressions.
  • Plug into a live state.db locally (PR 2) and eyeball a
    few real days.

Re-prices a measured day with mpc.SlotGridCostOre to compute actual
cost vs no-battery counter-factual. Same cost model as live planner,
so historical savings line up with what the MPC card already shows.

Per-direction pricing inside a slot — a slot that imports for 30 min
and exports for 30 min is scored as 0.5 kWh × import + 0.5 kWh × export
revenue, not 0 kWh net. MaxGapMs (20 min) caps stale-row attribution
so an outage doesn't silently inflate either side. Flow decomposition
(self-consumption / arbitrage / direct-export / bat→home / bat→grid)
is presentation-only and doesn't influence cost numbers.

Pure functions; caller wires LoadHistory + LoadPrices in PR 2.

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

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

loadDeficit := load - self

pvToBat := minPos(pvSurplus, charged)
directExport := pvSurplus - pvToBat

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 Clamp direct-export flow at zero

directExport is derived as pvSurplus - pvToBat without a non-negative clamp, while the other channel outputs are clamped. If PVKWh is slightly negative in a slot (which can happen with meter noise or inverter standby draw), this yields a negative DirectExportKWh value, producing physically impossible breakdown data in the API/UI despite this struct representing directional kWh channels. Clamping this field like gridToBat/gridToHome/batToGrid avoids invalid negative flow rows.

Useful? React with 👍 / 👎.

@frahlg
frahlg merged commit df0d936 into master May 26, 2026
1 check passed
@frahlg
frahlg deleted the savings-reconstruct branch May 26, 2026 17:04
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