Skip to content

feat(savings): API endpoints + cache (PR 2/3) - #201

Closed
frahlg wants to merge 1 commit into
savings-reconstructfrom
savings-api
Closed

frahlg wants to merge 1 commit into
savings-reconstructfrom
savings-api

Conversation

@frahlg

@frahlg frahlg commented Apr 26, 2026

Copy link
Copy Markdown
Member

Stacked on #198.

Summary

PR 2 of 3 in the historical savings feature track. Wires the
pure-Go reconstruction package from #198 into HTTP.

Three handlers, all gated on Deps.State != nil AND
Deps.Prices != nil — handlers return 200 {enabled: false} when
the dependencies aren't configured, mirroring /api/prices.

Endpoint Purpose
GET /api/savings/daily?days=N KPI bar chart feed (default 30d, cap 90d)
GET /api/savings/intraday?date=YYYY-MM-DD Per-slot breakdown + flow decomposition + predicted-vs-actual overlay
GET /api/savings/summary Today / last 7 days / last 30 days totals

What's added

  • savingsCache — per-day memoization keyed by YYYY-MM-DD, same
    pattern as dailyCache. Past days computed once per process,
    today always re-runs.
  • mpc.Service.LatestParams() — RLock'd snapshot of Defaults so
    the handlers can re-cost historical slots with the same export
    terms (ExportOrePerKWh / ExportBonusOreKwh / ExportFeeOreKwh)
    the live plan applies.
  • attachPredictedOverlay — best-effort: for each slot, look up the
    planner_diagnostics snapshot active at slot start, find the
    matching Action.CostOre, attach predicted_ore and
    prediction_error_ore to the row. Snapshots are cached within one
    request — reading the same Plan JSON 96 times for one day's
    drill-down would be silly. Failures are silent (the slot ships
    without the optional fields).

Test plan

  • go test ./internal/api/... — 8 new tests pass:
    • nil-state contract (200 + enabled:false)
    • nil-prices contract (200 + enabled:false)
    • empty DB returns enabled:true with empty days
    • today with seeded history matches expected öre
    • intraday returns one row per slot with all expected fields
    • intraday rejects malformed date with 400
    • summary obeys today ≤ 7d ≤ 30d monotonicity
    • past-day cache: closing the store after the first request still
      lets the second request resolve yesterday (today recomputes and
      can 500, which is fine — it's correctly excluded from the cache)
  • go test ./... — full suite green (34 packages, 600+ tests).

What's NOT in this PR

  • Frontend — web/savings.js + KPI card + drill-down table
    land in PR 3. Without the UI nothing visibly changes for operators
    yet, but curl already gives real numbers from a populated state.db.
  • Self-consumption-only counter-factual — still deferred to PR 4.

Wires the savings package into HTTP. Three handlers, all gated on
state + prices being configured (mirrors /api/prices contract).

  /api/savings/daily?days=N  — KPI-bar feed
  /api/savings/intraday?date — drill-down with flow decomposition +
                               predicted-vs-actual overlay from
                               planner_diagnostics
  /api/savings/summary       — today / 7d / 30d totals

Per-day memo cache (savingsCache) follows the same pattern as
dailyCache: past days computed once, today always re-runs. Adds a
small mpc.Service.LatestParams() getter so the handlers can read
ExportOrePerKWh / ExportBonusOreKwh / ExportFeeOreKwh under RLock —
keeping reconstructed historical savings comparable with the live
"vs no battery" number on the MPC card.

Tests cover: nil state, nil prices, empty DB, today with seeded
history, intraday shape + bad-date 400, summary monotonicity, and
past-day cache hit (validates by closing the store after first
request and confirming the second still resolves yesterday).

Stacked on #198.

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

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

}
s.mu.RLock()
defer s.mu.RUnlock()
return s.Defaults

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 Return effective export terms in LatestParams

LatestParams() currently returns s.Defaults verbatim, but the planner actually applies export bonus/fee from s.ExportBonusOreKwh and s.ExportFeeOreKwh during replan(). That means savings endpoints re-cost history with missing export terms whenever ExportOrePerKWh == 0 and bonus/fee are configured, producing incorrect actual_ore, no_battery_ore, and savings_ore that no longer match MPC’s own cost model.

Useful? React with 👍 / 👎.

Comment on lines +315 to +320
Actions []struct {
SlotStartMs int64 `json:"slot_start_ms"`
CostOre float64 `json:"cost_ore"`
BatteryW float64 `json:"battery_w"`
GridW float64 `json:"grid_w"`
} `json:"actions"`

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 Parse diagnostic slots instead of non-existent actions

The predicted overlay unmarshals planner diagnostics into a struct tagged with json:"actions", but persisted planner_diagnostics rows are mpc.Diagnostic payloads that expose slot rows under slots. In practice this leaves pa.Actions empty, so predicted_ore and prediction_error_ore are never attached even when matching diagnostics exist, making the overlay silently non-functional.

Useful? React with 👍 / 👎.

@frahlg
frahlg deleted the branch savings-reconstruct May 26, 2026 17:04
@frahlg frahlg closed this May 26, 2026
@frahlg
frahlg deleted the savings-api branch November 11, 2026 09:22
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