Florian Schmidt 5a6f34a467
ci / build-test (push) Successful in 2m34s
Analysis: bound the freshness query, let window sums skip chunks, share the Overview's catalog
Three things the 1,000-meter x 10-year measurement found, each proved by
EXPLAIN or a statement count before and after. No tally moves.

Freshness had two jobs in one unbounded query. The mark -- when a meter
last delivered -- is now stored on meter_rollup_state and maintained by
every recompute, with a one-pass backfill in the migration, so an
import-only meter keeps its years-old last activity without reading a
single raw row. The rhythm that decides stale versus live is sampled
inside a 90-day window and only for meters that actually have a live
source; a source silent for longer than that is re-read unbounded, so it
is still called stale by its own rhythm rather than by a default. The
portfolio query went from 13.8 ms planning plus 36.1 ms execution across
all 123 reading chunks to 0.58 plus 0.44 ms across four.

Window sums took their time bounds only from the unnest join, so the
planner could not exclude chunks: a 1,960-window case scanned 1.39 M rows
in parallel and spilled a 45 MB sort. Repeating the overall min and max as
constants makes it five chunks and nested-loop index scans, 121.5 ms to
8.7 ms.

The Overview read the catalog three times, once for the quantities and
once for each of its two bills. One context and one catalog snapshot now
feed all three: 31 statements per load to 23.

The final timings on an idle machine are in docs/ANALYSIS_REPORT.md: the
brief's target request (100 meters, ten years, monthly) is 286 ms against
two seconds, and a startup rebuild of 1,000 meters is 279 s.
2026-09-20 11:16:48 +02:00
2026-09-17 21:09:27 +02:00

MeterVault

A self-hosted, local-first energy & utility metering platform. MeterVault pulls meter data from Home Assistant, Tasmota and raw MQTT on a schedule, stores every reading timestamped and immutable, normalizes it into consumption, and turns it into cost dashboards. Energy types (electricity, water, heating oil, gas, district heat, …) and meters are user-defined — nothing is hardcoded.

Successor to a hand-maintained Energiebilanz spreadsheet. See docs/SDD.md for the full design.

Features

  • Automatic ingestion from MQTT/Tasmota (persistent subscriptions) and Home Assistant (REST poll or push), plus manual entry, a REST push API, and CSV import.
  • Immutable raw readings on a TimescaleDB hypertable; a normalized, append-only consumption layer on top — reproducible, auditable.
  • Seven measurement modes (cumulative/generation registers, burner runtime, tank/consumable, direct delta, instant rate, virtual). Handles meter swaps, counter resets and tank dip-sticks with calibration.
  • Virtual meters with a validated formula over other meters: sum, difference or free formula, e.g. Solar 1 + Solar 2, or self-consumption as Haus Netz. They are analysed exactly like physical meters: history, comparisons, source contributions, and costs where a cost rule applies. They are computed from their sources on every read, so they never go stale. A missing source month reads "no data", never a silent zero.
  • Tariff engine with time-ranged price history (unit/base/feed-in), scoped global / per type / per meter. The bill counts each energy type's grid import (or its household use), not every meter that happens to exist. Standing charges are counted once per scope. Cost categories are decoupled from energy types. Meterless manual costs are supported. The currency is configurable.
  • Rollups by local day and month, written together with the consumption, so dashboards never scan raw readings. The Settings page shows how far each meter's analysis data is built.
  • One period everywhere: every page shares a period toolbar (month to date, last month, year to date, previous year, last 12/24 months, all history, custom dates), a bucket size (day, week, month or year) and a comparison (previous period, previous year, or any calendar year). The selection lives in the URL, so reload, Back and shared links keep it.
  • Pages:
    • Overview of the selected period: cost with its composition, one card per energy type, history chart, "what changed", and attention items with a direct fix.
    • Analysis page to explore the portfolio, an energy type, a cost category, one meter or up to six meters side by side, by quantity or cost.
    • Energy type pages with Overview, History, a Sankey flow of the meter chain, and a meter list. A downstream meter is a subsection of an upstream one (main → car, pool, garden, …), and the unmetered remainder is shown as "Other".
    • A meter hub with tabs for Analysis, Readings, Normalized data, Events, Tariffs and Sources (Calculation for virtual meters). The record tabs are paged over the full history.
    • Solar (generation, self-consumption, feed-in, autarky, savings, with setup help for missing meter roles) and Tanks & consumables (last dipstick, estimate now, deliveries, burner runtime, forecast).
  • Honest numbers: a true zero, missing data, data that is only monthly, and a missing price are shown differently everywhere, in cards, charts, tables and the CSV export of any view.
  • Admin UI: full create/edit/delete for energy types, meters (with a calculation editor and live preview for virtual meters, friendly meter roles, and a recompute when a change needs one), ingest sources, tariffs (unit check; "Add tariff" links from a missing price open the editor prefilled), cost categories, and MQTT/Home-Assistant connectors. Includes a "Test connection" for Home Assistant and an effective-settings view.
  • English and German UI, light and dark theme, usable down to phone width.
  • REST API + OpenAPI/Swagger, API-key auth, reverse-proxy trust (Authelia/Traefik).
  • JSON config export/import for portability; Docker Compose + multi-arch image.

Upgrading to 0.4.0

0.4.0 reworks the dashboards and how analysis and costs are computed. Read docs/RELEASE_NOTES.md first: some figures change on purpose. Back up the database (pg_dump), then start the new image once and let it finish:

  • The first start rebuilds every meter's analysis data (normalization revision 3): consumption, the new day/month rollups and coverage. This happens before the web server listens, so the app is unreachable while it runs and Compose may report the container unhealthy. Let it finish rather than killing it. The time grows with the number of raw readings: about 0.1 s per monthly meter, ~0.6 s per meter with ten years of daily readings, ~1.4 s per meter with a year of hourly readings. A 1,000-meter test dataset (1.3 M readings) took about six minutes. Progress is logged, and a meter that fails is retried at the next start.
  • Virtual meters without a formula get the sum their links imply stored as an explicit formula. The log names the meters converted and those that still need configuration.
  • The bill changes: the grid meter is billed instead of every meter of a type, feed-in is credited only on a grid-export meter, a missing tariff is "not priced" instead of 0, and standing charges count once per scope. The seeded demo now matches the spreadsheet's yearly costs.
  • The REST API only adds fields: see the release notes for costStatus, costAvailability, costRule, notCosted, missingPrices, status and latestMonth.
  • Rolling back to 0.3.0: the old version ignores the new tables and never read the dropped continuous aggregates. Consumption stays as 0.4.0 booked it until each meter next ingests a reading. Stored virtual-meter formulas remain; 0.3.0 ignores them and sums links again.

Upgrading to 0.3.0

This release changes where consumption lands. Back the database up first (pg_dump), then start the new image once and let it finish:

  • The first start re-derives all stored consumption before the web server listens. The app is unreachable while it runs (Compose may report the container unhealthy after ~105 s) — let it finish rather than killing it. Progress and any meter it could not rebuild are logged.
  • Figures change once. Consumption between two readings is now attributed to the months it accrued in instead of landing entirely on the later reading, so historical months and their costs can shift; rows that had to be divided are marked estimated.
  • Imported monthly tables are marked as such in place before anything is recomputed, so they keep reconciling. If that step fails nothing is rebuilt and the whole upgrade simply runs again next start.
  • Check the log once for had its dates auto-detected: a CSV imported through the wizard with the date format left on auto-detect is treated as a monthly table when all its rows sit on the 1st. If such a sheet really was day-dated, revert that batch on /import and import it again with the day format.
  • Rolling back to 0.2.0 leaves the re-attributed consumption in place; it is re-derived under the old rules only as each meter next ingests a reading.

Quick start (Docker)

docker compose -f deploy/docker-compose.yml up -d
# open http://localhost:8760  → Import → "Load reference data" for a populated demo
# ...or start pre-populated:  METERVAULT_SEED=true docker compose -f deploy/docker-compose.yml up -d
# API docs at http://localhost:8760/swagger

Quick start (Proxmox VE LXC)

A community-scriptsstyle installer builds a self-contained LXC (Debian + PostgreSQL/TimescaleDB + the app as a systemd service). Run on the Proxmox host:

bash -c "$(curl -fsSL https://git.finalfactory.de/FinalFactory/MeterVault/raw/branch/master/deploy/ct/metervault.sh)"

It asks the standard container questions, optionally loads the demo dataset, and prints the URL (http://<ct-ip>:8760) plus the generated DB password. Re-run update inside the container to pull the latest source and rebuild. It builds from this public Gitea repo (there is no prebuilt tarball — releases ship as a container image). See deploy/ct/metervault.sh and deploy/install/metervault-install.sh.

Configuration is via environment variables (Section__Key double-underscore mapping), e.g.:

Variable Purpose
ConnectionStrings__Default PostgreSQL/Timescale connection string
MeterVault__TimeZone IANA timezone for buckets, display and month attribution (default Europe/Berlin). Changing it re-derives every meter's stored consumption at the next start, and historical monthly figures can shift. It must be an id both .NET and PostgreSQL know; anything else falls back to UTC and is reported in the log.
MeterVault__Locale Default UI language, en or de (default en). Each visitor can switch it from the app bar; the choice is remembered in a cookie.
MeterVault__Currency Currency code of every amount (default EUR). Tariffs in another currency are reported as not fitting, never converted.
MeterVault__RawRetentionDays Shown on the Settings page but not enforced: raw readings are kept, because every recompute rebuilds a meter from them.
MeterVault__ApiKeys__0 An API key accepted on the X-Api-Key header
MeterVault__AllowAnonymousApi true to open the REST API without a key (trusted LAN only)
MeterVault__ReverseProxyTrust true to honour X-Forwarded-User behind an auth proxy
MeterVault__EnableLiveIngestion false to disable the MQTT/HA workers
MeterVault__SeedReferenceData true to load the bundled demo dataset on first start (idempotent)
MeterVault__DataProtectionKeyPath Where the key ring for UI-entered connector secrets lives (default /var/lib/metervault/keys)
MeterVault__UpdateCheckEnabled false to stop the dashboard checking for a newer release
MeterVault__AllowInAppUpdate true to allow updates triggered from the UI/API — no key required, so anything that can reach MeterVault can trigger one; see below
MeterVault__UpdateCheckUrl Tag listing consulted by that check (repoint at a fork; blank also disables it)

The REST API is closed by default: with no ApiKeys configured and AllowAnonymousApi off, it returns 401. Set at least one API key (or open it explicitly for a trusted network).

The web UI has no authentication. There is no login: anything that can reach the port can read and change everything, including connectors and their stored secrets. Put it behind a reverse proxy with auth (Authelia, Traefik forward-auth, …) — MeterVault__ReverseProxyTrust then honours the user header — or keep it on a trusted network.

The dashboard compares the running build against the newest tag in the source repository and shows a banner when it is behind. That is a plain GET of a public tag list — nothing about the instance is sent — cached for six hours, and it never blocks or fails a page render. Turn it off with MeterVault__UpdateCheckEnabled=false.

Updating from the UI (opt-in)

MeterVault__AllowInAppUpdate=true adds an Update now button to that banner, and a POST /api/v1/system/update endpoint for scripting it from Home Assistant or curl:

curl -X POST http://metervault:8760/api/v1/system/update -H "X-MeterVault-Update: 1"

Both pull the latest source, rebuild, and restart the service — a few minutes during which MeterVault is unavailable. Readings are untouched; ingestion resumes on restart. LXC only: containers are replaced by pulling a new image, and the endpoint reports that rather than pretending.

That flag is the whole gate — there is no key and no prompt. With it on, anything that can reach MeterVault can trigger a rebuild and restart. Realistically that is a repeatable denial of service (minutes of downtime and a busy CPU per request), not code injection, because the build comes from your own repository — but it becomes remote code execution if that repository is ever compromised. It defaults off. Enable it only on a network you trust, or behind an authenticating proxy.

The X-MeterVault-Update header is not authentication: it stops a different website driving the endpoint through the browser of someone on your network, which a plain HTML form could otherwise do. The UI button does not need it — it runs over the Blazor circuit, which a foreign page cannot reach. Every triggered update is logged as a warning, since with no key there is no caller to attribute it to.

Secrets (broker/HA tokens) are never stored in the database as plaintext. Each connector picks one of two forms: the name of an environment variable, resolved at runtime, or the secret typed into the admin UI and encrypted at rest under the data-protection key ring. Either way a pg_dump or JSON export carries nothing usable.

Keep the key ring on persistent storage outside the app directory — the default /var/lib/metervault/keys survives an LXC update, and the Compose file mounts a named volume for it. Lose it and every UI-entered secret must be re-entered. The key ring is on disk, so this protects against leaked database content, not against an attacker who already has the host; that is the same trust boundary an environment variable has.

Pushing readings (Home Assistant)

curl -X POST http://localhost:8760/api/v1/readings \
  -H "X-Api-Key: $METERVAULT_API_KEY" -H "Content-Type: application/json" \
  -d '[{"meterId": 1, "time": "2026-01-01T12:00:00Z", "value": 47200}]'

See docs/wiring.md for wiring up Tasmota, MQTT and Home Assistant.

Development

dotnet build
dotnet test                       # integration tests spin a TimescaleDB via Testcontainers (needs Docker)
dotnet test tests/Core.Tests      # fast unit tests, no Docker
dotnet run --project src/App

Architecture, project layout and conventions live in CLAUDE.md.

Releasing

Edit the VERSION file on master; Gitea Actions tags vX.Y.Z and builds/pushes a multi-arch image to the Gitea container registry (.gitea/workflows/). Locally: pwsh deploy/build-and-push.ps1 -Registry git.finalfactory.de -Image finalfactory/metervault -Push. Requires a Docker-capable act_runner; the image build itself is self-contained.

License

Not yet chosen (see SDD §14). Add a LICENSE before the first public tag.

S
Description
No description provided
Readme
4 MiB
Languages
C# 83.8%
HTML 14.8%
CSS 0.7%
Shell 0.6%