Skip to content

feat(history): the figure for Skatteverket's energy tax refund after battery storage - #1950

Merged
frahlg merged 4 commits into
masterfrom
feat/battery-return-tax
Nov 2, 2026
Merged

frahlg merged 4 commits into
masterfrom
feat/battery-return-tax

Conversation

@frahlg

@frahlg frahlg commented Nov 2, 2026 •

Copy link
Copy Markdown
Member

Why

A Swedish household can get back the energy tax on grid electricity it stored in a battery and later fed back to the same grid (Skatteverket; 11 kap. 13 § LSE, in force from 2018, prop. 2017/18:294). The owner applies once per calendar year, within three years after it ends. Losses are not refunded. Skatteverket prescribes no way to measure the energy, the applicant must be able to show the figure, and a wrong figure can bring a tax surcharge. FTW's energy ledger holds what is needed.

What

  • History has a closed section, "Energy tax refund for battery storage". Pick a year (this one so far, or the three before it) to see the kWh, rounded down, by month with complete hours. The CSV gives every hour behind the figure.
  • GET /api/energy/battery-return?year= and /api/energy/battery-return.csv, Read tier, listed in the agent catalogue.
  • New package go/internal/batteryreturn; queries stay in state (LoadEnergyHistoryContext, month by month).

How the figure is counted

Where the readings cannot tell where energy went, it counts low:

  • Per Swedish clock hour, the battery took from the grid at least charge − solar − car discharge (at most the import), and sent to the grid at least export − solar − car discharge (at most the discharge).
  • Nothing says how much the battery holds, so no share of its content can be known. What the house takes from the battery counts as grid energy first, and what goes to the grid counts as other energy first. Grid energy counts after the least round-trip efficiency its own run of battery readings allows, (discharge − battery size) / charge per run between gaps, and its loss stays in the battery as other energy, so losses never count and the account never falls below what the battery holds. Each hour plays in the order that credits least: other energy in, the export out (other first), grid energy in, the house's share (grid first), then a full battery sheds grid energy first. A battery asset that takes over from another starts a new account.
  • Only measured and integrated ledger rows count. Gap markers and counter deltas spread over an outage do not. Every grid, battery and solar meter seen in the year must read every hour, and the next hour too, since the ledger marks an outage only when the reading returns. A charger that ever gave energy back must too.
  • An hour without full readings attributes nothing: its discharge counts as used at home, its charge as other energy. Without the battery's own readings, the battery counts as full of other energy afterwards, as at the start of the year.
  • Solar counts as 0 in hours wholly past civil dusk, when the site's position lies in Sweden, so a sleeping inverter does not break every night.
  • A device that changes identity (the home box's Sungrow went from a MAC-based to a serial-based device id in September) leaves two assets of each kind in the ledger. Assets of one kind that never read at the same time count as one meter; each answers until the next one's first reading, so the hours between stay incomplete.
  • It needs exactly one battery with its size set (sized at least what it gained in one day). Two batteries in one account could let one battery's exports carry the other's grid energy, so they get a message and no figure (feat(history): one account per battery for the battery-storage tax figure #1953 gives each battery its own).
  • It assumes FTW reads every solar inverter, battery and car charger on the site; the UI says so.

Evidence

  • go test ./internal/batteryreturn ./internal/api and npm test pass; make verify was clean on the final tree before the rebase onto f3b48e48 (narrow tests re-run after it).
  • Tests cover arbitrage, stored solar, grid energy used at home, partial and missing hours, recovered spreads in a real store, silent and late meters, daily rollups, V2X, one battery, the size floor, dark hours, Swedish year boundaries and the API.
  • Two independent reviews. The first found five ways the figure could overstate; all are fixed and kept as tests. The second re-ran those scenarios, fuzzed 120 generated sites with outages, silent meters and sleeping inverters against a minute-level truth (no case above the truth, worst ratio 0.992), and found two more overstatements: two batteries sharing a mix, and swapped coordinates making summer evenings dark. Both are fixed. A third review, made while building feat(history): one account per battery for the battery-storage tax figure #1953, found that the proportional mix itself overstated: with the battery's content unknown, grid energy the house had already used stayed in the mix and was credited to later exports (5 kWh grid in at night, 5 kWh to the house in the morning, 5 kWh solar at midday, 5 kWh to the grid in the evening returned about 0.6 kWh a day against a truth of 0), and an efficiency taken across a gap could run high. The method is now the strict order above with one efficiency per run of readings; that case is a test. A fourth review (on feat(history): one account per battery for the battery-storage tax figure #1953) then found three more: discharge played before charge within an hour (4 kWh against a least figure of 0), the charge loss dropped from the account (1,230.8 Wh against 0), and a new battery asset keeping the old account. Its repair, validated on about 24,000 random sites, is the hour order and loss handling above; the three cases are tests and fail on the previous code. The second review's fuzz harness re-run on the final code found no report above the truth in 300 runs, including configured sizes at half and a quarter of the real one. A site that buys at night and sells in the evening gets roughly (2η − 1)/η of the true figure, about 89 % at 90 % round trip.
  • Run against the home box's real ledger through its read API (no writes): 2026 so far gives 0 kWh (the earlier proportional mix gave 36.4 kWh): the house uses the battery's grid energy itself, and its exports are covered by solar and the charge losses, with 2,260 of 7,330 hours complete (FTW arrived on 20 July; September 685/720 and October 727/745 complete), battery size assumed 9.6 kWh. Before the identity fix the same ledger gave no figure.
  • Reviewed in a browser against 30 days of seeded ledger data: desktop, 375 px wide (no sideways scroll), dark and light.

For the owner

  • The changeset is minor: a visible new capability.
  • Method: the strict order is the only rule here that cannot overstate without knowing how much the battery holds. It gives the home box 0 for 2026. A proportional split would be fairer but needs the battery's real content, from its state of charge and size; that is a possible follow-up. Skatteverket prescribes no method.
  • Size history: the figure uses the battery size set today. If a battery was replaced by a smaller one during the year, the months before the swap can count too high; the ledger cannot tell a physical swap from an identity change. Recording each battery's size with its hardware identity would close this.
  • The ledger keeps hourly rows for two years and daily after, while the deadline is three years after the year. The UI tells owners to download the CSV soon after the year ends.

Not in this PR

  • The planner does not yet value the refund.
  • Sites with more than one battery need one mix per battery, which needs a size per battery.
  • Longer hourly retention.
  • The figure in the web app and the iOS app.

🤖 Generated with Claude Code

…battery storage

A Swedish household gets back the energy tax on grid electricity it stored
in a battery and later fed back to the same grid (11 kap. 13 § LSE). History
now works out that figure for one calendar year, month by month, with the
hourly basis as CSV. The count stays low wherever the readings cannot tell
where energy went.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 2, 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-11-02T09:26:17.617722Z c66a28e 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: c66a28e008

ℹ️ 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 +355 to +357
// out = efficiency × in − what the battery gained, and it gained at
// most a full battery.
r.Efficiency = clamp((out-r.CapacityWh)/in, 1)

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 Account for unobserved charging in the efficiency estimate

When the battery charges during telemetry outages and discharges after readings resume, out includes those discharges but in excludes their charging. Subtracting just one battery capacity across all readable segments can therefore inflate Efficiency to 100%, leaving fictitious grid energy in the mix after the actual grid charge has been consumed. For example, a 10 kWh battery with two unobserved solar refills followed by measured household discharges, then separate 10 kWh grid and solar charges each yielding 9 kWh, produces 20 kWh measured input and 38 kWh output. If the grid charge serves the house and only the final solar charge is exported, this calculation nevertheless reports about 818 Wh returned from the grid. Account for unknown initial energy in each uninterrupted segment when deriving efficiency.

AGENTS.md reference: AGENTS.md:L26-L26

Useful? React with 👍 / 👎.

The home box's Sungrow moved from a MAC-based to a serial-based device id
in September, so the ledger holds two grid meters, batteries and solar
assets. The report took that for two batteries and for meters that fell
silent, and gave no figure for the year. Assets of one kind that never
read at the same time now form one meter; the hours between them are
still owed and stay incomplete.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…than the readings allow

The proportional mix overstated. Nothing says how much the battery holds,
and with the content taken as a full battery, grid energy the house had
already used stayed in the mix and was credited to the evening's export:
5 kWh from the grid at night, 5 kWh to the house in the morning, 5 kWh of
solar at midday and 5 kWh to the grid in the evening returned about 0.6 kWh
a day where the truth is 0.

What the house takes from the battery now counts as grid energy first, and
what goes to the grid as other energy first. Grid energy enters after the
least efficiency its own run of battery readings allows, so a short run or
one cut by a silent battery cannot borrow an efficiency; other energy
enters whole. A full battery sheds grid energy first.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
frahlg added a commit that referenced this pull request Nov 2, 2026
A Swedish household gets back the energy tax on grid electricity it
stored in a battery and later sent back to the grid. The Core DP now
keeps the grid share of what the battery holds as a second state (0,
1/2, 1) and, in active arbitrage, credits each kWh of stored grid energy
it sends to the grid, counted as History counts it (#1950): solar first,
a proportional mix, no refund for losses. Without a refund it runs the
old arithmetic.

The credit is the least tax any Swedish household pays that year (a
dated table less the 9.6 öre northern deduction), never more than the
grid tariff, for SE1-SE4 priced in SEK with one sized battery. The start
share comes from History's last counted hour, in the background; charge
since then counts as other energy. The DP leaves the refund out while a
car is plugged in and across New Year. Every published plan reports the
refund it earns, and the Core DP shadow nets it out of its corrected
comparison. Energyplan does not plan for it yet.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
frahlg added a commit that referenced this pull request Nov 2, 2026
History (#1950, 3950f98) now counts what the house takes from the
battery as grid energy first and what goes to the grid as other energy
first; grid energy enters after the loss, other energy whole, and a
full battery sheds grid energy first. The proportional share let the
plan count more than the owner can claim.

The Core DP keeps its grid-share state but moves it by that order on
every action, from flows built once per slot and action. The planner
starts from History's grid and other energy rather than a share: what
the battery gave out since the count took grid energy, what it took in
is other energy. With no refund the DP runs the old arithmetic; with it
a 48 h plan takes about five times as long on an M5.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…p the charge loss

A third review found the strict account could still overstate:

- It played discharge before charge, so the house never took grid energy
  that came in earlier in the same hour (4 kWh where the least figure the
  flows allow is 0).
- It dropped the charge loss, so the account fell below what the battery
  held; the house then took other energy the real battery still had, and
  the export reached grid energy early (1230.8 Wh against 0).
- A new battery asset that took over within an hour kept the old account.

Each hour now plays: other energy in, the export out (other energy first),
grid energy in after the least efficiency with its loss kept as other
energy, the house's share (grid energy first), then a full battery sheds
grid energy first. A battery asset that takes over starts a new account.
The review's cases are tests and fail on the previous code.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
frahlg added a commit that referenced this pull request Nov 2, 2026
A Swedish household gets back the energy tax on grid electricity it
stored in a battery and later sent back to the grid. The Core DP now
keeps the grid share of what the battery holds as a second state (0,
1/2, 1) and, in active arbitrage, credits each kWh of stored grid energy
it sends to the grid, counted as History counts it (#1950): solar first,
a proportional mix, no refund for losses. Without a refund it runs the
old arithmetic.

The credit is the least tax any Swedish household pays that year (a
dated table less the 9.6 öre northern deduction), never more than the
grid tariff, for SE1-SE4 priced in SEK with one sized battery. The start
share comes from History's last counted hour, in the background; charge
since then counts as other energy. The DP leaves the refund out while a
car is plugged in and across New Year. Every published plan reports the
refund it earns, and the Core DP shadow nets it out of its corrected
comparison. Energyplan does not plan for it yet.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
frahlg added a commit that referenced this pull request Nov 2, 2026
History (#1950, 3950f98) now counts what the house takes from the
battery as grid energy first and what goes to the grid as other energy
first; grid energy enters after the loss, other energy whole, and a
full battery sheds grid energy first. The proportional share let the
plan count more than the owner can claim.

The Core DP keeps its grid-share state but moves it by that order on
every action, from flows built once per slot and action. The planner
starts from History's grid and other energy rather than a share: what
the battery gave out since the count took grid energy, what it took in
is other energy. With no refund the DP runs the old arithmetic; with it
a 48 h plan takes about five times as long on an M5.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
frahlg added a commit that referenced this pull request Nov 2, 2026
… energy

History (#1950, a17faf1) now plays each hour as: other energy in, the
export out (other energy first), grid energy in after the least
efficiency with its loss kept as other energy, the house (grid energy
first), then a full battery sheds grid energy first.

A planner slot moves the battery one way, so only the charge loss
changes the plan's count: it now enters as other energy, and the cap
at what the battery holds sheds the same amount of grid energy. Buying
at night and selling at the peak from an empty battery returns
(2η − 1)/η of the export, as History does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@frahlg
frahlg merged commit 875240e into master Nov 2, 2026
22 checks passed
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