Eloverblik

Dokumentation · Arkitektur og beslutninger

A1 – Solution architecture

Status: version 2, revised 15 November 2026 after two reviews of version 1 (commit 23278cd): the advisor's (reviews/architecture/advisor-1.md, approve with changes, findings A1v-01…19) and the second-family review (reviews/architecture/codex-1.md, not sound, findings A1x-01…17, two blockers). Appendix B lists every finding with what was changed. Written by worker elo-a1-architecture (Claude · Fable · high). Briefs: orchestration/tasks/a1-architecture.md, orchestration/tasks/a1r-architecture-revision.md.

Status note, 15 November 2026 (third architect round). This document remains the design of the whole product. **Phase 1 has its own complete build specification, docs/architecture/phase-1.md; where the two differ, phase-1.md wins.** Phases 2 to 4 below are provisional: each is re-planned and re-reviewed before it starts, with what phase 1 taught, from this document, from Appendix C (the round 2 findings that concern later phases) and from phase-1.md §1.4 (what phase 1 simplified and what that costs at scale). The round 2 reviews are reviews/architecture/advisor-2.md and reviews/architecture/codex-2.md.

0. Reading guide

Inputs: docs/brief/owner-brief.md, docs/brief/decisions.md (D1–D11, fixed), docs/research/R1–R4, L1, L2, docs/legal/REUSE-GRANT.md, orchestration/WORKERS.md, and the two reviews reviews/research/R1-codex.md (findings R1v-01…13) and reviews/research/R3-codex.md (R3v-01…21). R1 and R3 were read in their corrected versions (commits 4c3c311 and 430136f, each ending with "Review …: what was changed"), R2 and R4 at 551fbc2. Section numbers of R1 and R3 are those of the corrected versions. Where a review and a research document disagree, this document follows the review. The sibling project was read at <folder>/an earlier internal project (HEAD e0f85cc per R4 §0): docs/architecture/final-solution.md, docs/adr/ADR-002-spike.md, Makefile, deploy/, services/, web/, THIRD_PARTY.md, licence-policy.toml.

The lead's rulings built into version 2 (revision brief): phase 1 is the shortest honest path to the owner's own data in a browser, and nothing is built before the phase that needs it; the first load of the owner's history happens before 31 December 2026; the price-area emission figures are validated in phase 1 against the factor snapshot the lead saved on 15 November 2026; the design flair has its own task (A2) and its own epics; D11 as narrowed in §1.6 is accepted by the lead on the owner's behalf and listed for the owner's confirmation; the product is run against a business login with many metering points before any claim about scale.

Conventions. A decision is marked Decision: and is followed by its reason and the alternative rejected. References look like "R1 §9.4" (research document and section), "R3v-05" (finding of a research review), "A1v-04" and "A1x-02" (findings of the two reviews of version 1), "S&OP ADR-013" (the sibling's architecture document). "MP" is a metering point (målepunkt), identified by its 18-digit GSRN. "LB" and "MB" are location-based and market-based. Every number names its source; numbers computed here show the arithmetic. Epic numbers are new in version 2.

The architecture in ten lines.

  1. One PostgreSQL 18 database holds everything: request records, metering points, time series, factors, computed facts, aggregates, configuration. No DuckDB, no dbt, no generation schemas (§1.2). 2. A single worker owns all outbound traffic: a paced, resumable Eloverblik ingestion behind a source interface, and daily loaders for the public datasets. The API never calls an external service (§3). 3. Readings are stored one row per MP series and interval, UTC start, native resolution, in partitions that are Danish calendar months. A returned day replaces the stored day as a whole, and a per-day content hash turns an unchanged re-fetch into zero writes (§2.4, §3.9). 4. All time is stored as UTC instants; every day, week, month and year is a Danish local period (§4). 5. Location-based emissions are quantity × factor. Factors are stored per hour, area, gas and version with history. Results are materialised per MP, local day, accounting method and factor status, and per month; the interval level is a view over stored inputs (§2.7, §5). The accounting method is a dimension of every emission fact and a URL parameter (D11). 6. Market-based emissions are computed per reporting leaf (one MP's share in one node, under one boundary approach), where weights are applied once and instruments are matched once (§5.5). 7. Pre-aggregates serve the pages; a dirty queue recomputes only what changed; the server chooses the grain so that no series exceeds 750 points and no query scans more than a stated number of rows (§2.8, §6). 8. An Eloverblik refresh token is stored sealed: the API can write it and cannot read it (§8.1, from phase 2). 9. Reported periods are locked as whole local months, with the facts, the weights, the recipe and the input rows that produced them; later corrections and final factors appear as restatements (§5.8). 10. Phase 1 ends with the owner's own consumption and validated price-area emissions in a browser, on three pages in the analytical style (§10).

1. System shape

1.1 Services and their responsibilities

Compose serviceImage / packageResponsibilityTalks toFrom phase
postgrespostgres:18.7-alpine3.24, shm_size: 1gb (both as an earlier internal project/deploy/compose.yaml)The only data store–1
migrateimage of services/api, one-shotBootstraps the database roles, applies forward-only SQL migrations, loads reference seedspostgres1
apiservices/api (elo_api): FastAPI, Uvicorn, asyncpgNamed queries; exports; from phase 2 sessions, authorisation and administration (hierarchy, accounts, methods); from phase 3 targets, reports, locks. Never calls Eloverblik or Energi Data Servicepostgres; keycloak from phase 21
workerservices/worker (elo_worker)Scheduler and job queue; Eloverblik ingestion; public dataset loaders; calculation; aggregates; from phase 2 large exports, notifications and backup. The only process with outbound internet access and the only one that can open a tokenpostgres, the two external APIs1
caddycaddy:2.11.9-alpine (as S&OP)Reverse proxy for /api (and /auth from phase 2), serves the static web build; TLS in productionapi, keycloak1
keycloakquay.io/keycloak/keycloak:26.8.2 (as S&OP), own database in the same instanceOIDC identity provider; may federate Entra IDpostgres2

Decision: a modular monolith API plus one worker, as S&OP (S&OP ADR-013, ADR-014). Reason: one host, one organisation per install (D1), and the Eloverblik limits are per egress IP (R1 §9.1), so exactly one process must own that traffic. Rejected: separate ingestion and calculation services (two rate limiters to coordinate, nothing gained on one host).

**Decision: phase 1 runs in a local single-user mode, without Keycloak, the sealed token store and row-level security.** The stack binds to loopback, the API has one implicit user and refuses to start in this mode when its public address is not a loopback address, and the worker reads the refresh token from the environment (D2). Reason: the owner's first view needs one user on his own machine (A1v-02, A1v-15); identity, the sealed store and row-level security are built in phase 2, before any install other than the owner's machine. The seams exist from the start: the API logs in as the non-owner role elo_api and sets app.user_id in every transaction, and the shell talks to an AuthClient interface. Rejected: building identity first (it put 16 epics before the first view).

1.2 Where it differs from the S&OP platform, and why

TopicS&OP platformHereWhy
Build engine and layersDuckDB + dbt, bronze → hub → contract → biz → starNone. PostgreSQL only; layers are schemas (raw → core/ts/fx/price → calc/agg) maintained by SQL migrations and SQL functions that the worker callsSee the decision below
ServingImmutable generation schemas mart_g<id>, one activated at a timeLive tables and pre-aggregates; reported periods are frozen by locks (§5.8)Data arrives and is corrected in small daily increments for up to about 3 years (R1 §6.5); rebuilding and reloading 219 million rows per publication (§2.4) is waste. Reproducibility comes from change logs and locks instead
Semantic layerNamed SQL + catalog.yaml, two audiencesSame contract, one audienceEvery measure here is additive over MPs or over reporting leaves (or recomputed from additive parts), so a restricted user gets correct figures from the rows row-level security leaves visible; no stored headline rows exist
People's writesAppend-only planning eventsConfiguration tables with an audit trail; no workflow engineThere is no entry process, only stewardship
SecretsDatabase passwords, OIDC client secretThe same, plus a sealed store for Eloverblik tokens (§8.1)A token is a secret and personal data (L1)
BackupNightly pg_dumpNightly pg_dump in phase 1; base backup with archived write-ahead log from phase 2 (§8.6)A dump of tens to hundreds of gigabytes that changed in a few partitions is uploaded whole every night (A1v-10)
Volumespgdata, bronze, publishpgdata; from phase 2 exports, backups; from phase 3 reportsNo file exchange between engines
UnchangedPostgreSQL 18, Python 3.12 with uv, FastAPI/asyncpg, plain-SQL migrations, ops.job queue with SKIP LOCKED, Keycloak with backend-for-frontend sessions, row-level security through a non-owner role, Caddy, Docker Compose on one host, React 19 + TypeScript + Vite + TanStack Query, the vendored chart packages, make check, licence allowlist and notice inventory (D3)

**Decision: no dbt, no DuckDB and no medallion warehouse; SQL migrations, tables, views and set-based SQL functions in PostgreSQL are enough.** Reasons: (1) there is one source with one typed contract (R1), not several ERPs to conform, which was dbt's job in S&OP; (2) the unit of change is "one MP, one local day", and PostgreSQL can recompute exactly those units transactionally, whereas a batch build recomputes everything; (3) locks, restatements and the audit trail need transactions and constraints next to the facts; (4) one engine to operate and back up. Rejected: DuckDB over Parquet for the time series (faster scans, but a second engine, no row-level security, and file-based upserts for daily corrections); dbt-postgres (adds a tool to run the same SQL).

The serving query contract stays engine-neutral, as in S&OP ADR-002, so a columnar engine can be put behind it later if the scale gate (epic B22) fails its budgets.

1.3 What runs when

Times are Danish local time; the worker's scheduler (APScheduler, as S&OP) runs in Europe/Copenhagen and adds a random delay of up to 10 minutes. All times are configuration; the values are the defaults.

WhenJobWhat it doesSectionFrom phase
Continuouslyjob-runnerTakes jobs from ops.job; single-flight per job kind by advisory lock–1
While chunks are pending; runs above 500 calls only in the off-peak window (weekdays 18:00–06:00, weekends)eloverblik-backfillFirst load, newest quarter first, checkpointed per MP and chunk§3.51
04:30 dailyeds-loadOne call per dataset: rolling re-pull (120 days for declarations); from phase 2 prices, price list, mix, municipal coverage, the news feed§3.81
05:30 dailyeloverblik-dailyList MPs per account; re-fetch the trailing 14 local days for every series; retry due chunks§3.61
After every ingestion or load batchrecomputeDrains calc.dirty: MP-day aggregates, emission facts, months; from phase 2 cost and node-hours; bumps ops.data_version§5.71
Sunday 02:00eloverblik-weeklyMaster data (getdetails); from phase 2 charge links (getcharges) and the coverage reconciliation§3.61
Nights of the 1st–7th of each montheloverblik-control-sweepTiered Month control totals; re-fetch months whose total or quality changed§3.62
January, nightseloverblik-yearly-refetchFull re-fetch of the previous calendar year§3.62
On request (before a lock)eloverblik-closing-sweepFull re-fetch of the months to be locked§3.63
03:00 dailybackupPhase 1: pg_dump. From phase 2: incremental base backup; the write-ahead log is archived continuously§8.61
06:00 dailyhousekeepingPartition creation for the coming months; from phase 2 token expiry warnings, notifications, retention§81

API requests read; they enqueue jobs (ops.job) for anything slow (an Excel export of more than 100 000 rows, a manual re-fetch, a recalculation).

1.4 Repository layout and names

Nothing is named after [standard] (D5). The Python prefix is elo_, the npm scope @elo, the Compose project elo, the local address http://elo.localhost:8080.

eloverblik/
├── LICENSE  NOTICE  THIRD_PARTY.md  licence-policy.toml  notice-inventory.toml
├── Makefile  pyproject.toml  uv.lock  package.json  pnpm-workspace.yaml  pnpm-lock.yaml  biome.json  tsconfig.base.json
├── docs/{brief,research,sources,architecture,design,adr,legal,runbooks,guide}
├── orchestration/  reviews/
├── libs/
│   ├── core/            # elo-core (elo_core): time rules, code lists, typed models of the API payloads,
│   │                    #   reference implementations of every calculation. Pure functions, no I/O
│   └── sources/         # elo-sources (elo_sources): MeteringSource interface; Eloverblik Customer API client;
│                        #   Energi Data Service client; demo and replay sources. HTTP only, no database
├── services/
│   ├── api/             # elo-api (elo_api): auth/, security/, analytics/ (runner; one catalogue file and one
│   │   └── migrations/  #   queries directory per page), admin/, reports/, export/; migrations/sql/NNNN_*.sql
│   └── worker/          # elo-worker (elo_worker): scheduler, jobs, ingest/, loaders/, calc/, export/, backup/
├── tools/               # elo-devtools (elo_devtools): licences, notices, naming guard, testdb, synth (generator),
│                        #   capture (history capture), validate (report check); snapshot_declarations.py (lead's)
├── web/
│   ├── packages/
│   │   ├── charts/            # @elo/charts          (copied from an earlier internal project web/packages/…-charts, Apache-2.0)
│   │   ├── notation-tokens/   # @elo/notation-tokens (copied from …-tokens; stays CC BY-SA 4.0)
│   │   └── shell/             # @elo/shell           (forked from app-shell, Apache-2.0)
│   ├── apps/elo-web/          # the single-page app; one directory per page with its own strings module
│   └── tools/guard.mjs
├── fixtures/            # committed: generated contract fixtures, synthetic organisation definitions, golden
│                        #   calculation cases, small frozen extracts of public factor data (CC BY 4.0, attributed)
├── data/                # git-ignored: validation targets, the lead's factor snapshot, captured responses
├── deploy/              # compose.yaml, compose.dev.yaml, Caddyfile, dev.env, postgres/, testdb.sh, smoke.py;
│                        #   from phase 2 keycloak/realm.json, backup/
├── tests/{contract,calc,security,validation,scale,e2e}
└── .github/workflows/ci.yml

uv workspace members: libs/core, libs/sources, services/api, services/worker, tools. pnpm workspace: web/apps/*, web/packages/*. Tool versions are those of S&OP (R4 §3.6): pnpm 11.1.3, Node ≥ 22, TypeScript 7.0.2, Vitest 5.1.0, Biome 2.6.7, Vite 8.3.8, React 19.3.1; Python ≥ 3.12, ruff, mypy strict, pytest.

**Decision: calculation and time rules live in libs/core as pure Python and again as SQL functions in the migrations; a test asserts that both give the same result.** Reason: emission and cost arithmetic is where an error is expensive (D9); the SQL is what runs over hundreds of millions of rows, the Python is what a reviewer can read and what the golden cases are written against (§5.9). Rejected: Python only (row-by-row over 219 million readings); SQL only (no independent check).

Decision: files that several page epics would edit do not exist. Each page directory holds its own catalogue file, queries and strings module, merged at build; epic B01 adds every new dependency named below, so later epics rarely touch the lock files; each epic owns a reserved block of migration numbers and the tables listed for it in §10.5 (A1v-02).

New runtime dependencies beyond S&OP's, all on the S&OP allowlist by their published licence and confirmed against the pinned artefacts in epic B01: httpx (BSD-3-Clause), pynacl (Apache-2.0), zstandard (BSD-3-Clause), openpyxl (MIT), apscheduler (MIT), pydantic (MIT).

1.5 Configuration and secrets

ItemWhereNotes
Database passwords for elo_owner, elo_api, elo_worker; from phase 2 Keycloak admin and OIDC client secretRoot-only env file in production; deploy/dev.env with public development values (as S&OP)Three database roles, §8.3
Eloverblik refresh token, phase 1ELOVERBLIK_REFRESH_TOKEN in the owner's git-ignored .env, passed to the worker only (D2)Never logged, never written to the database; the data access token lives in the worker's memory
Eloverblik refresh tokens, from phase 2Table ingest.credential, sealedEntered in the administration page, or imported once by make token-import, which never prints the value, says that the token is still in .env in clear and offers to blank that line (A1v-11)
Token sealing key pair, from phase 2Public key: environment of api and worker. Private key: a Docker secret file mounted only into worker (ELO_SEAL_PRIVATE_KEY_FILE)§8.1. Never in the database, never in an image
Operational settings (call pace, concurrency, windows, schedule, retention, row budgets)Environment variables with the defaults of this documentChanging them needs no migration
Organisational settings (default accounting methods, GWP set, VAT status, working hours, boundary)Tables in schema org, edited in the app, auditedThey are data: they change figures and must be traceable. Every change increments ops.config_version (§6.4)
Reference data that Energinet says will move (report groups, grid areas, the 55 % waste rule)Seed files in services/api/migrations/seed/ loaded into ref.*, versioned in gitR2 §8 item 13
Mail server for notifications, from phase 2Environment (ELO_SMTP_*)The organisation's own SMTP server; no third-party service

1.6 One reading of the brief that this document narrows

The lead's consequence of D11 says every method is "computed and stored for every metering point and interval". This design computes every method for every MP and interval, stores the result per MP and local day and per month, and serves the interval level from a view that multiplies the stored reading by the stored factor row (§2.7). Storing the interval level too would add, for 5 000 hourly consumption series over five years, 5 000 × 43 824 × 4 = 876 million rows for the four hourly methods alone and 1.5 billion for all seven location-based methods of §5.1, each a deterministic product of two stored rows, and all rewritten each time a factor moves from Initial to Preliminary to Final (R2 §2.2.2). What D11 asks of the product is kept in full: every method is available on every page, in every export and at every level down to one hour, is never baked into a number, and every figure states its method. Two conditions make that true in practice and are part of the design: defaults never change a method inside a series (§5.2), and a locked figure can be traced to the inputs it was computed with (§5.8). The lead has accepted this reading on the owner's behalf; it is listed in §11 for the owner's confirmation (A1v-19).


2. Data model

Types: int = int4, bigint = int8, smallint = int2, ts = timestamptz, num(p,s) = numeric(p,s). "PK" is the primary key and states the grain. Every table has created_at ts unless it is a fact or a partition child; it is not repeated below. Row counts are given at the design scale: 5 000 reporting MPs, five calendar years 2021–2025 = 1 826 days = 43 824 hours per series (four common years and the leap year 2024; each year has one 23-hour and one 25-hour day, so hours = days × 24).

The model is designed for the whole product; each table is created by the epic that first writes it, in the phase that needs it (§10.5). "Phase" below is the phase in which a table first exists.

2.1 Schemas

SchemaContentWritten byPhase
rawEvery external request and its per-item outcome; payload bodies for a limited timeworker1
ingestChunk checkpoints, per-MP ingestion state, token-request reservations, dataset state (1); source accounts, sealed credentials, control totals, unknown-field register (2)worker; api writes accounts and credentials1, 2
coreMetering points, their tree, versioned master data, derived geography, access windowsworker1
tsSeries, readings, calendar-period readings, per-day load state, change logworker, only through ts.replace_day() and ts.replace_period()1
refCode lists, MP type policy, price areas, grid areas, municipalities, calendar, GWP sets, method catalogue (1); report groups, connected areas (2); thresholds and rules (3)migrations (seeds), worker (grid areas)1, 2
fxEmission factors per hour with history (1); grid mix, municipal renewable coverage, yearly factor sets (2)worker; api for yearly factor sets entered by a steward1, 2
aggSeries-day and series-month aggregates (1); node-hours (2)worker1, 2
calcCalculation runs, dirty queue, location-based emission facts (1); mix facts, cost facts (2); market-based leaf facts (3)worker1, 2, 3
opsJob queue and history, data version (1); configuration version (2)worker, api1
orgHierarchy above the MPs, allocations, tags, method defaults, settings, attributes, site calendars (2); boundary weights and status, production links and attributes (3); manual energy (4)api (stewards)2, 3
priceSpot prices, charges, charge prices, charge links, supply contracts, invoice checksworker; api for contracts and invoice checks2
auth, sec, auditUsers, identities, grants, sessions; security functions; audit eventsapi2
mbClaims, their evidence and eligibility, application sets and applications (market-based)api3
planTargets, budgets, forecasts, base yearsapi, worker (forecast)3
rptReports and their method mapping, period locks, locked facts and inputs, restatements, approvalsapi, worker (lock job)3

2.2 Raw layer

**Decision: the request record lives in PostgreSQL: one row per HTTP request, one row per requested item with its outcome and content hash, and the item's payload body for 90 days.** Reason: the request record, the parsed rows and the checkpoint commit in one transaction, which is what makes a replay a no-op (§3.9). What an auditor asks for is the hash, the retrieval time, the source and the quality codes (R3 §6), and the parsed rows lose nothing of position, quantity and quality; the bodies serve debugging, are 18.6 GB before compression at scenario A and are the larger personal-data footprint, so they are not kept for good (A1v-15). Rejected: bodies kept as long as the readings (version 1); files on a volume (S&OP's bronze): two stores to keep consistent.

Decision: no raw table holds a GSRN, an upstream free text or an unclassified field. Items are keyed by the internal mp_id; errors are stored as the documented code only; payloads are reduced to an allowlist before hashing and storage (§8.4). Reason: a removed MP must not survive in request metadata, and an error string or an unknown field can carry a name, an address or a token (A1x-05, A1x-06).

TableGrain / PKColumnsPhase
raw.fetchone HTTP request; PK fetch_id bigint; not partitioned, so that evidence links are plain foreign keys (A1x-07)source smallint (1 Eloverblik Customer, 2 Eloverblik Third-party, 3 Energi Data Service, 8 replay of a capture, 9 demo), account_id int NULL, endpoint text, request_key text (endpoint, window and the internal IDs requested, in canonical form; never a token or a GSRN), requested_at ts, duration_ms int, http_status smallint, user_correlation_id uuid (sent as X-User-Correlation-ID), server_correlation_id text (returned x-correlation-id; not a UUID, R1 §0), body_sha256 bytea (of the redacted body), body_bytes int, item_count smallint, error_code int NULL, retry_after_s int NULL, job_run_id bigint. Kept while any stored row refers to it, otherwise 5 years. At 2 001 calls a day (§3.7) about 0.7 million rows a year1
raw.fetch_itemone requested entity in one response; PK (requested_on date, fetch_id, item_no smallint); range-partitioned by month of requested_onmp_id int NULL, dataset_window text NULL, success bool, error_code int, outcome smallint (1 ok, 2 no data yet, 3 outside the available period, 4 permanent error for this request, 5 retry later, 6 parse error, 7 unsupported unit, 8 stale: an older response than the stored one), content_sha256 bytea (hash of the item's redacted content without volatile fields such as mRID and createdDateTime), rows_inserted int, rows_changed int, rows_deleted int, payload_kept bool, unexpected_error_text bool (the upstream text was not the documented name of the code; the text itself is discarded). Partitions older than 5 years are dropped; nothing refers to an item row by key1
raw.payloadPK (stored_on date, fetch_id, item_no); range-partitioned by month of stored_onencoding smallint (1 = zstd-compressed JSON), body bytea (after the allowlist of §8.4). Partitions older than 90 days are dropped (configuration)1
What is keptHow long (default; configuration)
Request and item records, hashes, outcomesRequest: while referenced, else 5 years. Item: 5 years
Time series payload bodies that inserted, changed or deleted readings90 days
Master data and charge payload bodies (allowlisted fields only) whose content hash differs from the previous one for that MP90 days; the parsed version rows are kept (§2.3)
Public dataset payloadsNot kept: the parsed rows carry retrieved_at, version and history (§2.6), and the data are public
Token responses, stack traces, upstream error texts, fields outside the allowlistNever stored

Size: the first load's time series payloads are 219.1 million points × about 85 bytes of JSON (R1 §9.4) = 18.6 GB uncompressed at scenario A and 130.4 GB for the tree of L1 at every site (§2.4), held for 90 days. The compression ratio is not measured; epic B22 measures it.

2.3 Metering points and the organisation above them

**Decision: an MP is a node of a typed tree; its master data is versioned by observation; its place in the organisation, its reporting weight and its accounting method are separate assignments.** Reason: the API delivers master data as a snapshot without effective dates (R1 design item 10), the tree decides what may be added (R1 §6.3), and R3v-05/06 require the reporting boundary to be numeric weights and classes that are independent of who holds the supply contract. Rejected: one wide MP table with current values (loses the history an auditor asks for, R3 §6).

TableGrain / PKColumnsPhase
core.metering_pointone MP; PK mp_id int; unique gsrn char(18)parent_mp_id int NULL, root_mp_id int (itself for a parent), type_code text (→ ref.mp_type), account_id int NULL (NULL for an MP a steward registered by hand), first_seen_at ts, last_seen_at ts, status smallint (1 active, 2 no longer listed, 3 no access), has_relation bool, is_moved_out bool NULL1
core.mp_versionone observed version of master data; PK (mp_id, observed_from ts)observed_to ts NULL, content_sha256 bytea, fetch_id bigint, typed columns: sub_type text, physical_status text, net_settlement_group text, connection_type text, grid_area char(3), grid_operator_gln text, grid_operator_name text, municipality_code char(3), postcode text, city text, street text, building_no text, floor text, room text, location_description text, dar_reference uuid NULL, supplier_gln text, supplier_name text, consumer_cvr text, data_access_cvr text, consumer_name text NULL (restricted, §8.4), asset_type text, capacity_kw num(12,3) NULL, reading_occurrence text, unit text, product text, tax_reduction bool NULL, alias text, meter_number text, protected_name bool, protected_address bool, occurrence_raw text. Only fields on the allowlist of §8.4 have a column; a field the allowlist does not know is not stored. When the MP is protected, the address columns are NULL (§8.4)1
core.mp_geoderived geography of an MP over time; PK (mp_id, valid_from date)valid_to date NULL, price_area char(3), municipality_code char(3) NULL, rule smallint (1 from grid area, 2 from municipality, 3 set by a steward), ambiguous bool1
core.mp_accessa window in which an MP's data can be read through an account; PK (mp_id, account_id, access_from date)access_to date NULL, source smallint (1 listed by the API, 2 discovered by probing, §3.4), observed_at ts. Several rows per MP are normal: a moved-out MP, a second access period, later one row per power of attorney (D1). Chunks are planned inside these windows1
org.nodeone node of the organisation tree; PK node_id intparent_id int NULL, node_type smallint (1 organisation, 2 legal entity, 3 site, 4 building), code text, name text, cvr text NULL, valid_from date, valid_to date NULL, pictogram text NULL2
org.node_closureancestor × descendant; PK (ancestor_id, descendant_id)depth smallint. Maintained by trigger2
org.mp_allocationwhere an MP's quantity belongs; PK (mp_id, node_id, valid_from date)valid_to date NULL, share num(7,6) (default 1). Constraint: at any date the shares of one MP sum to at most 1. Only root MPs are allocated; children follow their root. One row of this table on one day is a reporting leaf (§5.5)2
org.dimension, org.dimension_membera tag family (cost centre, purpose, any other) and its members; PK dimension_id, member_idcode, name, parent_member_id NULL2
org.mp_dimensionPK (mp_id, dimension_id, valid_from date)member_id int, valid_to date NULL2
org.method_defaultdefault accounting method of a node; PK (node_id, family smallint)method_id smallint, set_by, set_at. family 1 = LB, 2 = MB. No validity dates: a default is a choice of presentation that applies to every period alike; its changes are in audit.event (A1v-04). Resolved through the nearest ancestor (§5.2)2
org.node_attributedenominators; PK (node_id, key text, period_start date)value num(18,4), unit text, source text. Keys: area_m2, fte, revenue_dkk, units_produced2
org.site_calendarworking hours of a node; PK (node_id, weekday smallint)open_from time, open_to time; inherited; default Monday–Friday 07:00–17:00, public holidays closed2
org.settingPK (key text, valid_from date)value jsonb, set_by. Keys include gwp_set, vat_registered, tax_refund_share, base_year, fiscal_year_start_month2
org.boundary_weightinclusion weight of a node or an MP under one boundary approach; PK (subject_kind smallint, subject_id int, approach smallint, valid_from date)weight num(7,6) (0–1), valid_to date NULL, basis text (why), set_by, set_at. approach 1 financial control, 2 operational control, 3 equity share, 4 ESRS reporting boundary. 1 or 0 under the control approaches, the equity percentage under equity share, the recognised share of a joint operation under approach 4 (R3 §1.5). An MP inherits the nearest ancestor's weight unless it has its own; without any row the weight is 13
org.boundary_statusfacts about a node or an MP that are not weights; PK (subject_kind, subject_id, valid_from date)valid_to date NULL, consolidated_group bool (member of the consolidated accounting group; independent of control and weight), lease_status smallint (1 owned and used, 2 leased in, 3 leased out), holder_node_id int NULL (the legal entity that holds the supply), user_text text NULL (who uses the energy, when it is not a node), set_by. Nothing here is inferred from who holds the Eloverblik relation (R3v-06)3
org.production_linkwhich consumption root a production MP belongs to; PK (production_mp_id, valid_from date)consumption_root_mp_id int, valid_to date NULL, export_mp_id int NULL (the series that carries the plant's export, when it is not the production MP's own child), confirmed_by, confirmed_at. Needed because an E18 plant is its own market MP and no field of the API links it to an E17 (R1 §6.3, open question 16). The product proposes a link when a production MP and a consumption root share a DAR reference or address; a link exists only when a steward has confirmed it (A1v-07)3
org.production_attributeattribute status of an own production plant; PK (mp_id, valid_from date)production_type text (solar, wind, …; renewable or not), attributes smallint (1 retained, 2 sold), valid_to date NULL, set_by. Decides whether self-consumed production is renewable under a market-based method or is treated at the residual mix (R3 §1.5, §3.3.3)3
org.manual_energy (phase 4)(node_id, carrier text, month date)quantity_mwh num(15,3), source_class smallint (fossil, nuclear, renewable), factor_ref, source text, entered_by. Purchased heat, fuels and production that no meter delivers; the inputs of E06, G19, G20 and of E02 where a plant has only inverter data4

ref.mp_type is the tree's rule book (seeded from R1 §5.1 and §6.3; a steward can change the switches, not the codes):

ColumnMeaning
type_code PK, name_da, name_enE17, E18, D01–D20, D99 as listed in R1 §5.1
role smallint1 consumption (E17), 2 production (E18, D05), 3 export to grid (D06), 4 import from grid, physical (D07), 5 tax basis (D15, D14), 6 surplus (D04), 9 other
fetch_timeseries boolfalse only for D99 by default
in_energy_totals booltrue for E17, E18, D05, D06 in their own measures; never a parent plus its children (R1 §6.3, L2)
chartable_as_load boolfalse for D15 and D04: a daily amount in the first hour is not a load (L1)
used_for_cost booltrue for every type that carries charges

Consumption reported everywhere (measure E01) is the E17 root's own series, as L2 confirmed against Eloverblik's report. Self-consumed production (E02) = production − export, computed in two cases only: a production child and an export child under the same root (D05 and D06), or a confirmed org.production_link, where production is the linked MP's series and export is the series the link names (for an E18 plant that delivers everything to the grid, export equals production and E02 is zero; R3 §3.3.1 "the export of an E18 point"). In every other case E02 is "unavailable" (R1v-07, R3v-04, A1v-07). A steward can register an MP by its GSRN that no account lists (status "no access"), so that the boundary list is complete independently of what Eloverblik returns (R3 §5, Q03).

Price area: core.mp_geo is derived from grid_area through ref.grid_area; if the grid area is missing, from the municipality unless that is ambiguous (330, 999); a steward can set it, and the row then carries rule 3 (R2 §2.8). An MP without a price area is listed on the data status page and has no emission or spot figures.

2.4 Time series

**Decision: one row per series and interval at native resolution in ts.reading, with a companion row per series and local day that holds a content hash and the provenance.** Reason: the brief's grain; and because Eloverblik returns one Period per local day (R1 §6.1), a per-day hash lets a re-fetch of unchanged days end without touching a reading row, which keeps the hot partitions free of dead tuples. Rejected: one row per series-day with value arrays (24–100 times fewer rows, but every hourly join to a factor needs an unnest, and a single corrected hour rewrites the day); it stays the fallback if B22 shows that the row model misses its budgets.

**Decision: a returned period is authoritative for its whole coverage, and the worker can write readings only through ts.replace_day() and ts.replace_period().** The function replaces the complete interval set of one series and one period in one transaction (§3.9): intervals that the new response no longer contains are deleted and logged, not left behind. Reason: an upsert by key keeps withdrawn intervals; four stored quarter-hours of 1 kWh replaced by one hourly value of 4 kWh would sum to 7 instead of 4 (A1x-02). Rejected: upsert by (series, interval start), as version 1 had it.

TableGrain / PKColumnsPhase
ts.seriesone series of one MP; PK series_id int; unique (mp_id, business_type)source_unit text, to_kwh num(12,6) NULL (1 for KWH, 1 000 for MWH; NULL for every other unit: not an active-energy series), first_start ts, last_start ts. Normally one per MP; a second only for formerly profiled history (R1 §4.8)1
ts.readingone value; PK (series_id, interval_start ts); range-partitioned on interval_start, one partition per Danish calendar monthseries_id int, quality smallint (1–5 = A01–A05), resolution smallint (15 or 60 minutes), interval_start ts (UTC instant), quantity num(15,3) NULL (kWh: the delivered value × to_kwh; NULL with quality A02 "missing"). Column order as listed, so that the row packs without padding. Only fixed-length resolutions live here: interval end = start + resolution. Check: the start is a multiple of the resolution. Within one series and local day all rows have one resolution, and intervals cannot overlap, because the day is replaced as a whole1
ts.reading_periodone value of a calendar-resolution series (P1D, P1M, P1Y, PXD); PK (series_id, period_start ts)period_end ts, resolution text, quantity num(15,3) (kWh), quality smallint, content_sha256 bytea, fetch_id bigint, source_requested_at ts, first_loaded_at ts, last_changed_at ts. For MPs read monthly or otherwise; the end is stored because a month is not a fixed duration (R1v-11). Exclusion constraint: periods of one series do not overlap. What can be computed from these rows is in §41
ts.day_loadcurrent load state of one series and local day; PK (series_id, local_date date)period_start ts, period_end ts, resolution smallint, points smallint, kwh_sum num(15,3), content_sha256 bytea (hash of period start and end, resolution, unit and the sorted points with position, quantity and quality), fetch_id bigint (→ raw.fetch: the response that is evidence for the current values), source_requested_at ts (a response requested earlier than this never replaces the day), first_loaded_at ts, last_changed_at ts, last_confirmed_at ts (last re-fetch that returned the same hash), withdrawal_seen_at ts NULL (a successful response did not contain this day; §3.9)1
ts.reading_changeappend-only log of every change to a stored value after the first load of its day or period; PK change_id bigintseries_id, interval_start ts, interval_end ts, old_present bool, old_resolution smallint NULL, old_quantity, old_quality, new_present bool, new_resolution smallint NULL, new_quantity, new_quality, changed_at ts, old_fetch_id, new_fetch_id. Covers inserts after the first load, changes, deletions and changes of resolution, in both tables. The interval set of a day as it was at time T is the current set with every change after T undone in reverse order; ts.readings_as_of(series, from, to, T) does that (§5.8)1

Row count for the first load, rows = series × days × points per day:

ScenarioArithmeticRows in ts.readingHeap and index (below)
A: 5 000 hourly series, no children5 000 × 1 826 × 24219 120 00018 GB
B: every site has four hourly series5 000 × 4 × 1 826 × 24876 480 00073 GB
C: 5 000 quarter-hour series, no children5 000 × 1 826 × 96876 480 00073 GB
L1: every site has the tree seen live, three hourly series and one quarter-hourly (L1)5 000 × 1 826 × (3 × 24 + 96)1 533 840 000128 GB
D: four quarter-hour series per site (upper bound)5 000 × 4 × 1 826 × 963 505 920 000293 GB
Full window on 15 Nov 2026 (2 144 days, R1 §9.4) instead of 1 826× 2 144 / 1 826A becomes 257 280 00021 GB
Growth if consumption moves to quarter-hours (R1 §6.7)5 000 × 365 × 96 per year175 200 000 a year15 GB a year

Size per reading, from PostgreSQL's documented storage layout (documentation chapter "Database Physical Storage", section "Database Page Layout": 23-byte tuple header padded to 24, 4-byte line pointer, 8 192-byte page with a 24-byte header): 24 + 4 + 2 + 2 + 8 + about 7 bytes for a three-decimal numeric = 47, aligned to 48, plus 4 = 52 bytes, 157 rows per page. Scenario A: 219.12 million / 157 pages × 8 192 bytes = 11.4 GB of heap. The primary key index entry is 8 + 4 + 4 (padding) + 8 + 4 = 28 bytes; at the default 90 % leaf fill that is about 263 entries per page, 6.8 GB: together 18.3 GB, 83.5 bytes per reading, which gives the last column of the table. A month partition holds 5 000 × 744 = 3.72 million rows (about 190 MB of heap) at scenario A and 5 000 × 744 × 4 = 14.9 million when the series are quarter-hourly. These are estimates from the layout, not measurements; epic B22 loads the scenarios named in §10 and reports the real sizes.

Derived tables at scenario A, estimated the same way (a numeric(18,6) amount takes about 9 bytes): the day emission facts for the four hourly methods are 36.5 million rows × about 220 bytes = 8 GB plus 1 GB of index (§2.7); the series-day aggregates about 1 GB; day cost facts about 1 GB; month mix facts about 0.8 GB (the advisor's estimates, A1v-03). **Disk requirement, to be confirmed by B22: the database is about 35 GB at scenario A and about 150 GB with the tree of L1 at every site; the host needs three times that (dead rows between vacuums, write-ahead log, one restored copy during a restore test): about 105 GB and 450 GB. Memory: 16 GB.**

**Decision: partitions are Danish calendar months, declared with bounds such as FROM ('2026-03-01 00:00 Europe/Copenhagen') TO ('2026-04-01 00:00 Europe/Copenhagen').** Reason: every recomputation, lock and closing sweep works on local months, so a local month is exactly one partition; only the newest partitions receive writes, and older ones can be frozen once and left alone. Rejected: yearly partitions (a recomputation of one month reads a year); partitioning by series (thousands of partitions, and every time-window query touches all of them).

Indexes: the primary key only. A lookup for one series and a time range is a range scan of it; a recomputation for a month across all series is a sequential scan of one partition.

PostgreSQL does this well without helpPostgreSQL needs this help
Range scans by (series, time); partition pruning by time; parallel aggregation; AT TIME ZONE 'Europe/Copenhagen' and date_trunc(unit, ts, zone) for local periods; upsert with ON CONFLICT … DO UPDATE … WHERE … IS DISTINCT FROMAggregates across thousands of series: S&OP's serving spike met a 500 ms budget on 966 865 rows and missed it at ten times that (an earlier internal project/docs/adr/ADR-002-spike.md §1); scenario A is 227 times that row count, so pages never aggregate ts.reading across many series: they read §2.8
Transactions around payload, readings, change log and checkpointBulk loading: the worker copies a response into a temporary table and merges set-based; never row-by-row inserts
Row-level security on moderately sized tablesParallel queries in a container: shm_size: 1gb (the defect S&OP's spike found, kept in its Compose file)
Hot versus cold partitions: after the first load of a partition the worker runs VACUUM (FREEZE, ANALYZE) on it once; autovacuum then only works on the two or three newest
Memory settings: the image defaults (shared_buffers 128 MB, work_mem 4 MB, as recorded in S&OP's spike §2.2) are too small for this volume; B22 sets and records values for a 16 GB host
No time-series extension: TimescaleDB's compression and continuous aggregates are not under an OSI-approved licence, which the licence policy excludes (to be re-verified if ever reconsidered); the design does not depend on them

2.5 Reference data

TableGrain / PKColumns and source
ref.code(list text, code text)name_da, name_en, note. Every code list of R1 §5 (quality, sub-type, status, settlement group, connection type, asset type, unit, business type, resolution)
ref.mp_typetype_code§2.3
ref.price_areacode (DK1, DK2)name_da, name_en
ref.grid_area(code char(3), valid_from date)name, price_area, retrieved_at, source. Seed: the 45 areas of docs/sources/energi-data-service/samples/derived_grid-area-and-municipality-to-price-area_2026-08.json; refreshed monthly from DatahubMeasuringPointStatistics (R2 §2.8). Whether Eloverblik's meteringGridAreaIdentification is exactly this three-digit code is checked on the first real response (R2 open question 5); a value that does not match leaves the MP without a price area and visible as such
ref.municipalitycode char(3)name, region, price_area NULL (NULL for 330 and the placeholder 999, R2 §2.8)
ref.calendar_daylocal_date datestart_utc ts, end_utc ts, hours smallint (23, 24, 25), iso_year, iso_week, weekday, month, quarter, year, is_weekend, is_public_holiday, holiday_name, is_working_day. Generated for 2015–2040 by a migration function from the PostgreSQL time zone database and a holiday rule file (seed/holidays_dk.yaml: rules with validity years, computed locally, R2 §5). The rule file is checked against an official list in B03, because the research marks the abolition of Store Bededag from 2024 as unverified
ref.report_group(code text, valid_from date)name_da, production_type, simple_group, renewable_share num(4,3), class smallint (1 fossil, 2 nuclear, 3 renewable, 4 other). Seed: the 17 codes of R2 §2.2.4, with Energinet's numerator (R3 §3.3.2): share 1 for wind (R18, R19), solar (R16), hydro (R11x) and biomass (R01, R01-1, R01-2, R01-3); 0.55 for waste (R17); 0 for the rest. R15x "Anden VE" has share 0 because Energinet's numerator leaves it out, and a result with a non-zero R15x quantity is flagged; R20 "Anden produktion" and R21 "Lager" are class 4 with share 0. Keyed on the code, never on the name
ref.connected_areacodeorigin_label_da, origin_label_en (West Denmark, East Denmark, Germany, Norway, Sweden, the Netherlands, Great Britain, unknown)
ref.gwp_setgwp_set textch4 num(6,2), n2o num(6,2), source, status. The named sets of R3 §1.4: AR5 = 28 / 265 (stated by Eloverblik and Energinet; reproduces their figures); KK2025 = 28 / 273 (Klimakompasset 2025); AR6-fossil = 29.8 / 273 and AR6-nonfossil = 27.0 / 273, both status = unverified until the IPCC table is saved as a source (R3 open question 13). "AR6" alone is not a set: it has two methane values and the declarations do not split methane by origin
ref.methodmethod_id smallint§5.1
ref.threshold(key, effective_from date)value, unit, source. Legal thresholds are data (R3 design item 15)

2.6 Emission factors, prices and charges

**Decision: every factor row is stored per gas with its dataset, version, retrieval time and the dataset's metadata timestamp, is upserted on its natural key, and every change of value or version writes the old row to a history table.** Reason: Initial → Preliminary → Final, the method change announced for 24 November 2026 and any silent revision are then ordinary updates that trigger recomputation (R2 design item 2, R3v-20). CO2e is never stored for hourly factors; it is computed from the gases with the chosen GWP set. Rejected: storing CO2e (fixes the GWP set at load time).

Phase: fx.factor_hour and its history exist from phase 1; the other fx tables and all of price from phase 2.

TableGrain / PKColumns
fx.factor_hour(dataset smallint, price_area char(3), allocation smallint, hour_utc ts)co2_g num(12,6) (g/kWh), ch4_mg num(12,6) (mg/kWh), n2o_mg num(12,6) (mg/kWh), co2_origin_g num(12,6) (g/kWh, before biogenic CO2 is set to zero), t_factor num(8,6), d_factor num(8,6), version smallint (1 Initial, 2 Preliminary, 3 Final), retrieved_at ts, meta_updated_at ts, fetch_id bigint, extras jsonb (columns of the dataset the loader does not know, §3.8). dataset 1 = DeclarationGridEmission, 2 = DeclarationTransmissionEmission; allocation 1 = 125 %, 2 = 200 %, 3 = Total
fx.factor_hour_history(dataset, price_area, allocation, hour_utc, superseded_at ts)the superseded row
fx.mix_hour(dataset smallint, price_area, hour_utc, connected_area text, report_grp_code text)share_ppm int, share_mwh num(14,6), version smallint, retrieved_at ts. dataset 1 = DeclarationGridmix, 2 = DeclarationTransmissionGridmix. A reload replaces the rows of an hour and area as a set; replaced and vanished rows go to fx.mix_hour_history (the same columns and superseded_at), so that the mix behind a locked figure can be reconstructed (A1v-05)
fx.re_coverage_hour(municipality_code char(3), hour_utc ts)re_share_pct num(9,6) (0–100), re_kwh_keep num(16,3), consumption_kwh num(16,3), retrieved_at ts; history table of the same shape. Loaded only for municipalities in which the organisation has MPs
fx.factor_setfactor_set_id intkind smallint (1 yearly declaration per price area, 2 yearly national, 3 general declaration: residual mix, 4 AIB residual mix, 5 supplier's individual declaration), publisher, name, supplier_gln NULL
fx.factor_year(factor_set_id, year smallint, area text, allocation smallint)co2_g, ch4_mg NULL, n2o_mg NULL, co2e_g_published num(12,6) NULL, gwp_basis text NULL, biogenic_co2_g NULL, loss_dist_share num(7,6) NULL, loss_trans_share num(7,6) NULL, re_share NULL, nuclear_share NULL, status smallint (1 preliminary, 2 final, 3 prior-year substitute, 4 approximation computed by the product's maintainers, labelled wherever shown), source_document text, source_url text, published_on date, entered_by. The published CO2e is kept beside the gases because recomputing from rounded gases does not reproduce it (R3v-19: 348.17 against the printed 348.07 g/kWh for 2025)
price.spot(price_area, interval_start ts)resolution smallint (60 until 2025-09-30, 15 from 2025-10-01), dkk_per_mwh num(12,4), eur_per_mwh num(12,4), dataset smallint, retrieved_at. A continuous series from Elspotprices and DayAheadPrices, seamless in UTC (R2 §2.5.1)
price.chargecharge_id int; unique (owner_gln, charge_type, code)charge_type smallint (1 subscription D01, 2 fee D02, 3 tariff D03), name, description, component smallint, basis smallint (the billable basis) and unit text (§5.6). The identity is owner, type and code (R1v-04)
price.charge_price(charge_id, valid_from date, source smallint)valid_to date NULL (exclusive), resolution smallint (1 = one price per day, 24 = one per local clock hour, 30 = per month), prices num(14,6)[] (1 or 24 values, DKK excluding VAT), retrieved_at. source 1 = DatahubPricelist, 2 = getcharges snapshot, 3 = charge links endpoint
price.charge_link(mp_id, charge_id, valid_from date)valid_to date NULL, factor int (quantity), capacity_kw num(12,3) NULL (entered by a steward for charges per kW, §5.6), source smallint (2 getcharges, 3 charge links endpoint), first_observed_at ts, last_observed_at ts, assumed_before_observation bool
price.supply_contract(node_id or mp_id, valid_from date)valid_to, kind smallint (1 spot plus margin, 2 fixed price), margin_dkk_per_kwh, fixed_dkk_per_kwh, subscription_dkk_per_month, entered_by
price.invoice_check(subject_kind, subject_id, month date)invoiced_dkk num(18,2), note, entered_by. The amount a steward read from the bill; makes a month "bill-reconciled" (§5.6)

Seeds for fx.factor_year in the repository, each row with its source: the yearly declaration 2021–2025 per price area and allocation (R2 §3.3), the general declaration 2024 and 2025 and AIB's Danish residual mix 2025 (R3 §3.1). A steward adds a year in the app; the entry is audited.

2.7 Computed facts

All quantities are stored in base units and converted only in queries (R3v-01): kWh; g CO2; mg CH4; mg N2O; g biogenic CO2; DKK excluding VAT. tCO2e = (co2_g + ch4_mg × GWP_CH4 / 1000 + n2o_mg × GWP_N2O / 1000) / 1 000 000. Emission and cost amounts are numeric, so that a recomputation gives the same digits whatever the order of summation; nothing is rounded before display (R2 §3.4.4).

**Decision: location-based facts are physical facts per MP; boundary weights and allocation shares are applied in the query, once. Market-based facts are per reporting leaf and boundary approach, with the weights already inside.** Reason: a location-based emission is linear in consumption, so weighting afterwards is exact. A market-based emission is not: eligible consumption contains the weight, and instruments are matched to nodes, so one physical MP fact multiplied by weights gives 900 g where 3 000 g is right, and gives two half-shares the same residual although one of them is covered (A1x-01; both cases are tests of B53). Rejected: one fact grain for both families, as version 1 had it.

TableGrain / PKColumnsRows at design scalePhase
calc.runone calculation run; PK run_id intstarted_at, finished_at, trigger smallint (§5.7), calc_version text (version of the SQL functions), method_versions jsonb, units_done int–1
calc.dirtywork queue; PK (scope smallint, scope_id int, local_date, what smallint)reason smallint, queued_at ts. scope 1 = one MP, 2 = a price area (every MP in it), 3 = a municipality, 4 = a node and its subtree; what 1 = aggregates, 2 = emissions, 3 = cost, 4 = node-hours. A factor restatement queues one row per area and day, not one per MP (A1v-13)transient1
calc.emission_dayreporting MP × local day × hourly method × factor status; PK (mp_id, local_date, method_id, factor_status smallint); partitioned by yearfactor_status: 1 Initial, 2 Preliminary, 3 Final, 0 pending (an input of the method is missing for those hours; the row then has kwh only). Measures, all numeric: kwh (grid-delivered consumption), kwh_basis (what the factors were applied to: kwh minus the local renewable part in the municipality methods), kwh_local_re, co2_g, ch4_mg, n2o_mg, bio_co2_g, loss_t_co2_g, loss_t_ch4_mg, loss_t_n2o_mg, loss_d_co2_g, loss_d_ch4_mg, loss_d_n2o_mg, loss_t_bio_co2_g, loss_d_bio_co2_g, loss_t_kwh, loss_d_kwh, kwh_mix_covered (the part of kwh_basis for which grid mix rows exist), re_kwh, nuclear_kwh; run_id int. A day normally has one row per method; a day whose hours have different statuses has one row per status. The data basis "Final only" reads the rows with status 3 (§5.7)4 hourly methods × 5 000 × 1 826 = 36 520 000, plus the mixed-status days; about 220 bytes a row: 8 GB and 1 GB of index. Phase 1 builds two methods: half of it1
calc.emission_monthreporting MP × local month × location-based method × factor status; PK (mp_id, month date, method_id, factor_status)The same measures. For the yearly methods (LB-AN-*, LB-ANDK-125): factor_status 4 final yearly factor, 5 preliminary yearly factor, 6 prior-year substitute; and co2e_published_g = kWh × the published CO2e of the factor set, kept beside the gases because it cannot be recomputed from them (§5.5, A1x-12). Months of a year that is not over are provisional under the yearly methods (§5.5)7 methods × 5 000 × 60 = 2 100 0001 (hourly), 2 (yearly)
calc.mix_monthreporting MP × month × geography × dimension × member; PK (mp_id, month, geo smallint, dim smallint, member text, factor_status)kwh num(15,3). geo 1 price area, 2 municipality; dim 1 energy source (the simple_group, plus "municipal renewable"), 2 origin (connected_area). The grid mix does not depend on the allocation percentage (R2 §2.2.4)about 21 members × 2 × 5 000 × 60 = 12 600 0002
calc.cost_dayroot MP × local day; PK (mp_id, local_date); partitioned by yearone num(18,6) column per component of §5.6, spot_benchmark_dkk (never part of a total), kwh, status smallint (1 computed from observed links, dated prices and an entered contract; 2 estimate: links assumed or no contract; 3 incomplete: a price, a billable basis or a series is missing; 4 bill-reconciled), run_id5 000 × 1 826 = 9 130 0002
calc.cost_monthroot MP × monththe same300 0002
calc.mb_runone market-based calculation; PK mb_run_id intapplication_set_id, year, approach, method_id, started_at, calc_version, status smallint (1 current, 2 superseded)–3
calc.mb_leaf_yearrun × reporting leaf; PK (mb_run_id, mp_id, node_id)q_kwh (eligible consumption of the leaf: Σ over days of consumption × allocation share × boundary weight, plus self-consumed production with sold attributes, weighted the same), applied_kwh, applied_renewable_kwh, applied_nuclear_kwh, residual_kwh, co2_g, ch4_mg, n2o_mg, co2e_published_g, nuclear_kwh, loss_kwh, loss_applied_kwh, loss gases, residual_factor_status (final or prior-year substitute), supplier_factor_set_id NULLleaves × approaches × methods per year: 5 000 × 2 × 2 = 20 0003
calc.mb_leaf_instrumentrun × leaf × claim; PK (mb_run_id, mp_id, node_id, claim_id)applied_kwh, target smallint (1 consumption, 2 losses). How each claim was spread; the evidence that no claim covers the same consumption twice–3
calc.mb_leaf_monthrun × leaf × monthThe year result prorated by the leaf's weighted monthly consumption; provisional until the year is over240 000 a year3
calc.v_emission_intervalview: reporting MP × interval × hourly methodreading × the factor row of its hour and area (and the municipal share), with the factor's version and retrieved_at: the lowest level of every drill-down. While calc.dirty holds a unit for the day, the view's rows for that day are flagged and the query answers preparing (A1v-05)not stored (§1.6)1
calc.v_emission_dayviewcalc.emission_day for hourly methods; for yearly methods the month fact prorated by agg.mp_day.kwh–2

Every page and export reads emissions through relations in which method_id is a column; no table or column name contains a method.

Where the measures of the KPI catalogue (R3 §5) come from:

MeasuresStored inComputed in the query
E01, E03, E04 (grid consumption, export, production)agg.mp_day, agg.mp_month of the series with the matching roleboundary weight, MWh
E02, E05 (self-consumption, total electricity)the same, production minus export in the two cases of §2.3; org.production_link, org.production_attributeavailability rule of §5.4
E07, E09, E10, E11a–c (renewable, nuclear, fossil; shares)calc.emission_day/month (re_kwh, nuclear_kwh), calc.mix_month; calc.mb_leaf_* for market-based methodsshares
G01–G05, G10, G11, G16 (Scope 2, gases, biogenic, losses, splits, intensity)calc.emission_day/month per location-based method; calc.mb_leaf_* for G02 and the market-based G05CO2e with the GWP set or as published; tonnes; weights for location-based figures; grouping
G07, G07S, G08 (instrument coverage, surplus, register)mb.*–
G12–G15 (intensities, base year, target)emission facts, org.node_attribute, plan.*, rpt.locked_factratios, variances
M02–M04 (per m², per FTE, per unit)agg.mp_month, org.node_attributeratios
M05–M10 (base load, peak, load factor, duration curve, off-hours share, day-type profile)agg.node_hour, or ts.reading for one MP; org.site_calendar, ref.calendar_daypercentiles, sorting, profiles
M12–M14 (cost, unit cost, price capture)calc.cost_day/month, price.spotratios
Q01a–Q04, Q06§5.10–
Q05 (anomalies)ts.reading, agg.mp_day; the anomaly table of B42the rule of R3 §5
E06 family, G17–G20, M01, M11, M15a–c, E12, G06a–T, G08R, G09not before phase 4, or unavailable for the reasons the catalogue gives–

2.8 Pre-aggregates

**Decision: three pre-aggregates, maintained incrementally by the worker from calc.dirty: series-day, series-month, and node-hour for large nodes only.** Reason: they cover the three shapes the pages ask for (ranking and tables of MPs by day or month; time development of any selection; hourly shape of the organisation) and each is bounded. Rejected: materialised views refreshed whole (a refresh rewrites everything for one corrected day); aggregating at query time without a budget (§2.4); node-hours for every node with more than one series, as version 1 had it (as many rows as the readings, rebuilt by every edit of the hierarchy, where a site fits the on-request budget below; A1v-15).

TableGrain / PKColumnsRows at design scalePhase
agg.mp_dayseries × local day; PK (series_id, local_date); partitioned by yearkwh num(15,3), resolution smallint, expected_minutes smallint (1 380, 1 440 or 1 500), present_minutes, measured_minutes (A04), estimated_minutes (A03), incomplete_minutes (A05), adjusted_minutes (A01), missing_minutes (A02 or absent), kwh_estimated, kwh_incomplete, max_kw real, max_kw_at ts, min_kw real. A check compares kwh with ts.day_load.kwh_sum; a difference stops the unit and is reported5 000 × 1 826 = 9 130 000 per series per site (× 4 with children)1
agg.mp_monthseries × local monthsums of the above; max_kw, max_kw_at; days_complete smallint; source smallint (1 from days, 2 from a calendar-period reading that covers exactly this local month, §4)300 0001
agg.node_hournode × UTC hour × price area × municipality; PK (node_id, hour_utc, price_area, municipality_code); partitioned by Danish monthkwh_consumption, kwh_export, kwh_production (num(15,3), each MP weighted by its org.mp_allocation.share), series_expected smallint, series_present smallint. Built only for nodes with more than 200 consumption series beneath them (the root and large entities)nodes × 43 824 × the price areas and municipalities beneath each; for the root alone at most 98 × 43 824 = 4.3 million2

Row budgets. A query never scans more than 2 million rows of readings or of a pre-aggregate (configuration; B22 confirms or changes the number). At hour grain that is about 228 series-years of hourly data: one MP, a site or a mid-sized selection is computed from ts.reading on request, a larger node from agg.node_hour, and a larger free selection (a tag, a multi-select) answers too_large_for_grain. At day grain the budget is MPs × days: 5 000 MPs allow 400 days; beyond that g=auto falls to months, which read the month tables (5 000 × 60 = 300 000 rows for five years). The sibling's spike missed 500 ms when its fact tables were ten times their size, about 2.6 to 2.7 million rows in the largest (ADR-002-spike.md §1), which is why the budget sits below that and why B22 measures it with row-level security on (A1v-03). If B22 shows that day grain over the whole organisation is needed beyond the budget, the remedy is a leaf-node × day × method aggregate, smaller than a change of engine. Nothing is ever sampled silently.

Quarter-hour series are summed to the hour in agg.node_hour; quarter-hour values are shown on the MP detail page only. Because the node-hour rows keep price area and municipality, hourly emissions of a large node for any hourly method are a join to the factor tables at query time, with at most 98 municipality rows per hour for the root. agg.node_hour carries physical quantities (allocation shares, no boundary weights).

2.9 Targets, scenarios, claims, reports

TableGrain / PKColumnsPhase
plan.targetone target; PK target_idnode_id (or dimension_member_id), measure text (a KPI ID of §7.2: E01, G01, G02, M12, M02 …), method_id NULL (required for emission measures: a goal names its method, R3 §1.1.1), gwp_set NULL, kind smallint (1 target, 2 budget), base_year NULL, target_year, note, set_by3
plan.target_value(target_id, month date)value num(18,6). The path is stored month by month; a helper proposes a linear or previous-year-profile path, which the steward saves. Nothing assumes linearity (R3v-18)3
plan.forecast_value(node_id, measure, method_id, month, version int)value, model text, created_at. Written by the worker (phase 3: remaining months = same month last year × the year-to-date ratio)3
plan.base_year(node_id, measure, method_id)year, value_at_lock, lock_id, recalculation_policy text3
mb.claimone underlying claim to an emission attribute; PK claim_id; unique natural key (kind, registry, external_id)kind smallint (1 cancelled guarantee of origin, 2 PPA, 3 supplier's individual declaration, 4 green tariff), registry text (the issuing registry, or the counterparty for kinds 2–4), external_id text (cancellation statement ID; contract number and delivery year for kinds 2–4), technology, renewable bool, nuclear bool, country, bidding_zone, production_from date, production_to date, hourly_profile_ref NULL, device, commissioning_year NULL (unknown allowed), re100_type NULL, exemption_class NULL, mwh num(14,3), co2_g, ch4_mg, n2o_mg (per kWh; zero for wind, solar, hydro), cancellation_date, beneficiary_text, beneficiary_node_id, covers_losses bool, legacy bool, entered_by. Importing the same cancellation twice violates the key (A1x-04)3
mb.claim_evidencePK (claim_id, document_id)sha256, file_name, uploaded_by, uploaded_at; the files are on the reports volume3
mb.claim_eligibilityone decision per claim and year; PK (claim_id, year)status smallint (1 proposed, 2 verified, 3 rejected), checks recorded one by one: evidence_present, beneficiary_is_ours (the beneficiary is a node of the organisation), same_market (the claim's market contains the consumption's; rule in ref.threshold), period_ok (production period against the consumption year; rule in ref.threshold, default: production within the year), unique_ok (the natural key and no other claim with the same registry, device, period and volume), decided_by, decided_at, reason. Only verified claims are applied; proposed and rejected claims are never in a reported coverage (R3 §1.1.2, A1x-04)3
mb.application_setthe plan of applications for one year and one boundary approach; PK application_set_id; unique (year, approach)status smallint (1 draft, 2 current, 3 locked), set_by. Each approach an organisation reports under has its own set; a set without applications is valid and gives the residual result3
mb.applicationPK (application_set_id, claim_id, node_id, target smallint)mwh_requested num(14,3); target 1 consumption, 2 losses. Constraint: within a set, Σ requested over a claim ≤ the claim's MWh. What is actually applied, and where, is computed by §5.5 and stored in calc.mb_leaf_instrument3
rpt.reportone report edition; PK report_idname, framework text (ESRS 2026, ESRS 2023, VSME, GHG Protocol, internal), month_from date, month_to date (whole local months), root_node_id, approach smallint, gwp_set, basis smallint (1 best available, 2 Final only), mb_loss_convention smallint, status smallint (1 draft, 2 approved, 3 superseded), supersedes_report_id NULL, lock_id NULL3
rpt.report_methodthe report's method mapping; PK (report_id, node_id, family smallint)method_id. One row at the root in the usual case; rows at lower nodes when parts use another method (D11). Resolved once when the report is locked and never afterwards (A1v-04)3
rpt.period_lockone lock; PK lock_idroot_node_id, month_from, month_to (whole local months; a lock of part of a month is refused, A1x-03), approach, basis, locked_at ts, locked_by, data_version bigint, config_version bigint, calc_version text, closing_sweep_job_id, mb_run_ids int[], status smallint (1 active, 2 superseded), reason3
rpt.lock_recipePK lock_idrecipe jsonb: for every method its version and variants, the GWP coefficients, the report groups and their renewable shares, the loss convention, the eligibility rules: everything a recalculation needs besides the rows below3
rpt.locked_factlock × MP × node × month × method × factor status × classification; PK (lock_id, mp_id, node_id, month, method_id, factor_status, consolidated_group bool, lease_status smallint)The measures of calc.emission_month (or of calc.mb_leaf_month), consumption and coverage of agg.mp_month, cost of calc.cost_month: each as a physical amount and as the amount weighted for the lock's approach, computed day by day with the allocation share, weight and classification valid on that day. An MP whose share, group membership or lease status changes inside a month has one row per state3
rpt.lock_inputthe public input rows the lock was computed fromCopies of the rows of fx.factor_hour, fx.mix_hour, fx.re_coverage_hour and fx.factor_year used for the locked months and areas, with their versions and retrieval times; the applications and eligibility decisions of the lock's sets; one table per source with lock_id in front of the source's key. For a locked year about 70 000 factor rows, up to 2 million mix rows and 8 760 coverage rows per municipality (§2.6)3
rpt.lock_factor_monthPK (lock_id, method_id, price_area, month)Consumption-weighted factor per gas, kWh by factor status, hash of the hourly rows: the factors.csv of the auditor's package (§6.5)3
rpt.lock_packagePK lock_idsha256, path on the reports volume, built_at. The auditor's package is built when the lock is taken and stored; a later download returns the same bytes (§6.5)3
rpt.restatementPK restatement_idold_lock_id, new_lock_id, reason text, approved_by, approved_at, summary jsonb (difference per measure and method, split by cause)3
rpt.approvalPK approval_idreport_id, user_id, role, approved_at, comment3

All tables of this section first exist in phase 3.

2.10 Users, roles and access

Copied in structure from S&OP (core.app_user, core.user_identity, core.role_grant, sessions, audit.event), in schema auth. All first exist in phase 2; phase 1 has one implicit local user (§1.1).

TableGrain / PKColumns
auth.app_useruser_id uuiddisplay_name, email, active
auth.user_identity(issuer, subject)user_id. Created at first login under an invitation, or by an audited link action (S&OP ADR-010)
auth.role_grantPK grant_id bigintuser_id, role, node_id int NULL (NULL = the whole organisation; otherwise the node and everything beneath it), valid_from date, valid_to date NULL. Two partial unique indexes: (user_id, role, valid_from) where node_id is NULL, and (user_id, role, node_id, valid_from) where it is not (A1x-07)
auth.user_mp(user_id, mp_id)Derived closure of grants over the tree and the allocations; rebuilt by trigger when grants, nodes or allocations change. Row-level security reads it (§8.3)
auth.session, auth.invitationas S&OP
audit.eventappend-only; PK event_id bigintat ts, actor_user_id, action, object_type, object_id, before jsonb, after jsonb, request_id. Covers every write in org, mb, plan, rpt, auth, fx.factor_year, price.supply_contract, ingest.source_account and every credential replacement (never the credential). before and after hold internal IDs, never a GSRN, a name or an address (§8.5)

3. Ingestion

3.1 The source interface

**Decision: ingestion talks to a MeteringSource interface; the Eloverblik Customer API is its first implementation, a demo source its second, the Third-party API a later third (D1).** Reason: the Third-party API returns the same master data, charges and time series (R1 §4.10) and differs only in how MPs and their access windows are found; the demo source lets the whole pipeline run in tests without a network, and a replay source feeds captured responses (the owner's history, B06) through the same path. Rejected: writing the ingestion against the Customer client directly and abstracting later.

class MeteringSource(Protocol):
    kind: SourceKind                      # customer | thirdparty | demo | replay (of captured responses)
    limits: SourceLimits                  # calls/min, token calls/min, max days per request, recommended batch
    async def health(self) -> SourceHealth
    async def list_metering_points(self) -> list[MeteringPointRef]      # roots and children, access_from/to if any
    async def get_details(self, gsrns: Sequence[str]) -> list[ItemResult[MasterData]]
    async def get_charge_links(self, gsrns: Sequence[str]) -> list[ItemResult[ChargeLinks]]
    async def get_timeseries(self, gsrns: Sequence[str], date_from: date, date_to: date,
                             aggregation: Aggregation) -> list[ItemResult[SeriesDocument]]

ItemResult carries the item key, an outcome, the source's error code and text, and the raw item. What differs for a third party is confined to list_metering_points (authorisations, accessFrom/accessTo, customer key) and to ingest.source_account (one account per refresh token, of either kind); core.mp_access already holds an access window per MP and account.

3.2 The Eloverblik Customer client

Endpoints used, and how each response is parsed. Parsing is per endpoint, HTTP status and content type; there is no universal wrapper (R1v-01).

CallUsed forSuccess shapeItem-level errorsRequest-level errors
GET /customerapi/api/isaliveHealth before and during large runsbare true–503
GET /customerapi/api/token (refresh token)Data access token{"result": "<JWT>"}–401, 403; body codes 50000–50005
GET …/meteringpoints/meteringpoints?includeAll=trueDiscover roots and their childMeteringPoints{"result": [dto…]}, no per-item wrapper–401
POST …/meteringpoint/getdetailsMaster data, roots and children{"result": [{success, errorCode, errorText, id, result}…]}per item400 (ProblemDetails, or a string with #nnnnn: or [nnnnn]), 401, 429, 503
POST …/meteringpoint/getchargesCharge links now and in the future (captured in phase 1, stored from phase 2)same wrapperper itemsame
POST …/meterdata/gettimeseries/{from}/{to}/{aggregation}Readings (Actual) and control totals (Month)same wrapper with MyEnergyData_MarketDocumentper itemsame
POST …/meteringpoint/getchargelinkswithchargesDated links and prices, when Energinet enables it{"result": {results[]: {meteringPointId, error, chargeLinks[]}, chargeInformations[]}}error string per result404 = feature disabled (R1 §4.7): probed weekly, used only when it answers
POST …/relation/addLink MPs registered to the CVR that have no relationper-item wrapperper itemNever called automatically: relations cannot be deleted any more (R1 §4.4). The administration page lists unlinked MPs and a steward links them with a confirmation
CSV exports, retired endpointsnot used

Parsing rules, all from L1 and R1 unless noted:

RuleDetail
TypesEvery scalar may arrive as a string, including booleans ("False") and numbers. No property is required by the schemas: the decoder tells absent, null, "" and [] apart and treats the first three as "no value"; arrays may be null; the payload of a failed item is never read (R1 §3.1). Fields outside the allowlist of §8.4 are discarded; only their names are counted
MatchingItems are matched on id / MarketEvaluationPoint.mRID.name, never on order; results are keyed by (MP, period) because an ID can repeat per access period (R1 §3.1)
Position → instantstart = Period.timeInterval.start + (position − 1) × resolution, in UTC, only for PT15M and PT1H. A point is accepted if its start lies before the period's end; positions up to 25 (hourly) and 100 (quarter-hourly) occur (R1v-02). Calendar resolutions (P1D/PT1D, P1M, P1Y/PT1Y, PXD) take their boundaries from the period and go to ts.reading_period (R1v-11)
QuantityParsed as a decimal; more than three decimals is a parse error for that item (quarantined, never rounded)
QualityA02 without a quantity is stored as a missing value
Unitmeasurement_Unit.name KWH is stored as it is, MWH × 1 000; a series in any other unit (power, reactive energy, counts; R1 §5.7) is not loaded and gets the outcome "unsupported unit": it is never summed as energy (A1x-15)
ErrorsThe documented code is stored; errorText and stackTrace are discarded (§8.4)
Mixed resolutionsOne response may hold PT1H and PT15M series; each series-day carries its own resolution
TimestampsBoth …Z and ….000Z forms

3.3 Token cache and pacing

**Decision: every outbound call to Eloverblik (data, token, health, probes) passes one deployment-wide pacer that starts calls at a fixed minimum spacing; there is no burst.** At the default of 60 calls a minute a call starts at most once a second, so no rolling minute can contain more than 60 starts, whatever happened before. Reason: the limit of 120 a minute is for all calls from the IP (R1 §9.1), and a bucket that refills while full can release almost twice its capacity in a rolling minute (A1x-16). Rejected: separate buckets for data and token calls (version 1).

MechanismDesignSource
Pace60 call starts a minute by default, configurable, hard ceiling 100: every call counts, so the ceiling leaves 20 a minute of the documented 120 unusedR1 §9.1, §9.2. 60 a minute is 5 % of the 1 200 a minute that all Eloverblik users share
Token callsAdditionally at most one a minute, deployment-wide. A row in ingest.token_request is written and committed before the call, and the pacer reads the last row; a worker that dies after receiving a token and restarts therefore waits, it does not call againR1 §2.2 (2 a minute per IP); A1x-16
Data access tokenOne per source account, valid 24 hours; renewed when less than 30 minutes remain; renewal serialised per account. Phase 1: held in the worker's memory. From phase 2: sealed and persisted in ingest.access_tokenL1 (24.0 h)
Concurrency4 requests in flightR1 §9.4's latency assumption; revisited after the measurement of B08
429A deployment-wide cooldown: no call starts for max(60 s, Retry-After), doubling on each further 429 up to 15 minutes; requests in flight finish; the failed request is retried after the cooldown and is not split, because a 429 is a signal about rate, not about the request (A1v-12, A1x-16). The cooldown is a row in ingest.pacer, so it survives a restartR1 §9.2
Off-peak windowA run that still needs more than 500 calls proceeds only on weekdays 18:00–06:00 and at weekends (configuration); the daily run is far below that for most installsR1 §9.4 "run it off-peak and spread it out"
Single runnerA PostgreSQL advisory lock makes sure only one worker process runs Eloverblik jobs, even if two are started–
TimeoutsConnect 10 s, read 120 sR1 §9.2 item 5 (value unverified)

3.4 Batching, partial success, retries and access windows

A request carries at most 10 MPs (Energinet's recommendation, R1 §4.1), grouped by account, by expected resolution and by window. One HTTP 200 can mix successes and failures; every item is recorded in raw.fetch_item and handled on its own. The outcome of a request window is kept apart from the state of the MP: a code that is permanent for one window says nothing about another window (A1x-09).

SignalAction
Item 10000The response is authoritative for the item's window (§3.9); the chunk becomes done
Item 30015 NoDataAvailableChunk state no_data, retried by the schedule of §3.5; stored days of that window are handled as possible withdrawals (§3.9)
Item 30018, 30017, 30010, 30016 (outside the available data period, before the oldest supported date, not covered by the access, relation expired in the period)Chunk state outside. The walk does not stop: the MP's readable windows are discovered (below) and the remaining chunks are planned inside them. The MP's own state changes only when the current daily window fails this way on three consecutive days: then it is "no current access" and listed
Item 20003, 20004, 20008 (malformed or unknown ID)Permanent for the MP: marked invalid, shown on the data status page, not retried until its master data changes
Item 20010, 40014 (no relation, no authorisation)"No current access" for the MP at once; historic chunks are not requested until a relation exists
Item 20011 UnknownErrorRetried by the chunk's schedule
HTTP 429Cooldown of §3.3; no splitting
HTTP 503 or a read timeoutWait 60 s and retry up to 3 times; then split: MPs 10 → 5 → 2 → 1, then for a single MP the period, halved down to one local day and no further. A chunk has a total budget of 8 attempts; when it is spent, or a one-MP one-day request fails, the chunk becomes parked with its next try, in the same transaction that records the failure. Five consecutive 503 answers pause all Eloverblik jobs for 15 minutes and check isalive
HTTP 400Parse the code; never resend unchanged (R1 §9.2 item 4). The planner never produces equal dates
HTTP 401 on a data callRenew the access token once (through the token pacing) and retry; a second 401 parks the job
/token answers 401, 403 or 50001The account becomes invalid, its jobs stop, the data status page (and from phase 2 a notification) says that a new token is needed

Discovering readable windows. When a chunk comes back outside, the MP's availability is located with single-MP requests in Month aggregation, whose responses are small: a binary search over the 71 months of the window for the first and the last readable month, at most ⌈log₂ 71⌉ = 7 probes per edge, 14 per MP. A chunk that straddles an edge is then requested with its dates clamped to the window, which costs one more call and cannot share a batch with MPs that have other windows; the edge month itself is searched by day in the same way (at most 5 more probes) when the clamped request is still refused. The windows are stored in core.mp_access. Every later request (daily, sweeps, closing) clamps its dates to the MP's windows, so a dateFrom before the first available day never rejects the item (R1 §6.6, A1v-12). These probes are counted in §3.7 as an upper bound per affected MP; how the API answers a request that straddles the end of an access period is not known and is one of the things the business-login run of B28 records.

3.5 First load and the chunk state machine

DecisionReasonRejected
Decision: Actual aggregation always.It returns every series at its own resolution; the API never splits values (L1)Hour (loses quarter-hour detail), Quarter (the same result as Actual in L1, but named for one resolution)
Decision: chunks are calendar quarters for hourly series and calendar months for quarter-hourly or unknown resolution.A quarter of 10 hourly MPs is at most 92 × 24 × 10 × 85 bytes = 1.9 MB (R1 §9.4); a month of 10 quarter-hourly MPs is 31 × 96 × 10 × 85 = 2.5 MB; calendar-aligned chunks make checkpoints readable. These are sizes to measure, not assurances against a timeout730-day chunks: about 15 MB per response, where timeouts are likely (R1 §9.4)
Decision: newest first. Every MP gets its most recent chunk before any MP gets an older one.The product is useful after one passOldest first
Decision: the window is the full "5 years + current year" (first day 1 January 2021 on 15 November 2026; the exact cut-off is unverified, R1 §6.6).Base years and five-year trends need it; history that ages out of the API cannot be fetched later, which is why the owner's history is captured before 31 December 2026 (§10, B06)A shorter default

ingest.chunk has one row per MP, purpose and window. States and transitions (A1x-10):

StateMeaningLeaves it by
pendingPlanned, not yet requestedThe runner takes up to 10 chunks with the same account, window and resolution class, newest window first
in_flightRequestedThe response's item outcome; a worker restart returns it to pending
doneThe item answered 10000 and the window was replaced (§3.9)A sweep that plans a new chunk for the window
no_dataThe item answered 30015Retried after 1 day, 7 days, 30 days and then every 90 days while the window is inside the API's range; after 8 attempts unresolved
outsideThe window is not readable for this MPWindow discovery (§3.4) replaces it by clamped chunks, or closes it as not_available when the MP has no readable day in it
parkedTransient failure after the attempt budgetIts next_try_at (1 hour, 6 hours, 1 day, then daily); after 8 further attempts unresolved
unresolvedNeeds a personListed on the data status page with its code; a steward re-queues it or closes it with a reason
not_available, invalidFinal for that window or MP–

A chunk is done only by its own item's success; it is never marked from its neighbours in the batch. The first load is complete for an MP when every chunk of its windows is done, not_available, or unresolved and shown. A stop at any point loses at most the requests in flight.

3.6 Recurring runs and re-fetch windows

RunWindow and calls per batch of 10 MPsWhy
DailyActual for the trailing 14 local days: 1 call. Also retries the chunks that are dueValues are typically 2–4 days late (R1 §11), the portal says up to 7 calendar days, and the drafted collection rule "5th working day" spans 12 calendar days across Easter (day of operation Wednesday; working days Tuesday, Wednesday, Thursday, Friday, Monday). That rule comes from a D1 text whose status is unverified (R1v-05), so 14 days is a default, not a guarantee; later arrivals are caught below
Weekly master datagetdetails: 1 call; from phase 2 getcharges: 1 moreMaster data and charge links change rarely; getcharges returns links valid now or in the future, each applied by its own validity (R1v-10)
Weekly coverage reconciliation (phase 2)No call of its own: it lists every series-month inside the MP's windows whose stored coverage is below 100 % or whose chunk is not done, and plans chunks for them within the retry scheduleRecovery of missing history must not depend on a control total changing (A1x-10)
Control sweep, tiered (phase 2)Month aggregation, month-aligned: the last 3 months every month (1 call); months 4–12 once a quarter (1 call); months 13–36 once a year and before a lock (2 calls). Then Actual for each MP-month whose control differsGrid companies reconcile monthly up to 3 years back and resend what differs (R1 §6.5). Energinet asks not to request several years repeatedly (R1 §9.2), hence the tiers: 12 + 4 + 2 = 18 calls per batch and year instead of 24 (A1v-12)
What the control comparesThe API's monthly quantity and quality against the values seen last time. On the first observation of a month there is nothing to compare with: the month is then verified against the stored sum of its readings, and re-fetched when they differ or when its coverage is incompleteA baseline taken after a correction would otherwise confirm stale hours for ever (A1x-10). The test never assumes that the monthly total equals the sum of the hours; where they differ after a re-fetch, the month is flagged as a quality finding
Yearly re-fetch (phase 2)Actual for the previous calendar year, in January: 4 calls for hourly series, 12 for quarter-hourlyCatches a correction that moves quantity between hours, or changes a quality, without changing a monthly total
Closing sweep (phase 3)Actual for the months to be lockedThe same, immediately before figures are reported; mandatory for a lock (§5.8)

3.7 The numbers

All counts are for one account with full batches; b = N / 10 for N reporting MPs. The window on 15 November 2026 is [2021-01-01, 2026-11-15): 2 144 local days, 24 calendar quarters, 71 calendar months (R1 §9.4; recomputed by both reviews). Profiles of a site:

ProfileSeries per siteFirst-load calls (list + details and charges + chunks)
Hone hourly parent1 + 2b + 24b = 1 + 26b
Qone quarter-hourly parent1 + 2b + 71b = 1 + 73b
4Hfour hourly series1 + 8b + 96b = 1 + 104b
L1three hourly and one quarter-hourly: the only tree seen live (L1)1 + 8b + 72b + 71b = 1 + 151b
4Qfour quarter-hourly series1 + 8b + 284b = 1 + 292b
First loadN = 100N = 1 000N = 5 000
H: calls · at 60/min · at 8/min261 · 4.4 min · 33 min2 601 · 43 min · 5.4 h13 001 · 3.6 h · 27 h
Q731 · 12 min · 91 min7 301 · 2.0 h · 15.2 h36 501 · 10.1 h · 3.2 days
4H1 041 · 17 min · 2.2 h10 401 · 2.9 h · 21.7 h52 001 · 14.4 h · 4.5 days
L11 511 · 25 min · 3.1 h15 101 · 4.2 h · 31.5 h75 501 · 21.0 h · 6.6 days
4Q2 921 · 49 min · 6.1 h29 201 · 8.1 h · 2.5 days146 001 · 40.6 h · 12.7 days
First usable state (list, details, charges, newest chunk): H · four-series tree31 · 121301 · 1 2011 501 · 6 001
RecurringN = 100N = 1 000N = 5 000
Daily run, H or Q: calls · at 60/min · at 8/min11 · 11 s · 1.4 min101 · 1.7 min · 13 min501 · 8.4 min · 63 min
Daily run, any four-series tree41 · 41 s · 5.1 min401 · 6.7 min · 50 min2 001 · 33 min · 4.2 h
Weekly master data and charges: H · four-series tree20 · 80200 · 8001 000 · 4 000
Control sweep per year (18 calls per batch): H · four-series tree180 · 7201 800 · 7 2009 000 · 36 000
Yearly re-fetch or closing sweep of one year: H · L1 · 4Q40 · 240 · 480400 · 2 400 · 4 8002 000 · 12 000 · 24 000

What the tables do not contain, and how it is counted:

ItemRule
The two time columnsThroughput estimates, calls ÷ rate. 60 a minute is the pace of §3.3. 8 a minute is 4 calls in flight at 30 seconds each, a latency nobody has measured (R1 §9.4); B08 measures it. They are not upper bounds: with a 120-second timeout, retries and breaker pauses no finite worst case follows
Dependency barrierThe list call precedes everything, so with 30-second calls a daily run takes at least 30 s + ⌈batches / 4⌉ × 30 s: 2 minutes for 100 H sites, 13 minutes for 1 000, 63 minutes for 5 000
Several accounts and partly filled batchesBatches are per account and resolution class: B_H = Σ over accounts ⌈H / 10⌉, B_Q = Σ ⌈Q / 10⌉. First load = A + 2 B_MD + 24 B_H + 71 B_Q for A accounts; daily = A + B_H + B_Q. With one L1-like site per account the daily run is 3 calls per site
TokensOne call per account without a valid token, and one renewal every 23.5 hours during a long load. At one token call a minute, A cold accounts need at least A − 1 minutes between the first and the last token call: 99 minutes for 100 accounts, 16.7 hours for 1 000. They overlap with data calls and count against the same pace
HealthOne isalive before a run and one every 5 minutes during it: 12 an hour, about 250 for the 21-hour L1 load at 5 000 sites
Window discoveryAt most 14 probes, one clamped call per edge and 5 day probes per edge for an MP with a refused chunk (§3.4)
Retries, the weekly probe of the charge links endpointNot estimated; reported by each run
The owner's own installOne account, one L1 tree: 1 + 2 + 24 + 71 = 98 calls for the first load, 3 a day

A first load of 5 000 sites with the tree of L1 is a job of about a day at the pace and of about a week if calls take 30 seconds; it runs in the off-peak window, newest first, and the data status page shows its progress.

3.8 Public dataset loaders (Energi Data Service)

Rules for all loaders (R2 §1): one call per dataset per minute at most, Retry-After honoured with a margin and exponential back-off after a 429; timezone=UTC and the UTC key column on every request; explicit sort on the key; limit=0 with a time window; a row budget of 17 500 rows per call, inside the largest response R2 observed without error (17 520 rows); the window is ⌊17 500 / rows per day⌋ days and is halved if a response reaches the budget. Datasets have independent limits, so loaders run in parallel. First-load window: from 1 January 2021, 2 144 days on 15 November 2026. Phase 1 loads DeclarationGridEmission only; the other datasets follow in phase 2 (§10). A loader can read saved files instead of the API, which is how the lead's snapshot of 15 November 2026 is used for the validation (§5.9).

DatasetFeedsRows per dayFirst load: calls (= minutes)Daily
DeclarationGridEmissionfx.factor_hour dataset 13 allocations × 2 areas × 24 = 144window 121 days → 18rolling 120 days = 17 280 rows → 1 call
DeclarationTransmissionEmissionfx.factor_hour dataset 2144181
DeclarationGridmixfx.mix_hour dataset 1720 to 2 832 (15 and 59 rows per area and hour in the two saved samples)90 to 3585 to 20
DeclarationTransmissionGridmixfx.mix_hour dataset 2same range90 to 3585 to 20
ReCoverageMunicipality, filtered to the k municipalities in usefx.re_coverage_hour24 × kk = 1: 3; k = 10: 30; k = 98: 307k = 10: 2; k = 98: 18
Elspotprices (DK1, DK2; ends 2025-09-30)price.spot481 734 days / 364 → 5, once–
DayAheadPrices (DK1, DK2; from 2025-10-01)price.spot19251 (the last 7 days and tomorrow)
DatahubPricelistprice.charge_pricevariesOne request per owner GLN for the charge codes in use, over the dataset's whole history (it starts in 2014), so that a price that became valid before 2021 and is still valid is present; split by year when a response reaches the row budget; a new owner GLN gets its own backfill (A1x-14)1 (ValidFrom in the last 3 months and the future; the filter acts on ValidFrom, R2 §2.6)
DatahubMeasuringPointStatisticsref.grid_area–11 per month

Further rules:

RuleDetail
UpsertOn the natural key; a row whose values or version differ goes to history first; the affected (area, local day) pairs are queued in calc.dirty for every MP in that area
Vanished rowsA key that a reload of its window no longer contains is moved to history and its area and day are queued; it is not left in place
ColumnsA column the loader does not know is kept in the row's extras and reported on the data status page; an expected column that is missing stops that dataset's load with a notice. Never a silent default (R2 §7 question 1, A1v-18)
News/News is read once a day; an item whose lastUpdated changed is stored in ingest.dataset_state and shown (R2 §1.8)
Monthly re-pullOnce a month every declaration dataset is re-pulled from 1 January of the previous year, so that the Final version published by 1 June and any revision older than 120 days are picked up (R2 §2.2.2, R3v-20)
Announced changesEach run reads /meta/dataset/{name}; a changed lastMetadataUpdate or caution text is stored in ingest.dataset_state and shown on the data status page. For the change announced for 24 November 2026 a re-pull from 1 September 2026 is preconfigured for the first run after that date (R2 §2.2.1)
Hours without a factorStay without one. No estimate from CO2Emis or GenerationProdTypeExchange is substituted; the consumption of those hours is reported as pending (§5.7)
DeclarationProductionNot loaded: it is "not to be used for green accounting purposes" (R2 §2.2.5). If it ever is, never filtered by one allocation method (R2 design item 7)
CO2Emis, CO2EmisProg, GenerationProdTypeExchange, benchmarksNot loaded before phase 4 (§10): they serve a "right now" tile and industry comparisons, not reporting
AttributionEvery page and export that shows these data carries "Kilde: Energinet (www.energidataservice.dk)" and says which values are derived (R2 §1.9)

3.9 Replacement and idempotency

One transaction per response. For every successful item, the response is authoritative for its window: what it contains replaces what is stored for the same series and period; what it no longer contains is withdrawn (A1x-02).

  1. Insert raw.fetch and the raw.fetch_item rows (after the allowlist of §8.4). 2. For each returned Period of a fixed resolution, compute the content hash over period start and end, resolution, unit and the sorted points (position, quantity, quality). 3. If ts.day_load.source_requested_at is later than this request's requested_at, the item's day is skipped with outcome "stale": an older response that arrives late never replaces a newer one. 4. If the hash equals ts.day_load.content_sha256: update last_confirmed_at only. A replayed or unchanged response writes no reading. 5. Otherwise call ts.replace_day(series, local day, points, …), which locks the day's ts.day_load row and brings the stored interval set of [period start, period end) to exactly the delivered set: rows that are not delivered are deleted, changed rows updated, new rows inserted, a change of resolution replaces all rows of the day. Every deletion, change and insert after the day's first load is written to ts.reading_change with presence, resolution, quantity and quality on both sides. ts.day_load gets the new hash, sum, point count, resolution and source_requested_at; the series-day is queued in calc.dirty; the payload is kept. 6. A day that the response does not contain. For a successful item, a local day of the requested window without a Period, which has stored readings, sets withdrawal_seen_at and changes nothing else. If the next successful response for that window, on a later run, again lacks the day, the day is withdrawn: its readings are deleted and logged. If the day comes back, the mark is cleared. A single response is never enough to delete a whole day, because "no data" is also what a slow day looks like. A failed item (any other code, or an HTTP error) changes nothing. 7. Calendar-resolution periods (P1D, P1M, P1Y, PXD) go through ts.replace_period() with the same rules, keyed by the period's bounds; a period that overlaps stored periods of the series replaces them. The Month answers of the control sweep are control observations in ingest.control_total and are never stored as readings. 8. A series whose unit has no conversion to kWh (to_kwh is NULL) is not loaded: the item gets the outcome "unsupported unit" and the series is listed on the data status page (A1x-15). 9. Mark the item's chunk done (or its other state, §3.5) in the same transaction.

A replay therefore changes nothing, a crash between two responses leaves no half-written day, and the sum of an hour can never contain both a withdrawn and a current value. Public datasets follow the same pattern on their natural keys: a row of an hour and area that a reload no longer contains is moved to history, not left in place.

Ingestion tables (schema ingest):

TableGrain / PKColumnsPhase
ingest.source_accountone source account; PK account_idkind, label, party_kind smallint (1 company, 2 private person, 0 not yet classified; set by a steward, §8.4), status (active, expiring, invalid, disabled), token_type, token_expires_at, last_ok_at, last_error_code. Phase 1 has one row, for the token in the environment1
ingest.token_requestPK (account_id, reserved_at ts)completed_at, http_status. Written before the call (§3.3)1
ingest.pacerone rowcooldown_until ts, consecutive_429 smallint, paused_until ts1
ingest.chunkPK (mp_id, purpose smallint, chunk_start date)chunk_end date, state, attempts smallint, next_try_at ts, last_error_code, fetch_id, done_at, split_from (the chunk it was clamped or halved from)1
ingest.mp_statePK mp_idobserved_resolution, last_daily_ok_at, current_access bool, daily_failures smallint, state_code1
ingest.dataset_statePK datasetloaded_through, meta_last_update, caution_sha256, news_last_updated, columns_seen text[], last_run_at, status1
ingest.unknown_fieldPK (endpoint, json_path)first_seen, last_seen, occurrences. The name of a field the allowlist does not know, never its value (§8.4)1
ingest.control_totalPK (mp_id, month date)api_kwh, api_quality, seen_at, stored_kwh, verified_at, status (1 verified equal, 2 differs: re-fetch planned, 3 differs after re-fetch: quality finding)2
ingest.credential, ingest.access_tokenPK account_id§8.12

3.10 Health

isalive is checked before each run and every 5 minutes during a run; it is cached by Energinet for 60 seconds and says little about a single request (R1 §0), so the breaker of §3.4 is the real protection. The data status page (§7.1, D3) shows per account: token expiry (from the exp claim, read once when the token is entered), warnings 60, 30, 14 and 7 days before it, last successful call, invalid state; per run: calls, 429 and 503 counts, items by outcome; per MP: readable windows, latest day with data, chunks by state; per dataset: latest hour loaded, hours pending, the stored notice and news. In phase 1 the same information is printed by make status; the page is built in phase 2.


4. Time

**Decision: one rule. Every instant is stored as timestamptz (UTC), every interval is half-open [start, end), and every calendar period (day, week, month, quarter, year, hour of day, working hours) is defined in the single business time zone Europe/Copenhagen.** Reason: UTC keys are unambiguous on the 23- and 25-hour days and are what both sources deliver (L1, R2 §4.3); the product has one format and one locale (D4). Rejected: storing local timestamps (the repeated hour collides); a time zone per user (not asked for, and every aggregate would depend on the viewer).

TopicRule
Local daylocal_date = (interval_start AT TIME ZONE 'Europe/Copenhagen')::date. A day is local midnight to local midnight: 23, 24 or 25 hours; ref.calendar_day holds its UTC bounds and length. Nothing assumes 24 or 96 points
WeekISO 8601 week (Monday to Sunday) of local dates, with the ISO week-year
Month, quarter, yearCalendar periods of local dates. A reporting year that is not the calendar year is a range of local months chosen in the report (org.setting.fiscal_year_start_month); yearly factors always belong to calendar years
AggregatesDay = Σ of the intervals whose start lies in the local day; week, month, quarter and year = Σ of local days. Stored aggregates carry local_date or the first day of the month, never a UTC day
Hour of dayThe local clock hour 0–23 of the interval start. On the 25-hour day clock hour 2 occurs twice: a profile averages the two as two observations, and queries return intervals and minutes per cell so a page can show it; on the 23-hour day clock hour 2 does not occur, which is "no such hour", not missing data
Expected intervalsPer series-day: length of the local day ÷ resolution (92, 96, 100 or 23, 24, 25). Completeness is measured in minutes of covered time, not in counts, so mixed resolutions add up (R3v-11)
Mixed 15-minute and hourly seriesStored as delivered. At hour grain a quarter-hourly series is the sum of its quarters. At quarter-hour grain an hourly series is returned at its own resolution and flagged; it is never split. A sum over mixed series is offered at hour grain and coarser
A meter that changes resolutionEach series-day has one resolution (ts.day_load.resolution); both kinds of rows live in the same table
PowerkW = kWh ÷ interval length in hours. Peak, base load and load factor of a site or of the organisation are computed from the summed hourly load (from ts.reading within the row budget, from agg.node_hour for large nodes), never by adding per-MP peaks; every such figure carries the resolution it was computed at, and an hourly average is not presented as a quarter-hour billing peak (R3v, catalogue remarks)
Joining hourly factorsKey = the UTC hour of the interval start; a quarter-hour takes the factor of its hour (R2 §4.2)
Joining 15-minute pricesA quarter-hour reading joins the price of its quarter; an hourly reading uses the mean of the four quarter prices of its hour; before 2025-10-01 the hourly price applies to both (R2 §4.2)
Tariff positionsPosition = local clock hour of the interval start + 1. Both occurrences of the repeated hour use the same position; the missing hour has no interval. This follows DatahubPricelist's statement on the transition days but is unverified against an invoice (R1 open question 14, R2 open question 7), so the mapping is one SQL function with its own golden test and is checked in B34
RequestsEloverblik: dateFrom inclusive and dateTo exclusive are Danish local dates (L1). Energi Data Service: timezone=UTC always; the …DK columns are never used as keys
PresentationDanish formats (D4) from one formatting module in @elo/shell; the API returns ISO 8601 instants with offset and local dates; conversion to text happens only in the browser
The frontier"Data through" replaces S&OP's "last closed month". For a selection it is the latest local day on which the value coverage of its active consumption series (Q01b for that day: minutes with a quantity ÷ expected minutes) is at least a threshold, 98 % by default (configuration), looking back at most 45 days. It is defined on coverage, not on the slowest series: a minimum over 5 000 series would sit a week back on most days, and one hour that is never delivered would pin it for ever (A1v-01). Series that have nothing on that day are named in the caveat ("12 of 5 000 metering points have not delivered"), holes before the frontier do not move it and are what Q02c reports. Period presets ("month to date", "year to date") end at the frontier, and a comparison with the previous year uses the same range of days in that year
Readings with a calendar resolutionA reading for a day, month or year (ts.reading_period) contributes to the grains that contain its whole period: a reading that covers exactly one local month to that month and to coarser periods; any other period only to the year or range that contains it entirely. Finer grains, hourly factors, spot cost and load measures are unavailable for that MP, and its consumption is reported under hourly methods as "without an hourly basis", beside the pending quantity. Nothing is spread over hours (A1x-08)

5. Calculation

5.1 The accounting methods ("opgørelsesmetoder")

ref.method is the catalogue: method_id, code, family (LB, MB), resolution (hourly, yearly), geography, allocation, name_da, name_en, purpose, factor_source, version int, status (available, unvalidated, unavailable), valid_from. The code is what appears in URLs and exports.

CodeDanish nameEnglish nameWhat it is forFactor sourcePhase
LB-PA-125Lokationsbaseret · time · prisområde · 125 %Location-based, hourly, price area, 125 %Scope 2 location-based (GHG Protocol 7.1; ESRS E1-8 §30(a)(ii); VSME B3 §33(b)). Eloverblik's "Prisområde". Product default for LBDeclarationGridEmission, allocation 125% (R2 §3.4.1)1
LB-PA-200… · 200 %…, 200 %The same with the other CHP allocation Energinet publishesthe same, 200%1
LB-MU-125Lokationsbaseret · time · kommune · 125 %Location-based, hourly, municipality, 125 %Eloverblik's "Kommune": deducts the consumption covered by local renewables; Energinet calls it the most precise declaration (R3 §3.2)ReCoverageMunicipality plus the emission factors chosen by the validation of §5.9 (R2 §3.4.2, §3.4.4)2
LB-MU-200… · 200 %…, 200 %2
LB-AN-125Lokationsbaseret · år · prisområde · 125 %Location-based, yearly, price area, 125 %The yearly declaration × consumption: a quick estimate, and comparison with accounts built on annual factorsEnerginet "Miljødeklaration, årsgennemsnit", in fx.factor_year kind 1 (R2 §3.3)2
LB-AN-200… · 200 %…, 200 %2
LB-ANDK-125Lokationsbaseret · år · Danmark · 125 %Location-based, yearly, national, 125 %Reconciliation with Klimakompasset, which uses the annual national declaration (R3 §2.4.2)fx.factor_year kind 2. Unavailable until a national factor is entered: the published workbook has no Denmark total (R2 §3.3). A steward may enter Klimakompasset's factor once obtained (R3 open question 4) or R2's consumption-weighted approximation; the row's status says which, and an approximation is labelled as one wherever it is shown4
MB-AN-ENMarkedsbaseret · år · residualmiks fra EnerginetMarket-based, annual matching, residual mix from EnerginetScope 2 market-based under the 2015 rules: contractual instruments applied per year, the remainder at the supplier's declaration or the residual mix (R3 §3.3.3). With no instruments registered it is consumption × the residual factor. Product default for MBVerified claims (mb.claim); supplier's declaration (fx.factor_year kind 5) where a contract gives one; otherwise Energinet's general declaration (kind 3)3
MB-AN-AIBMarkedsbaseret · år · residualmiks fra AIBMarket-based, annual matching, residual mix from AIBThe same with AIB's Danish residual mix for the remainder; CO2 only, CH4 and N2O unavailable, which the label says (R3 §3.1)Verified claims; fx.factor_year kind 44
MB-HRMarkedsbaseret · timematchMarket-based, hourly matchingHourly matching (the GHG Protocol revision's proposed "Method 1", SBTi C32; neither in force, R3 §1.2, §2.5)Hourly instrument data. Unavailable while no hourly Danish guarantees of origin exist (R3 open question 5)4; the code is reserved

The codes are those of the corrected KPI catalogue (R3 §5), which names LB-PA, LB-MU, LB-AN with the allocation percentage, MB-AN with its residual source, and MB-HR. Ten methods: seven location-based, of which four are hourly and materialised per day (§2.7), and three market-based, computed per reporting leaf (§5.5). The allocation percentage, the residual source and the variants of §5.3 are part of a method's identity or definition, so one method_id always means one way of computing.

5.2 The method is a switch (D11)

RuleDesign
Dimensionmethod_id is part of the key of every emission fact and a column of every relation that serves emissions (§2.7)
FilterEvery page and export that shows emissions has the parameter m in its URL: a method code, or lb / mb meaning "each part's default of that family". There is no global setting that changes stored numbers
Defaultsorg.method_default: one LB and one MB default per node, inherited from the nearest ancestor, without validity dates; the root starts with LB-PA-125 and MB-AN-EN. A report stores its own mapping (rpt.report_method), resolved once when it is locked
LabelEvery response states the method(s) used (§6.2); every figure, chart title line and export row carries the method's name or code
Location-based and market-basedNever in one total or one column; they appear side by side as two labelled figures (R3 design item 1)
Comparing methodsOne dedicated view (analysis page A4) shows methods as a structure dimension: one bar per method for the same period and selection, each labelled, never summed, never as a time variance
GWP set and data basisTwo further parameters, gwp (default: the organisation's setting) and basis (best available, or Final only; §5.7), applied at query time to the stored gases and status rows; both are shown in the footnote of every emission figure

A figure that mixes parts with different methods. It can arise only under m=lb or m=mb, or in a report whose mapping has rows below the root. The rules, each with its test (A1v-04; the tests are acceptance criteria of B41 and B55):

#RuleTest
1A request resolves one mapping MP → method, from the defaults as they stand now (or from the report's stored mapping), and applies that same mapping to the period, to the comparison period and to the target. A method never changes inside a seriesChange a site's default from LB-PA-125 to LB-MU-125: under m=lb both this year and the previous year of that site are now in LB-MU-125; under m=LB-PA-125 nothing has changed; in no method does the variance to the previous year subtract one method from another
2The figure is the sum of the parts' emissions, each part computed in its own method; an intensity is Σ emissions ÷ Σ kWh, never an average of intensitiesTwo sites with different defaults: the total equals the two single-method figures added, to the last stored decimal
3The response carries mixed: true when the mapping holds more than one method among the MPs that have consumption in the period, with one entry per method: code, kWh, share of kWh, emissionsThe same request: two entries whose kWh add up to the total
4A mix stays inside one family, one GWP set and one data basis. org.method_default and rpt.report_method are keyed by family, so a location-based mapping cannot contain a market-based methodInserting a market-based method under family LB is refused by a constraint
5A mapping that mixes 125 % and 200 % is shown on pages with a warning in the label; a report with such a mapping cannot be locked (R2 §3.5: not in one report)The lock is refused with that reason
6Label and export: the title reads "Lokationsbaseret (blandet: 2 metoder)", a footnote names the methods with their shares, the export has one row per part and methodAsserted on the page and in the CSV
7A variance to a target is computed only when the target's method equals the method of every part it covers; otherwise it is "not applicable" with the reasonA target in LB-PA-125 on a selection shown in LB-MU-125: no variance, a reason

5.3 Hourly location-based emissions

The recipe is R3 §3.3.2 with the symbols and units of R3 §3.3.1 (it binds Energinet's technical guide to R2 §3.4); it is not repeated here. What this design fixes on top of it:

PointDecision
Input CThe E17 root's own series in kWh, grid-delivered; children are never added (L2). Production and export never reduce it (gross accounting: GHG Protocol 5.4, ESRS AR 18(e), R3 §1.5)
Base quantity BPrice area: B = C. Municipality: L = C × REshare / 100 (local renewables), B = C − L. An MP without a known municipality is computed with the price-area recipe under the municipality method and flagged (R2 §4.2)
Per intervalco2_g = B × CO2PerkWh; ch4_mg = B × CH4PerkWh; n2o_mg = B × N2OPerkWh, with the factor row of the interval's UTC hour, the MP's price area and the method's allocation. Stored columns: kwh = Σ C, kwh_basis = Σ B, kwh_local_re = Σ L
LossesAdditive, per gas, per hour: transmission gas × (TFactor − 1), distribution gas × (DFactor − 1), both on base B, not compounded. The product TFactor × DFactor − 1 is a different quantity (R3 §1.3, R3v-03)
Biogenic CO2Consumption: Q × (CO2originPerkWh − CO2PerkWh); losses: the two loss quantities × the same difference (measures G04a, G04b). Q is C or B: variant (b) below
ScopesEmissions excluding losses are Scope 2. The loss amounts are Scope 3 category 3 and are never added to Scope 2. Biogenic CO2 is a memo line outside the scopes (R3 design item 8)
Renewable, nuclear, fossilfuel = B × SharePPM / 1 000 000 per report group and connected area. Renewable = L + wind (R18, R19) + solar (R16) + hydro (R11x) + biomass (R01, R01-1…3) + 0.55 × waste (R17): Energinet's numerator. Nuclear = R14. Fossil and other = C − renewable − nuclear, which includes 45 % of waste, R20 and R21. R15x "Anden VE" is not in Energinet's numerator and stays out; a non-zero R15x share is flagged on the result (R3 §3.3.2). The shares per report group are data in ref.report_group. These quantities are computed over the hours that have mix rows (kwh_mix_covered); the others are outside the share and its denominator (§5.7)
Source and origin splitcalc.mix_month: per report group's simple group and per connected area, plus "Kommunal vedvarende energi" (L) in the municipality methods
Three open variants, each one parameter of the method's definition(a) src: municipality emission factors and mix from the Transmission or the Grid datasets (R2 §3.4.4); (b) bioBase: municipality biogenic CO2 on C or on B (Energinet's guide and Eloverblik's page differ, R3 §3.3.2); (c) the price-area mix from the Grid or the Transmission mix dataset (R2 §3.4.4). Decision: all three are implemented as parameters, the validation of §5.9 chooses, and until it has, the municipality methods have status unvalidated and say so on screen. Initial values follow Energinet's technical guide: (a) Transmission, (b) C, (c) Grid
Changing a variantRaises the method's version and recomputes the method for all periods; locked periods keep their figures and show the restatement (§5.8)
What a figure namesIts method code, GWP set, and for the municipality methods src and bioBase, with the factor status behind it (R3 §3.3.4 rule 1)

5.4 Boundary, weights and what is summed

Location-based figures. A reporting total over a node for boundary approach a is Σ over MPs and days (fact × allocation share × w(MP, a, day)), with w from org.boundary_weight (R3 §1.5: a 30 % equity share contributes 30 %). The weights are applied in the query, once, to physical facts; this is exact because a location-based emission is linear in consumption. The data model holds four approaches (financial control, operational control, equity share, the ESRS reporting boundary); phase 3 builds and tests two, the organisation's consolidation approach and the ESRS reporting boundary, and the others when an organisation asks for them (A1v-15). In the ESRS reporting boundary a leased-in MP has weight 1 whatever the control approach, a leased-out MP has weight 0 in own operations and appears as its own line (downstream value chain), and a joint operation has its recognised share (ESRS 1 §§71–73, AR 36; R3v-06). The split "consolidated accounting group / other" groups the already weighted figures by org.boundary_status.consolidated_group (R3v-05). Before phase 3 there are no weights: every figure is physical and says so. Operational pages (load profile, MP detail, data quality) always show physical quantities. An MP without an allocation is counted at the root and listed as unplaced.

Market-based figures are not weighted in the query; their facts are already per leaf and approach (§5.5).

Physical electricity. E01 = Σ w × C; E02 (self-consumed own production) per production type and attribute status, in the two cases of §2.3 only; E05 = E01 + E02. Where an MP has a production plant (its asset_type and capacity say so) but neither a production child nor a confirmed production link, E02 and E05 are unavailable for every selection that contains it, and E01 is shown with the flag "excludes unmeasured self-consumption" (R3 §5, E05). Production minus export is computed only over intervals for which both series have a value. Nothing is ever netted against export.

5.5 Yearly and market-based methods

Yearly location-based methods (LB-AN-*, LB-ANDK-125): per MP and year C × factor_year(area, allocation, year), with losses = emissions × the year's published loss shares and renewable and nuclear quantity = C × the year's published shares. Month and day figures are the year's factor applied to the month's or day's consumption. Status follows the factor: preliminary (mid-January), final (by 1 June), or prior-year substitute.

Published CO2e (A1x-12, R3 §1.4). A yearly factor set that prints its own CO2e has it stored (co2e_g_published), and the facts carry co2e_published_g beside the gases. The CO2e of such a figure is the published one when the set's GWP basis is not stated or equals the selected GWP set; it is recomputed from the gases, and labelled "recomputed", only when the basis is known and differs from the selected set. The response says which (co2eBasis: gases for hourly factors, published, published, basis not stated, recomputed). The per-gas quantities are always those derived from the printed gases and are never adjusted to make the total agree; the difference is shown as a reconciliation line. Example: the 2025 general declaration prints 337.59 g CO2, 0.34 g CH4 and 0.004 g N2O per kWh and a CO2e of 348.07; the gases give 348.17 with 28 / 265. Its basis is not stated in the saved copy, so 348.07 is used and labelled "published, GWP basis not stated"; 30 MWh of residual consumption is 10.4421 t, not 10.4451 t.

Market-based methods (MB-AN-EN, MB-AN-AIB), phase 3. The grain is the reporting leaf: one MP's share in one node (a row of org.mp_allocation), under one boundary approach, for one year. Leaves are disjoint, and together they are the organisation's weighted consumption. The calculation of one calc.mb_run (R3 §3.3.3, A1x-01, A1x-04):

StepRule
1 Eligible consumption per leafq = Σ over days (C × allocation share × w) + self-consumed own production whose attributes were sold, with the same share and weight. The weight is applied here, once
2 Order of applicationsThe verified claims applied in the run's application set, deepest node first, then by claim ID. An application to a node concerns the leaves at or beneath that node
3 Applying one applicationApplied = min(requested kWh, Σ of the still uncovered q of those leaves). It is spread over those leaves in proportion to their uncovered q. Because deeper applications are served first and each takes only what is uncovered, an ancestor's and a descendant's applications can never cover the same consumption twice. What is requested and not applied is surplus (G07S), reported, never applied
4 Residualresidual = q − Σ applied, never negative by construction
5 Emissions of the leafΣ applied × the claim's factor + residual × the residual factor: the supplier's individual declaration where the MP's supply contract names one, otherwise the residual mix of the method. Gases and published CO2e as above
6 MixRenewable = applied renewable claims + self-consumed renewable production with retained attributes; nuclear = applied nuclear claims + residual × the residual mix's published nuclear share; the rest is fossil. The residual mix's own renewable share is not counted as renewable (R3 §3.3.3)
7 Losses (G05)Loss kWh of the leaf = the hourly loss quantities on base C (from the MP's LB-PA rows), with the same share and weight. Two named conventions, a setting of the report, never mixed: MB-GHGP (loss kWh × the location-based factor unless claims marked covers_losses are applied to the losses; the default) and MB-KK (loss kWh × the residual factor unless claims cover the loss quantity). Applications with target "losses" are matched to loss kWh by the same steps 2–4
8 TotalsA node's figure is the sum of the leaves at or beneath it; a selection of MPs is the sum of their leaves. No weight is applied afterwards
9 Months and daysThe leaf's year result prorated by its weighted consumption (annual matching has no finer truth). Months of a year that is not over are provisional under every yearly method, labelled so, and can be locked only with the whole year (A1v-14)
10 Residual factor not yet publishedNo preliminary residual factor exists (R3 §3.1): until publication the previous year's is used with status "prior-year substitute", and the run is repeated when the new one is entered

Two cases that the grain exists for, both acceptance tests: (1) 100 kWh, a residual factor of 100 g/kWh, no claims, an equity weight of 30 %: 3 000 g, not 900 g. (2) An MP of 100 kWh allocated half to node A and half to node B; A covers its 50 kWh with guarantees of origin, B covers nothing: A has no residual, B has 50 kWh.

A claim is applied only when its eligibility for that year is verified (§2.9): evidence present, the beneficiary is the organisation, same market, production period accepted, and unique. Importing the same cancellation statement twice is refused by the natural key; two claims with the same registry, device, period and volume are flagged for a steward before either can be verified.

Upstream emissions of electricity (G06a, G06b, G06T): not available, because no named, versioned upstream factor source exists (R3 §1.3). The measures return "unavailable" with that reason until a steward loads a factor set with its includesLosses flag; if the flag is set, G05 is a memo line and is not added again.

5.6 Cost

**Decision: cost is the sum of dated components, each priced on its own billable basis, in DKK excluding VAT; the spot value of consumption is a benchmark column and is never added to a total.** Reason: the grid tariff sits on the D07 child, the electricity tax on D15 and the national tariffs on the E17 parent (L1), each with its own quantity (R3v-09); and not every charge is priced per kWh (A1x-14). Rejected: one consumption series × a blended price.

Every charge has a billable basis (price.charge.basis), assigned from its type and resolution by a seeded rule and correctable by a steward:

BasisApplies toAmount
1 Energy of the linked seriesTariffs (D03) with 1 or 24 pricesΣ over intervals of the linked MP's kWh × the price of the tariff position (§4)
2 Amount per monthSubscriptions (D01, monthly)Monthly price × the link's factor × the share of the month's days on which link and price are valid
3 Amount per month and kWSubscriptions priced per kW (R2 §2.6: 40022)Monthly price × contracted capacity × the share of days. The capacity is not in the API: until a steward enters it on the link, the component is incomplete, never computed with 1
4 Monthly feeFees (D02) with a monthly resolutionAs basis 2
5 One-off feeFees valid on one dayThe price, on that day
9 Not supportedAnything else (per ampere, per reading, …)Incomplete, listed
Component (column of calc.cost_day)SourceBasis
energyThe supply contract of the MP (price.supply_contract): no contract: kWh × spot, status "estimate"; spot plus margin: kWh × (spot + margin); fixed price: kWh × the fixed price. Exactly one of the three, never twoE17 root series, per interval
energy_subscriptionThe contract's monthly subscriptionPer month, prorated by days
grid_tariffTariffs owned by the grid companyBasis 1 on the linked MP
tso_tariffEnerginet's system and transmission tariffsBasis 1 on the linked MP
electricity_taxCharge EA-001 and other charges flagged as taxBasis 1 on the linked MP (D15 in net settlement group 6)
subscription_grid, subscription_tsoSubscriptionsBasis 2 or 3
feesFeesBasis 4 or 5
tax_refund (negative)org.setting.tax_refund_share × refundable tax down to the minimum rate in forceOnly when the organisation has set a share; default 0
spot_benchmark_dkkkWh × spot of the price areaNot a component. A reference for price capture (M14) and for "what the same consumption costs at spot"; never in a total

Total = energy + energy_subscription + tariffs + tax + subscriptions + fees + tax_refund. With 100 kWh, a spot price of 1 DKK/kWh and a fixed contract of 2 DKK/kWh the energy component is 200 DKK, and the benchmark column shows 100.

Rules: a charge is identified by owner GLN, type and code (R1v-04); price.charge.component and basis are assigned by seeded rule tables, so that a new charge code needs a row, not code. **Price of a charge on a day, one source, in this order:** (1) the charge links endpoint, once Energinet enables it; (2) the DatahubPricelist row valid on that day; (3) the price observed in a getcharges snapshot, but only for days on or after the snapshot was taken; before that, without a price list row, the component is incomplete. An observed current price is never used as a historic price. The price list is loaded per charge in use over its whole history, so that a price which became valid before the product's window and is still valid is present (§3.8). **Links are known only from the first observation onwards** (R1v-03): for earlier days the current links are assumed and the status is "estimate"; without an entered supply contract the energy component is an estimate as well. A steward can enter the invoiced amount of a month (price.invoice_check); when it agrees with the computed amount within a tolerance the month becomes "bill-reconciled", otherwise the difference is shown (R3 §4, M12). Pages and exports show the split by status. VAT is never stored: a VAT-registered organisation sees amounts excluding VAT, others see 25 % added at presentation (R1 §8.4). The electricity tax is a dated series (0.8 øre/kWh in 2026–2027, R2 §2.5.2), like every other price.

5.7 Factor status, data basis and recomputation

RuleDesign
Version usedThe row currently in fx.factor_hour, whatever its version; the datasets hold one row per key (R2 §2.2.2)
Status of an hour for a methodThe lowest status among the inputs the method's recipe needs for that hour: the emission factor row (Initial, Preliminary, Final) and, in the municipality methods, the presence of the municipal coverage row. A missing input makes the hour pending; it is never read as zero: a missing coverage row is not "0 % local renewables" (A1x-13). The grid mix has its own coverage (kwh_mix_covered): hours without mix rows are left out of the renewable, nuclear and source quantities and of their denominators, and the share is shown with the kWh it covers
Stored by statusDay and month facts have one row per factor status (§2.7), so every figure can be split, and a basis can be chosen, without recomputation
Data basis, a parameter of query, report and lockbest (default): every hour with a factor, whatever its version; pending hours contribute consumption and no emissions, and the figure states "x % of the consumption has no factor yet". final: only hours whose status is Final; all other consumption is reported beside the figure as "not in the Final basis". It is a parameter and not a variant of a method, because it is a filter over stored status rows that applies to every hourly method alike (A1v-14 advised a variant; A1x-13 a parameter; the parameter keeps the method list at ten)
Period called "final"Only if all of its consumption has status Final (two hours of 2025 are still Preliminary, R2 §2.2.2)

Recomputation triggers (each inserts into calc.dirty):

#TriggerScope queued
1A reading changed, appeared or was withdrawnThat MP and day
2A factor, mix or coverage row changed, appeared or disappeared, also when its version label did not change (R3v-20)The price area (or municipality) and day: one queue row, expanded to its MPs when processed
3An MP's price area or municipality changedThat MP from the date of the change
4A method's definition or variant changedThe whole method
5Report groups or their renewable shares changedMix and renewable quantities
6A price, charge link, billable basis or contract changedCost for the validity range
7An MP was moved, a node re-parented, an allocation share or its dates changedNode-hours of the old and the new ancestors for the affected dates, and auth.user_mp. Debounced: the rebuild starts when no such edit has arrived for 5 minutes; until it has finished, hour-grain queries on those nodes answer preparing (A1v-13, A1x-11)

The recompute job processes the queue in set-based statements per local month partition, writes facts with a new calc.run, re-derives the month rows and node-hours touched, and increments ops.data_version. Settings that change results at query time without touching a fact (method defaults, boundary weights and status, allocations, production links, GWP setting, site calendars) increment ops.config_version in the transaction that changes them; both versions are in every cache key (§6.4), so a cached answer never survives an edit. A whole-year factor restatement for 5 000 MPs is 2 areas × 365 queue rows and 12 statements, each joining one month partition to a few thousand factor rows; B22 measures it.

5.8 Locked periods and restatements

**Decision: a lock covers whole local months, and freezes four things: the facts, the weights and classifications that were valid day by day, the recipe, and the input rows.** Reason: a lock that copies only month totals cannot say what [15 January, 1 February) was, classifies a month with one weight although an MP changed group in the middle of it, and loses its trace when a factor is restated or interval data are dropped (A1x-03, A1v-05). Rejected: locks with arbitrary dates (they would need day slices of everything for a case no reporting framework asks for).

Taking a lock, in this order: (1) the closing sweep for the months; (2) the recomputation, until calc.dirty is empty for the scope; (3) the lock job takes the advisory lock that recompute needs, so nothing changes under it, and in one snapshot transaction writes rpt.locked_fact (amounts physical and weighted, per MP, node, month, method, factor status and classification, computed day by day), rpt.lock_recipe, rpt.lock_input, rpt.lock_factor_month, the market-based runs it refers to, and the data, configuration and calculation versions; (4) builds and stores the auditor's package (§6.5). A report edition reads only its lock.

EventEffect
A correction arrives, or final factors replace preliminary onesThe live figure changes; the locked figure does not. Measure Q06 = live − locked, per measure and method, split by cause: readings (from ts.reading_change after the lock time), factors and mix (from the factor histories), boundary and allocation (from audit.event), method (recipe versions)
Someone drills into a locked monthMonth → days → intervals through calc.emission_interval_as_of(lock), which takes the readings as of the lock time (ts.readings_as_of) and the factor rows from rpt.lock_input; the intervals sum to the locked fact. The live view is offered beside it, labelled, with every change since the lock
Interval data of a locked period are dropped by retention (§8.5)The locked facts, recipe, input rows and package remain; the hour-level drill-down of that period ends and says so. The month level stays reproducible from the lock alone
The organisation restatesA new lock supersedes the old one; rpt.restatement records old, new, reason and approver; the old lock and its package stay readable (ESRS 1 §§84–87, 98; R3 design item 12)
The accounting method of a report changes between yearsThe comparatives are taken from the locked facts of the earlier year in the new method, which exist because every method is locked; the change is recorded as a restatement with the reason "method" (a metric redefinition, ESRS 1 §84). Whether published comparatives are revised is the organisation's decision; the product shows both
A yearly methodIts months can be locked only when the year is over and the whole year is in the lock (§5.5)

Tests (B55): a lock of half a month is refused; an MP that changes consolidated-group membership on the 16th has two rows whose sum is the month; a factor restated after the lock leaves the as-of intervals summing to the locked fact while the live view differs; a changed method variant does the same; after the retention job has dropped the intervals the package still downloads byte for byte and the month figures still reproduce from rpt.lock_input.

5.9 Validation against Eloverblik's own report (L2)

CheckWhere it runsWhat it asserts
Golden casesCI, tests/calcHand-computed fixtures, among them the reviewers': 1 000 kWh at 100 g CO2, 0.5 mg CH4, 0.1 mg N2O per kWh with GWP 28/265 = 100.0405 kg CO2e; with 30 % local renewables and the factor applied to the rest = 70.02835 kg; additive losses at 1.45 % and 3.87 % = 53.2 kWh-equivalents per 1 000, not 53.76; the market-based cases of §5.5; the cost cases of §5.6
SQL equals referenceCIFor a synthetic organisation and the frozen factor extract in fixtures/, the SQL facts equal the Python reference of libs/core for every method, to the last stored decimal. There is no third implementation: the reference is the readable loop (A1v-15)
The owner's reports, price area (phase 1, B12)Locally by the lead; skipped when data/validation/ is absentThe check runs the product's own report query (report.footprint, the blocks of L2's table) with the same parameters a user would set, on the owner's readings and on the factors of the lead's snapshot of 15 November 2026 (data/validation/declarations-2026-11-15/, loaded through the normal loader from files). It compares, after rounding to the report's printed precision: consumption (equal to the last decimal), emissions excluding losses, both losses, biogenic CO2 and the gas intensities, for the price-area reports with 125 % and with 200 % that the lead has asked the owner for, in both data bases. Source and origin splits and the renewable share follow in phase 2 with the mix datasets
The owner's reports, municipality (phase 2, B31)The sameThe same query for each combination of the three variants of §5.3 and both data bases, including the source and origin splits and the renewable share, against the municipality report of L2 and the further reports. The run prints the residual of every combination; the combination that matches is written into the method definitions by the lead, and the municipality methods become available. If none matches, they stay unvalidated and the closest combination and its residuals are reported
Why the snapshotEnerginet restates the declaration datasets (a method change is announced for 24 November 2026; whether history is recalculated is open, R2 §7 question 1). A report made on 15 November can only be compared with the factors of that day (A1v-06)
LimitsA report on preliminary data can be reproduced only with factors saved at the time: the datasets keep one version per hour (R2 §2.2.2). The lead has asked for one report on preliminary 2026 data; Eloverblik cannot compute reports for 15 September to the end of 2026 (R1 §10)

5.10 Data-quality measures

Definitions are those of the corrected catalogue (R3 §5, Q01a–Q06); durations, not point counts, so that mixed resolutions and 23- and 25-hour days add up. D is the required duration of an MP: the reporting period intersected with the period in which the MP has a boundary weight above zero.

MeasureDefinitionStored input
Q01a Measured coverageΣ minutes with quality A04 ÷ Σ Dagg.mp_day.measured_minutes, expected_minutes
Q01b Value coverageΣ minutes with any quantity (A04, A03, A05, A01) ÷ Σ Dpresent_minutes
Q02a Supplier-estimated sharekWh with A03 ÷ kWhkwh_estimated
Q02b Incomplete aggregateskWh with A05 ÷ kWh. The missing part is unknown and is not inferred; A05 is not an estimate (R3v-10)kwh_incomplete
Q02c Missing intervalsHours without a quantity (A02 or nothing delivered), and their share of Σ Dmissing_minutes
Q02d Product gap-fillAlways zero. Decision: the product never fills a gap. A missing interval contributes nothing and is counted in Q02c; an estimate of missing consumption would be an invented number in an audited total–
Q03 Boundary data coverageΣ duration with data access within D ÷ Σ D, and the number of in-boundary MPs without accesscore.mp_access, org.boundary_weight
Q04 Factor status, per methodShares by state: Final, Preliminary, Initial, substitute (prior-year value), pending (no factor; outside the total); on kWh and on emissions; with a flag when values were restated by a method change of the publisherthe status rows of calc.emission_day and calc.emission_month, factor history
Q05 Anomalies (phase 2)The parameterised rule of R3 §5: a robust band around the median of the same weekday and clock hour over the previous 8 weeks, flat lines, zero runs, base-load steps; each anomaly has a status (open, explained, data error)ts.reading, agg.mp_day
Q06 Restatement§5.8; the percentage is of the locked value and is "n/a" when that is zerorpt.locked_fact

A ratio without a denominator is "n/a"; a measure without its input is "unavailable"; neither is shown as zero (R3 §3.3.4 rule 4). These are product controls that support the disclosure of estimation under ESRS 2 GDR-M 49(a) and an assurance engagement; no rule prescribes them in this form (R3 §5, priority C).


6. Serving

6.1 The contract

**Decision: named, parameterised SQL queries with a YAML catalogue, served by POST /api/query/{id}, as S&OP (S&OP ADR-008); the runner and catalogue code are copied from an earlier internal project/services/api/src/sop_api/analytics/ (D10).** Reason: explicit grain and method per visual, one place to review every number's SQL, a contract the web app, the CSV export and the tests share. Rejected: a generic "cube" endpoint with free dimensions (every combination would have to be made safe and fast); GraphQL (the same, with more machinery).

Each page directory has its own catalogue file and queries, merged at build (§1.4). A page contains no SQL and no arithmetic beyond formatting: every figure, variance and ratio is a column of a query (R4 §3.7). A catalogue entry declares parameters with types and ranges, the columns with unit and polarity, the permission, and the combinations that return "unavailable" with a reason. Parameters are bound by the driver. Unlike S&OP there is one audience (§1.2).

Common parameters: p (period: explicit range, or a preset resolved against the frontier), n (node IDs), t (dimension members), mp (MP IDs), m (method, §5.2), gwp, basis (data basis, §5.7), cmp (comparison: previous year, previous period, target, budget, forecast, none), g (grain), w (boundary approach: physical, financial control, operational control, equity share, ESRS reporting boundary; default physical on operational pages, the ESRS reporting boundary on ESG pages).

6.2 The response

Shape, with illustrative values:

{ "queryId": "consumption.development", "columns": [{"name": "kwh", "type": "number", "unit": "kWh", "polarity": -1}],
  "rows": [], "grain": "day", "state": "ok",
  "method": {"family": "LB", "mixed": false, "parts": [{"code": "LB-PA-125", "kwhShare": 1.0}], "gwp": "AR5", "co2eBasis": "gases", "dataBasis": "best"},
  "basis": {"dataThrough": "2026-11-12", "coverage": 0.998,
            "factorStatus": {"final": 0.0, "preliminary": 0.71, "initial": 0.21, "pending": 0.08, "substitute": 0.0},
            "boundary": "physical", "locked": null},
  "scale": {"kwh": {"max": 1234.5}}, "dataVersion": 4711, "configVersion": 17, "calcVersion": "1.0.0", "truncated": false }

state is ok, empty, unavailable (with a reason: no price area, method unavailable, no factor set, feature not configured), too_large_for_grain, or preparing (an aggregate is being rebuilt). An unavailable figure is never a zero (R4 design item 14). scale gives the maximum of each unit over the whole result, so that paged tables, small multiples and print share one scale (R4 §4.6, §4.11).

6.3 The aggregation rule

**Decision: the server chooses the grain; no series leaves the API with more than 750 points, no bar chart with more than 150 rows, no small-multiple page with more than 25 panels** (the budgets R4 §6.3 derives from its measurements: layout is linear up to about 750 points and 1.5 seconds at 8 760).

RuleDetail
g=autoThe finest grain whose point count is at most 750 and whose scan stays inside the row budget of §2.8: quarter-hours up to 7 days (672 points), hours up to 31 days (744), days up to 750 days, weeks up to 14 years, months beyond. For 5 000 MPs the row budget allows day grain up to 400 days; a longer window falls to months
An explicit finer grainAllowed up to the budget; beyond it HTTP 422 grain_too_fine with the longest window that grain allows
Aggregated rowsCarry kwh, min_kw, max_kw, max_kw_at and the number of intervals, so that a peak is not averaged away (R4 design item 7)
The grain is statedIn the response and in the third title line of the chart
Structure chartsThe query returns the top N (default 25, at most 150) and one remainder row computed by the server; the full list is the paged table (page size 100, server-side sort and filter)
Small multiplesUp to 25 panels per page plus an "others" panel; the shared scale maximum comes from the response
Heat mapDay × clock hour for at most 366 days: up to 9 150 cells in compact arrays, drawn on a canvas (R4 §4.3: canvas above about 2 000 cells) with a hidden data table summarised by day
Load duration curveSorted on the server; 200 quantile points and the labelled points (minimum, base load, P95, P99, maximum)
TablesVirtualised in the browser, paged by the server

6.4 Performance budgets and caching

Budgets, to be confirmed or revised by B22 at design scale (the first is S&OP's): a named query answers within 500 ms at the 95th percentile with 10 concurrent users; the daily run's recomputation for 5 000 MPs finishes within 15 minutes; a full-year factor restatement within 60 minutes.

LayerDesign
Pre-aggregatesThe main cache (§2.8)
Result cacheIn the API process: least-recently-used, keyed by query ID, parameter hash, ops.data_version, ops.config_version and the user's access-scope hash, so that neither recomputed facts nor an edited setting (a default method, a weight, an allocation) leaves a stale answer (A1x-11)
HTTPETag from the same key; the browser's query cache (TanStack Query) revalidates with it
Not usedA separate cache server: one more service for data that changes once a day

6.5 Export

ExportDesign
CSVThe same named query with ?format=csv: same parameters, permissions and method label; refused if the data version changed between the page and the export (S&OP review N-06). Danish convention by default (semicolon, decimal comma, UTF-8 with byte-order mark), locale=iso for machines. Every file starts with comment rows: method, GWP set, boundary, period, data-through date, factor status, source line
Excel.xlsx written by openpyxl; up to 100 000 rows in the request, larger ones as a worker job with a download link. One sheet of data, one sheet "Metode" with the same header information as CSV
Interval dataReadings of selected MPs for a period, with quality and change flags, as CSV; always a worker job
Report for an auditorA ZIP for one report edition, built by the worker when the lock is taken and stored (rpt.lock_package), so that a later download returns the same bytes even after factors were restated or interval data dropped: report.xlsx (Scope 2 LB and MB, energy quantities and mix, losses, biogenic memo, with comparatives), method.html (printable: methods, factor sources and versions, GWP set, allocation percentage, boundary approach, estimation and completeness, restatements), metering_points.csv (boundary list with weights, classes and validity), factors.csv (the consumption-weighted factors of rpt.lock_factor_month with versions and retrieval times) and factors_hourly.csv (the hourly rows of rpt.lock_input), recipe.json, quality.csv (Q01–Q04 per MP), claims.csv (claims, eligibility decisions, how each was applied per leaf) and the evidence documents, changes_since_lock.csv, manifest.json (hashes of all files, lock, data version, calculation version). It answers the questions of R3 §6 one file each

**Decision: the auditor's report is a package of open files, with a printable HTML summary, not a server-rendered PDF.** Reason: an auditor recomputes from tables; a PDF engine is a heavy dependency for a cover sheet. Rejected: headless browser rendering in a container.


7. The web app

One single-page app, web/apps/elo-web: React, TypeScript, Vite, React Router, TanStack Query, plain CSS from the three packages, static build served by Caddy (as S&OP "Front end"). The visual design, the notation manual, the scenario codes and the polarity table are task A2 (D6–D8); this section fixes what each page answers and which data it needs.

7.1 Pages on three levels

Measure IDs, formulas and units are those of the corrected KPI catalogue in R3 §5 (with its recipes in R3 §3.3); facts are stored in base units (§2.7) and converted in the queries. Every page has the common filters of §6.1 (period, selection, comparison); "method" means the switch of §5.2. Phase 1 builds one page of each level (the lead's ruling); the rest follows in the phase that has its data.

PageLevelThe question it answersMeasuresPage-specific filtersDrill pathsPhase
X1 Overblik (overview)ExecutiveDo we use and emit less than last year, and can the figures be trusted? Later also: do we pay less, and are we on target?Phase 1: E01 with variance to previous year; G01 by the method switch; Q01b coverage and Q04 factor status as caveats; consumption by month; the MPs with the largest variance. Phase 2: M12, M13, E11a, ranking by site. Phase 3: variance to targetmethodCard → the analysis page of that measure; row → A1 for that selection; caveat → D1 (phase 1), A7 (phase 2)1, extended in 2 and 3
A1 Forbrug (consumption development)AnalysisWhen did consumption change, and against what?E01 by month or day with previous year and variances; phase 2: small multiples per site on one scale, the change by site as a variance waterfall, E03 and E05 where production exists, M02 where area is known; phase 3: targetgrainPeriod → D1 (phase 1), D2 (phase 2); site → A21, extended in 2
D1 Målepunkt (metering point)DetailEverything about one MPMaster data and its versions; the tree with each child's role; the series by hour or quarter-hour with quality; emissions per interval for the chosen method with the factor, its version and retrieval time; changes to values; ingestion state of the MP (first day, latest day with data, open chunks). Phase 2: charges and cost per interval, allocation, tags; phase 3: boundaryseries of the tree; windowInterval → D2 (phase 2); factor → D4 (phase 2)1, extended in 2 and 3
A2 Steder og målepunkter (structure)AnalysisWhich sites and MPs drive consumption and its change?E01, absolute and relative variance, share of total; M02, M03, M04, G12, G13a, G13b where the denominators are entered; ranked bars with remainder; full table with in-cell barslevel (entity, site, MP); sort measureRow → D1 (MP) or A1 (site)2
A3 Belastning (load profile)AnalysisWhen is power used: base load, peaks, nights and weekends?Heat map day × hour (D6); M10 day-type profile; M08 load duration curve; M05 base load; M06 peak and its time; M07 load factor; M09 share outside working hoursone MP, a site, or a selection within the row budget (§2.8); large nodes from node-hoursCell or peak → D22
A4 Udledning (emissions)AnalysisHow much do we emit by the chosen method, why does it move, and what would another method say?G01 over time with variances; the change split into a consumption effect and an intensity effect (§7.2); G16 own intensity against the grid's; consumption, intensity and emissions as aligned tiers; E07, E09, E10, E11a, E11b and the source and origin split; G03 by gas; G10 by price area and municipality; G05 and G04a, G04b as separate lines; the method comparison view (§5.2); Q04. Phase 3: G02 beside G01method; GWP set; data basisPeriod → D2; method → D42
A5 Omkostning (cost)AnalysisWhat does electricity cost, by component, and where is it expensive?M12 stacked components over time; the change split into a volume effect and a price effect; M13; M14 price capture against the spot benchmark; share of consumption in the tariff peak positions; by site; cost by status (computed, estimate, incomplete, bill-reconciled)components; with or without VATSite → D1; period → D22
A6 Egenproduktion (production and export)AnalysisWhat do our plants produce, what is exported, what do we use ourselves? Shown only if a production or export series existsE04, E03; E02 by production type and attribute status and E05 where they can be computed (§5.4), "unavailable" otherwise–MP → D12 (E02 through production links: 3)
A7 Datakvalitet (data quality)AnalysisWhich figures rest on incomplete, estimated or changed data, and where does consumption look wrong?Q01a, Q01b, Q02a–Q02c, Q03 per site and MP; gaps on a timeline; day × MP state matrix; values changed since a date; Q05 anomalies with their statusquality state; changed sinceMP → D1; gap → D32
D2 Døgn og time (day and hour)DetailWhat happened in this day or week, hour by hour?Consumption per interval; emission intensity; spot price; the three as aligned tiers; a table of intervals with quality, factor version and costselection; day or weekMP → D12
D3 Datastatus (data status)DetailIs the data arriving?Accounts and token expiry; runs and their outcomes; per MP: windows, latest day with data, chunks by state, unresolved items; unlinked MPs; unsupported units; unknown fields seen; datasets: latest hour, pending hours, notices and news; API health. In phase 1 the same facts come from make status and from D1–MP → D12
D4 Metoder og faktorer (methods and factors)DetailHow is a figure calculated, and with which factors?The method catalogue with status and version; factors by hour, area and version with history; yearly factor sets with published CO2e; GWP sets; the reconciliation with Eloverblik's report (E11c and the footprint blocks of §5.9); "how to read" per methodmethod; area; period–2
X2 ESG-statusExecutiveWhere do we stand on the reporting year: Scope 2 by both methods, losses, coverage by claims, progress to target, what is still preliminary, what is locked?G01, G02 side by side; G05; G04a and G04b (memo); G07; G14; G15; Q04; lock state per periodreport or year; boundary approachFigure → R1; coverage → R3; lock → R13
R1 Rapporter (reports and locks)Detail (ESG)What have we reported, on which basis, and what has changed since?Report editions with Scope 2 LB and MB, G03, G11, energy quantities and mix, intensities G12–G13b, comparatives; G06 shown as unavailable with its reason; locks; Q06 restatement with causes; approvalreportFigure → A4 with the report's settings, as of the lock; export → the stored auditor's package3
R2 Afgrænsning (boundary)Detail (ESG)Which MPs count, with which weight, since when?MPs with entity, site, lease status, weights per approach, validity; unplaced and excluded MPs; G11 splitapproach; dateMP → D13
R3 Kontrakter (claims)Detail (ESG)Which contractual instruments back the market-based figure?G08 register with eligibility; G07 coverage; G07S surplus; how each claim was applied; evidence documentsyear; approach–3
Administration–Phase 2: users and grants; source accounts and tokens; hierarchy, allocations and tags; method defaults; factor years; contracts; settings; jobs. Phase 3: boundary, production links, targets, audit log–––2, 3

7.2 Rules common to all pages

RuleSource
Every page states its purpose and key message, has three descriptive title lines (who and filters; measure, unit, method; period, grain, comparison), footnotes with source, data-through date and factor statusR4 design item 11; PageFrame
Consumption, cost, emissions and intensities have polarity −1; production, renewable share and completeness +1; prices 0. The table is finalised in A2 (D8); the API sends polarity per columnR4 §1.5
An unavailable figure says so with its reason; a relative variance with a reference ≤ 0 is "N/A"; estimated readings and preliminary factors are marked; nothing missing is drawn as zeroR4 design item 14
No page labels an organisation or site "CO2-neutral" or "100 % green"; a renewable claim is shown with its evidence (claim, MWh, period) and beside the location-based figureR3 design item 14; this is a product rule, the legal reach is narrower (R3v-20)
Every page that shows Energi Data Service data carries the source lineR2 §1.9
G01 and G02 are labelled "Scope 2, el" (electricity only): the organisation's Scope 2 also contains purchased heat, steam and cooling (G19, G20), which Eloverblik does not have and which arrive only with the manual inputs of phase 4R3 §5, G20
A report edition shows, per figure, whether its framework requires it: the catalogue's applicability predicates are answered once in the report's settings; outside a report no figure is called "required"R3 §5, R3v-12, R3v-13
Ratios over a period or a selection are Σ numerator ÷ Σ denominator, computed in the query, never a mean of ratiosR3 §3.3.4 rule 2
"Why did it change" is answered with a decomposition, drawn as a variance waterfall (a component that exists, R4 §4.7). Emissions: change = (C₁ − C₀) × i₀ + C₁ × (i₁ − i₀), a consumption effect and an intensity effect, with i = emissions ÷ consumption in one method. Cost: (C₁ − C₀) × p₀ + C₁ × (p₁ − p₀) for the per-kWh components, plus the change in fixed charges. Consumption: the change by site. The terms add up to the variance exactly; they are query columns, not page arithmeticA1v-16
The executive pages have a print stylesheet (one page, A4 landscape, the same notation); nothing is rendered on the serverA1v-16
URL state holds every filter, including method, GWP set and data basis, so a link reproduces the viewD11; state.ts

Monitoring (phase 2, A1v-16). The owner's first verb is "monitor"; a product that shows a problem only to someone who looks does not do that. Two things are built: the anomaly measure Q05 with its parameterised rule (R3 §5: robust band around the same weekday and clock hour over the previous 8 weeks, flat lines, zero runs, base-load steps; each anomaly kept with a status), shown on A7; and one outbound channel, e-mail through the organisation's own SMTP server, for three events: a token within 60, 30, 14 or 7 days of expiry or invalid; no successful daily run for 48 hours; new open anomalies, as one daily digest. A message contains counts and links, never a GSRN, an address or a quantity.

7.3 What the architecture needs from the design task (A2), and where the flair is built

The design direction and the notation manual are task A2, a separate task with its own brief, done before the first page is built (the lead's ruling, A1v-09). The architecture adds no visual constraint; it needs these outputs, and the plan has epics that apply them:

Output of A2Used by
The notation manual: comparison codes and labels (previous year, previous period, baseline year, target, budget, forecast), polarity per measure, quality-state notation, the heat map and load duration rules (D6, D8), Danish number and date formats (D4)B14 (comparison labels), B16, every page epic; B37 for the heat map
The design direction: typography (fonts with their licences), layout and density, card style (R4 design item 13), pictograms for node typesB13 (fonts in the notice inventory), B17
Composition of the three phase 1 pages (X1, A1, D1) at 390 and 1280 px, and of X2 and one further analysis pageB16, B17; later B40, B41, B56
A motion specification: which transitions carry meaning (a variance forming, a drill-down unfolding on one scale), their durations, and the reduced-motion fallbackB17, B45, B60
A checklist a page is accepted against, including accessibilityThe design application epics B17, B45, B60

The flair is built in the design application epics, one per phase (B17, B45, B60): the pages of that phase are brought to A2's composition, typography and motion, on the strongest model, reviewed by the lead and shown to the owner at 390 and 1280 px. Their acceptance is A2's checklist, an automated accessibility check (axe) without serious findings, and the owner's view.

7.4 Where every catalogue measure is shown

MeasuresShown onPhase
E01X1, A1, A2, D1, every export1
E02, E03, E04, E05A6; E03 and E05 also on A12 (E02, E05: 3 where a production link is needed)
E07, E09, E10, E11a, E11bA4; E11a also on X1; all in R12
E11cD4, the reconciliation with Eloverblik's report2
E06 family, E12Not built: other carriers are phase 4; E12 has no obtainable definition (R3 §5)4 / unavailable
G01X1, A4, D1, D2, X2, R11
G02, G07, G07S, G08X2, A4 (beside G01), R1, R33
G03, G10A4 (by gas; by price area and municipality), R12
G04a, G04b, G05, G16A4; G04, G05 also on X2 and R12 (price-area values from phase 1 in D1 and the footprint query)
G06a, G06b, G06TR1, as "unavailable" with the reasonunavailable
G11R1, R23
G12, G13a, G13b, M02, M03, M04A2, where the denominators are entered (org.node_attribute); G12–G13b also in R12
G14, G15X2, X13
G08R, G09, G17–G20, M01, M11, M15a–cNot built before phase 4 (their gates are in §10.4)4
M05–M10A32
M12, M13, M14A5; M12, M13 also on X12
Q01a, Q01b, Q02a–Q02c, Q03, Q05A7; Q01b as the caveat of X1 and A1 from phase 12 (Q01b: 1)
Q04X1, A4, D1; X21
Q06R13

7.5 What is copied, under which names, and what is new

Every copy records the upstream repository and commit in a VENDORED.md beside it and a row in THIRD_PARTY.md (D10, docs/legal/REUSE-GRANT.md).

Copied from an earlier internal projectCommit (R4 §3.2)Name hereChanged on arrival
web/packages/…-chartsddceb13web/packages/charts, @elo/charts, Apache-2.0Identifiers and prefixes renamed (below). Functionally unchanged; its 634 test cases must pass after the rename
web/packages/…-tokens74da52aweb/packages/notation-tokens, @elo/notation-tokens, CC BY-SA 4.0Token file notation-tokens.json; provenance key renamed; themes renamed. The LICENSE, the attribution to the [standard] Association and the statement of adaptation stay, in the package and in every generated file, as the licence requires (D5's one exception). The sentence claiming that the tokens follow the standard is removed from the generated header: D5 allows no claim of conformance
web/packages/app-shellfc333c0web/packages/shell, @elo/shell, Apache-2.0Kept: layout, URL state, PageFrame, visual states, cards, named-query hook, auth seam, "how to read". Replaced: period model, entity model, comparison model, S&OP vocabulary (below)
web/tools/guard.mjs, the Vite notice pluginec82e50web/tools/guard.mjs, web/apps/elo-web/vite-plugins/Guard rules below
services/api: auth, sessions, CSRF, security context, migration runner, analytics runner and catalogueHEAD e0f85ccelo_api.auth, .security, .db, .analyticsAudiences removed; method and basis added to the response
services/worker: job queueHEADelo_worker.jobs–
tools: licence, notice and distribution-notice checks, test database fixtureHEADelo_devtoolsPolicy and inventory rewritten for this repository
deploy/, Makefile, licence-policy.toml, notice-inventory.toml, CI workflowHEADsame pathsWarehouse targets removed
RenamedFromTo
Components and hooks…Table, …ThemeProvider, use…Theme, [standard].tsAnalyticalTable, ThemeProvider, useTheme, notation.ts
CSS class and variable prefixes; theme attribute…-, --…-, data-…-themean-, --an-, data-theme
Theme IDs…-light, …-classic-light, …-darkanalytical-light, analytical-classic, analytical-dark
Token provenance key$extensions.…$extensions.provenance

The rename is one scripted, repeatable transformation (kept in tools/), so a later upstream change can be re-imported and renamed again. The naming guard (make guard) fails the build when the string "[standard]" occurs in web/, services/, libs/, tools/, deploy/, fixtures/, README.md, or the product documentation under docs/design/, docs/runbooks/ and docs/guide/ (A1v-18), except in the token package's LICENSE, the legal comment of generated token files and built bundles, the token file's description, THIRD_PARTY.md and VENDORED.md files. The project's own records (docs/brief, docs/research, docs/sources, docs/architecture, docs/adr, docs/legal, reviews/, orchestration/) are not product and are not guarded.

Built new or extendedWhy (R4 §4)Phase
Period model: days, hours, rolling windows, presets resolved against the frontier (§4)The shell knows only closed months1
Entity picker: tree with search over thousands of MPs, multi-select, deep link to an MP; tag filterThe shell has one company <select>2 (phase 1: a plain list of the account's MPs)
Method switch and GWP selector; comparison model with labels supplied by A2D11; the closed scenario union of the chart package1
Danish number and date formatting as the single module (D4); all UI text in one strings.tsD41
Grains hour and quarterHour; energy unit scaling from a kWh baseTokens and chooseScaling stop at day and at the SI prefix of the given unit2
Dense line chart: one path per series, no markers except labelled points, a time-based x scale so 23- and 25-hour days and gaps are trueOne DOM element per point today2
Heat map on canvas with the paired day totals and hour profile (D6)Does not exist2
Load duration curveExtension of the line chart with a rank axis2
Stacked bars over structure; aligned tier stack (consumption, intensity, price)Cost components by site; two measures on one time axis2
Day × MP quality matrix; gap timeline pagingData quality page2
Virtualised table body; paged small multiples with a server-supplied scaleHundreds of rows and panels2

Not taken: the upstream showcase kit (D7: one style, no separate variant), brand themes, anything under the MIT notice of Microsoft Corporation (docs/legal/REUSE-GRANT.md point 4), the S&OP warehouse and planning modules.


8. Security and privacy

8.1 Token storage

From phase 2 (B24). In phase 1 the token is in the owner's environment only (§1.5).

**Decision: a refresh token is stored as a sealed box (X25519 public-key encryption, libsodium through pynacl). The API holds only the public key: it can store a token and can never read one back. The private key is a Docker secret mounted only into the worker.** Reason: a token is a one-year credential to an organisation's metering data and carries personal data in clear (L1); the API is the component exposed to users, and with this split a compromised API process or a SQL mistake in a query cannot yield a stored token. (A compromised API can still see a token at the moment it is submitted; the guarantee is about what is stored.) Rejected: symmetric encryption with a key in the API's environment (the exposed process could decrypt); an external vault service (one more service for one secret per install).

AspectDesign
EntryAn administrator pastes the token once in the administration page (or make token-import reads it from the environment, D2). The API checks in memory that it is a JWT whose tokenType is a Customer API refresh token, reads exp, seals it, stores ciphertext, expiry and type. No other claim is stored; the value is never echoed, logged or returned
Database rightselo_api has INSERT and UPDATE on ingest.credential and no SELECT on the ciphertext column; elo_worker has SELECT. ingest.access_token is worker-only
UseThe worker unseals in memory when it needs a data access token; the data access token (24 hours) is sealed and persisted so restarts do not call /token
Replacement and expiryReplacing a token is an audited action; the old ciphertext is overwritten. Warnings 60, 30, 14 and 7 days before expiry, on the data status page and to administrators at login. Tokens cannot be renewed by API (R1 §2.1)
Key rotationkey_id on each row; a runbook re-seals with a new key pair
BackupsContain only ciphertext; the private key is backed up separately by the operator (runbook)
Repository.gitignore excludes .env*, secrets/, data/; the guard rejects JWT-shaped strings and GSRNs outside the anonymised 579999… range in tracked files

8.2 Authentication and roles

Authentication is S&OP's (S&OP ADR-010): OIDC authorisation-code flow with PKCE against Keycloak (which can federate the organisation's own provider), server-side sessions, an HttpOnly cookie, a CSRF header on state-changing requests, users identified by (issuer, subject), first login only under an invitation, no authorisation data in tokens.

RoleMay
viewerExecutive and analysis pages for the granted nodes. No MP addresses, no interval export
analystAlso detail pages, MP master data, all exports
stewardAlso edit hierarchy, allocations, tags, attributes, method defaults, boundary weights and status, production links, targets, contracts, claims, yearly factor sets; link unlinked MPs
reporterCreate report editions, lock periods, approve, restate
auditorRead-only access to everything in scope, the audit log and the auditor's package; a grant with an end date
adminUsers, invitations, grants, source accounts and tokens, settings, jobs. No access to figures by this role alone

A grant is (user, role, node or the whole organisation, validity); a node grant covers everything beneath it. Phase 1 has one implicit user; phase 2 builds admin, analyst and viewer, and admin does the stewardship of that phase; steward, reporter and auditor arrive in phase 3 with the tables they guard (A1v-15).

8.3 Row-level security

As S&OP ADR-011: elo_owner owns the schemas and runs migrations; elo_api is not an owner, not a superuser, NOBYPASSRLS; elo_worker writes the data schemas; every API transaction sets app.user_id; restricted tables have forced row-level security.

TablesMechanism
MP-level facts and aggregates (agg.mp_*, calc.*, core.*, price.charge_link, org.mp_*)Policy sec.has_org_wide_read() OR mp_id IN (SELECT mp_id FROM auth.user_mp WHERE user_id = sec.current_user_id()): an uncorrelated subquery that the planner can hash once per statement
Node-level aggregates (agg.node_hour), org.nodeThe same with the user's granted subtree
ts.reading, ts.reading_changeNo direct access for elo_api. Read only through sec functions that take the MP set and time range, check the set against auth.user_mp once, and then scan. Reason: every query on the largest table names its MPs, so one check per call replaces a policy evaluated per row
raw.*, ingest.credential, ingest.access_tokenNo access for elo_api (evidence payloads reach an auditor through a checked function)
Configuration (org, mb, plan, rpt)Write policies by role and node

The guarantee covers mistakes in API queries and direct calls by a restricted user, not a compromised API process (S&OP "Scope of the guarantee"). CI runs, as elo_api: a user granted site A cannot read, export or drill into site B through any query; no app.user_id returns nothing; a revoked grant takes effect at once; a moved MP follows its new node; totals for a restricted user equal the sums of the MPs they may see; the readings function refuses an MP outside the grant; the credential column cannot be selected. Whether the policy form meets the latency budget is part of B22. Policies exist from phase 2 (B26); phase 1 has one user and none.

8.4 Personal data: one storage policy, applied before anything is written

Each deploying organisation is the controller of its own install; the product is not a party (R1 §12), and docs/runbooks/ carries a short template in which an installing organisation records the controller, the purpose and the retention it has chosen (R1 design item 15). A business's meters are mostly not personal data, but names, contact details and the consumption of a private person's MP are.

**Decision: master data and list responses pass an allowlist before they are hashed, stored, logged or exported: only the fields the table below names are kept; everything else is discarded, and only the name of an unknown field is recorded.** Reason: a deny-list keeps whatever Energinet adds next, and an "extras" column keeps it for good; a future billingContactEmail must not land in the database and its backups (A1x-06). Rejected: keeping unknown fields in a JSON column, as version 1 had it.

DataTreatment
contactAddresses[] (names, phone, mobile, e-mail, attention, address), secondConsumerPartyNameNever stored, in getdetails and in the list response alike
firstConsumerPartyNameStored as consumer_name only when a steward has classified the account as a company (ingest.source_account.party_kind = 1) and protectedName is not true. A CVR number alone does not make a name non-personal (sole proprietorships). Not stored otherwise; visible to analyst and above
Location address (street, building, floor, room, postcode, city), darReference, locationDescriptionStored, because they identify a site; visible to analyst and above; viewer sees node names only. When protectedAddress or protectedName is true, street, building, floor, room, DAR reference and location description are not stored; municipality, postcode and grid area, which the calculation and the price area need, are kept (R1 design item 15, A1v-11)
meterNumberStored; visible to analyst and above
GSRNStored in core.metering_point only; no other table, log line, request record or audit event contains it; shown to analyst and above
consumerCVR, dataAccessCVR, supplier, grid company, type and status codes, capacity, grid area, municipalityStored
Any field the allowlist does not nameDiscarded. Its JSON path (not its value) is counted in ingest.unknown_field and shown on the data status page, so that a maintainer classifies it and extends the allowlist or the discard list in a migration
Upstream error texts and stack tracesNever stored. The documented error code is stored; the text a page shows comes from the product's own code list. A text that is not the documented name of its code only sets a flag
JWT claimsOnly exp and tokenType are read; nothing else is stored or logged
A private person's account (party_kind = 2, or not yet classified)The install shows that it processes personal data and requires a retention period to be set (§8.5)
App usersName, e-mail, issuer and subject; pseudonymised when a user is removed, audit events keep the user ID (as S&OP "GDPR notes")

Test (B04 on the models, B07 through ingestion, B44 after a removal): responses are fed through ingestion in which sentinel values sit in every contact field, in the list response's name fields, in a nested unknown field, in an error text and in a stack trace; afterwards no sentinel occurs in any database column, in the captured logs or in any export.

8.5 Retention and removal

No source in the research imposes a retention period on a token user (R1 §12); storage limitation under the GDPR applies to personal data. Defaults, all configuration:

DataDefault
Readings and their change logKept while the MP is in the organisation; optional limit retention.interval_years, enforced by dropping whole month partitions; mandatory for private accounts. Dropping interval data ends the hour-level drill-down and the as-of reconstruction for those periods; the month level stays reproducible from the lock (§5.8); the page that sets the limit says so
Payload bodies90 days
Request and item records§2.2
Locks: facts, recipe, input rows, packageLife of the deployment
Audit eventsLife of the deployment
Logs90 days; sessions 30 days (as S&OP)
Export files7 days, or until downloaded once

Removing an MP on request is one job with a defined closure (A1v-11, A1x-05). It deletes: the MP's rows in ts.reading, ts.reading_period, ts.day_load, ts.reading_change, agg.*, calc.* (facts, dirty rows, leaf facts), core.mp_version, core.mp_geo, core.mp_access, ingest.chunk, ingest.mp_state, ingest.control_total, price.charge_link, org.mp_*, raw.payload bodies and raw.fetch_item rows that refer to it, and every export file that contains it. It then replaces the GSRN in core.metering_point by a random key and clears parent links, so that what must stay (the MP's rows in locked facts, raw.fetch records, audit events, which hold only the internal ID) no longer identifies anyone. What stays, and why, is stated to the person who runs the job: reported month figures, because a published total must remain reproducible. The job writes a removal record (internal ID, time, operator). Backups: a removed MP remains in backups until they expire (30 days by default, §8.6); a restore replays every removal record newer than the backup before the install is opened again. Test (B44): after the job, a search for the GSRN, the address and the sentinel values over every table and the exports volume finds nothing.

8.6 Logging, exports, backups, transport

RuleDetail
Never loggedAuthorization headers, tokens, decoded claims, request and response bodies, GSRNs, names, addresses, quantities, upstream error texts. Log calls take structured fields from an allowlist (IDs, codes, counts, durations); free text from outside the product is not a field. A test runs the suite and scans the captured logs for eyJ, for 18-digit numbers beginning with 57 and for the sentinel values of §8.4 (R1 §11: a token was once pasted into a public issue log)
LoggedRequest ID, user ID, query ID, mp_id, job and run IDs, both correlation IDs of each Eloverblik call (support asks for them, R1 §2.3), outcome codes, durations
Export filesWritten with random names to the exports volume; served only through the API after the same grant check as the query that produced them, to the user who requested them; deleted after the first download or after 7 days, and at once when an MP in them is removed (A1v-11)
OutboundOnly the worker has internet access; a generic user agent; no telemetry; fonts and scripts self-hosted (as S&OP). Notifications go to the organisation's own mail server and contain no personal data (§7.2)
Backups, phase 1Nightly pg_dump to a local directory: one MP tree on the owner's machine, megabytes
Backups, from phase 2Decision: base backups with continuous archiving of the write-ahead log, by pgBackRest (MIT; the option S&OP's architecture names for later), encrypted, to an off-host repository: a weekly full and a daily incremental backup, 30 days of retention. Reason: at scenario A the database is about 35 GB and with children 150 GB or more, almost all of it in month partitions that did not change that day; a nightly compressed dump uploads all of it again, because compression defeats deduplication, whereas an incremental backup copies the changed files only (A1v-10). Rejected: pg_dump per changed partition (the tracking is the product's to write and to get wrong). B22 measures backup and restore time at scale and confirms the choice; B44's restore test uses scenario A, not the demo organisation
What a restore cannot bring back by re-fetchingReadings older than the API's "5 years + current year" window, the change log, the locks, the configuration and the claims: they exist only in the backup. Readings inside the window can be fetched again
TransportOnly Caddy is published; TLS by Caddy in production; development and phase 1 bind to loopback (as S&OP)

8.7 Generated data for the demo and for the tests

Decision: the demo dataset and the contract fixtures are generated, never anonymised. They come from the synthetic generator of §9.2 with a fixed seed: a fictitious organisation, GSRNs in the 579999… range, invented addresses, load shapes from parametric models, payloads of exactly the shapes the live API returned. The demo is joined to real public factors and prices (CC BY 4.0, attributed), of which a small frozen extract is committed for offline tests. Reason: a real load profile multiplied by a factor is still someone's profile. The samples under docs/sources/eloverblik/samples/ are exactly that: the owner's own metering point with every quantity scaled, its daily shape, its solar export and its grid company's real prices intact (A1v-08). Version 1 rested its contract tests on them, against its own rule. In version 2 the committed contract fixtures are generated (fixtures/contract/), with the saved samples as the specification of their shape; the real samples are used only as a local comparison (the generated fixtures must have the same structure, keys and types), and whether they stay in the repository when it becomes public is the owner's decision (§11). Rejected: scaling or shuffling the owner's data.

The public demo is a static build of the web app against a fixture API (S&OP "Demo build"), with a banner that the data are generated (phase 3).


9. Quality

9.1 Test strategy

LayerWhatWhere
UnitTime rules (local day bounds, expected minutes, tariff position, frontier), parsing, limiter and retry state machines under a simulated clock, catalogue validation, formattinglibs/*/tests, services/*/tests, Vitest in web/
ContractThe generated fixtures in fixtures/contract/ (§8.7) parse into the typed models and round-trip; they have the shapes of the saved samples, which are compared with them locally and are not an input of CI; assertions on what L1 observed: 23 and 25 hourly points, 92 and 100 quarter-hour points, mixed resolutions in one response, string-typed scalars, "" and null, 1 and 24 tariff positions. The same for the Energi Data Service samples: 3 allocation rows per hour and area, the repeated local hour, null exchange columnstests/contract
DatabaseEvery migration applied to a throwaway PostgreSQL 18 (S&OP's deploy/testdb.sh); ingestion idempotency; change log; dirty-queue recomputation; partitionsservices/*/tests
CalculationGolden cases; SQL equals the Python reference; the footprint report query on the demo organisation; the market-based and cost cases, including both DST daystests/calc
SecurityThe denial and positive tests of §8.3 as elo_api; the log scan of §8.6; the sentinel test of §8.4; the removal closure of §8.5; the sealed storetests/security
ValidationThe owner's reports through the product's report query, on the lead's factor snapshot, local only (§5.9)tests/validation
ScaleThe scenarios and queries of §10.6 on generated data; not in the normal CI runtests/scale, spikes/scale
End to endPlaywright on the demo organisation through Caddy at 390 and 1280 px: sign in, overview, switch method, drill to an MP and to a DST day, export CSV; fails on console errors, horizontal overflow, a missing chart (S&OP's screenshot checks) and on a serious finding of the automated accessibility check (axe, R4 design item 15)web/apps/elo-web/e2e, tests/e2e

9.2 The generator of synthetic organisations

elo_devtools.synth takes a definition (legal entities, sites by archetype: office, school, shop, workshop, cold store, pumping station, charging site, building with solar; counts; a seed) and produces (a) a MeteringSource that answers with payloads of exactly the shapes of the saved samples, including a fault mode, and (b) a bulk path that writes readings directly for the scale test. It has a revision clock: the same request at a later simulated date can return different values. The core cases are built in B04, the others in B21. The awkward cases it must contain:

CaseDetail
Daylight savingThe 23-hour and the 25-hour day, hourly and quarter-hourly; a leap day; year and month boundaries at 22:00 and 23:00 UTC
GapsDays not yet delivered; A02 positions without a quantity; a chunk answered 30015; a whole month missing
QualityRuns of estimated values (A03), an incomplete aggregate (A05), an adjusted value (A01)
CorrectionsA value changed at a later revision; a day that arrives late; a correction that moves quantity between two hours without changing the month total; a monthly control total that changes; a correction that withdraws a position; a day delivered in quarter-hours and later as one hourly value; an older response delivered after a newer one; a day missing from one response and present in the next, and one missing from two
FrontierOne hour in one series that is never delivered; 1 % of the series seven days late
TreeA parent with a child identical to it (D07), a child with a daily amount in the first hour (D15), a quarter-hourly export child (D06), a site with production and export where self-consumption is computable (D05 + D06), a production MP (E18) with a confirmed link to a consumption root and one without, an electric-heating child (D14), a child of an unknown type
ResolutionA meter that changes from hourly to quarter-hourly on a date; a monthly-read MP (P1M)
AccessAn MP registered in the middle of the window (30018 for earlier chunks); an MP that disappears; one that appears later; one without a relation; the same ID in two access periods; an MP with data only in an earlier half-year; an access edge in the middle of a chunk
GeographyMPs in DK1 and DK2; municipality 330; a missing grid area; an unknown grid area code
ValuesA zero-consumption MP (relative variance not applicable); large industrial values; a series in MWH; a series in KWT
ChargesA 24-position tariff, a daily tariff, a monthly subscription with quantity 2, a price change inside a month, a future-dated link, a link that ends, two charges with the same code and different type; a charge per kW and month; a monthly fee
Master dataBooleans and numbers as strings, "" and null, null arrays, an undocumented field carrying a sentinel value, a protected name, a protected address, sentinel values in every contact field and in an error text
API faults429 with and without Retry-After; bursts of 503; a timeout; a 400 whose body is a string with #20013:; successes and failures in one 200; 401 after token expiry; an invalid refresh token

9.3 What CI runs (make check, as S&OP)

Lint and format (ruff, Biome); types (mypy strict, tsc); unit, contract, database, calculation and security tests on PostgreSQL 18; the naming and secret guard; the web build; licence allowlist for Python and JavaScript dependencies; notice inventory including the built bundle; Playwright on the demo data. The scale test and the validation against the owner's report run on demand.

9.4 Licence and notice inventory

ItemLicenceWhere recorded
New codeApache-2.0LICENSE, NOTICE
Material copied from an earlier internal project (§7.5)The owner's own, Apache-2.0 here (D10)THIRD_PARTY.md, a VENDORED.md per copy with the commit
Notation tokens and every generated file or bundle that contains themCC BY-SA 4.0, attribution to the [standard] Association, statement of adaptationPackage LICENSE; legal comment in generated files and at the top of every built JS and CSS file; dist/licenses/; notice-inventory.toml
Software dependenciesThe S&OP allowlist (licence-policy.toml: MIT, BSD-2/3-Clause, Apache-2.0, ISC, PostgreSQL, MPL-2.0, 0BSD, Zlib, Python-2.0, MIT-0); LGPL or AGPL needs an ADRlicence-policy.toml, checked for every locked package
Public data in fixtures/ (factor and price extracts)CC BY 4.0, "Kilde: Energinet (www.energidataservice.dk)", marked as extractsTHIRD_PARTY.md, a SOURCE.md beside the files
Documents under docs/sources/ (Energinet PDFs, portal texts, OpenAPI files, legal texts)Their publishers' terms; not part of the productListed in THIRD_PARTY.md; whether they may be redistributed in a public repository is open (§11)
Fonts, if A2 chooses anyOFL-1.1, self-hostedTHIRD_PARTY.md, licence file beside the fonts
Files under the MIT notice of Microsoft Corporation in the upstreamNot taken–

10. Delivery plan

Epics follow the naming of orchestration/WORKERS.md: task ID B<nn>, brief orchestration/tasks/b<nn>-<slug>.md, branch build/b<nn>-<slug> in the worktree ../eloverblik-wt/b<nn>-<slug>, review B<nn>v. Each epic is sized for one worker in one session; version 1's four oversized epics are split (A1v-02). "Agent" is the suggestion for the author; the review is by another model family (WORKERS.md): Codex · gpt-6.1-sol · xhigh where the row says "x" (ingestion limits, emission and cost arithmetic, secrets, access, locks), Codex · high otherwise, Agy · gemini-3.8-flash · medium for checklist-style checks.

Definition of done for every epic (as S&OP): reviewed; unit tests and the epic's acceptance tests pass in CI; migrations forward-only, inside the epic's reserved block of numbers, and applied in CI; the epic creates only the tables §10.5 assigns to it; new tables have their access rule (from phase 2: a policy and a denial test); copied files are in the notice inventory with a VENDORED.md; no token, real GSRN or metering data in the repository; behaviour documented under docs/; make demo works from a clean checkout.

The principle of the phases (the lead's ruling): phase 1 is the shortest honest path to the owner's own data in a browser, on three pages in the analytical style. Everything else waits for the phase that needs it, and the reason is given in §10.2–10.4. The data model of §2 is designed for the whole product, but a table is created by the epic that first writes it.

10.1 Phase 1 – The owner's own data in a browser

Phase 1 is specified in docs/architecture/phase-1.md, which replaces this section: scope, tables, the ingestion rules with their invariants and test tables, the calculation, the pages, security, the epics with acceptance criteria, sizes and dependencies, the waves and the exit. The epic numbers B01–B18 used elsewhere in this document refer to that specification; where an epic was split there (B04a/b, B06a/b, B08a/b, B12a/b, B16a/b) a reference to the old number means both parts. Phase 1 builds less than this document's sections 2 to 8 describe for it (no stored emission facts, aggregates or dirty queue, no calendar-resolution readings, no access-window table; phase-1.md §1.4), and it builds the dense time series chart (B18) that section 10.2 lists under B36.

10.2 Phase 2 – An organisation: many metering points, access, all location-based methods, cost, monitoring

EpicScopeAcceptance criteriaDepends onAgent · model · effortReview
B21 Generator IIThe remaining cases of §9.2: API faults, access windows, charges, geography, master data oddities; the bulk path for scaleEach case exists and is asserted; an organisation of 5 000 sites with a stated share of L1 trees and quarter-hourly series can be generatedB04Claude · Opus · highCodex high
B22 Scale gateThe scenarios, sizes and gate queries of §10.6 on the real tables of phase 1 and throwaway versions of what phase 2 addsReport docs/adr/ADR-001-storage-scale.md with every number of §10.6 and the decision: the design stands, or which remedy is taken (a changed row budget; a leaf × day aggregate; day-array readings; a columnar engine behind the query contract), and the backup choice of §8.6 confirmedB10, B12, B21Claude · Opus · highCodex high
B23 Identity and rolesKeycloak with a realm, login, sessions, CSRF, /api/me; roles admin, analyst, viewer; audit.eventA seeded user signs in; the session survives an API restart (make smoke); local single-user mode can no longer be combined with a non-loopback address; every write is audited without a GSRN, name or addressB02Claude · Sonnet · mediumCodex high
B24 Sealed credential store, several accounts§8.1; account page; make token-import; sealed access-token cache; classification of an account as company or privateelo_api can write and cannot select the ciphertext; without the private key nothing decrypts; a wrong token type is refused; replacement is audited; two accounts share one pace and one token-call spacingB23Claude · Opus · highCodex x
B25 Hierarchy, allocations, tagsorg.* tables of phase 2, closure, API and administration pages; trigger 7 with its debounce; ops.config_versionAn MP moved from A to B on the 16th is in A's and B's day, month, node-hour and export figures for its own days only, after a backdated edit as well (A1x-11); a cached answer does not survive a changed default; allocation shares above 1 are refused by the databaseB10, B23Claude · Sonnet · highCodex high
B26 Grants and row-level securityauth.role_grant, auth.user_mp, policies on every table that exists, checked functions for readingsEvery test of §8.3 passes as elo_api; an organisation-wide grant and a node grant can both be stored; the policy form meets the budget measured in B22B25, B22Claude · Opus · highCodex x
B27 Sweeps and access windowsTiered control sweep, coverage reconciliation, yearly re-fetch, window discovery with clampingA month whose first control differs from the stored sum is re-fetched; an unchanged control never confirms an incomplete month; a no_data chunk outside 14 days is retried by its schedule; a moved-out MP with data only in January–June gets those months although its newest chunk is refused; a mid-chunk edge is clamped and loadedB09, B21Claude · Opus · highCodex x
B28 A run against a business loginThe client and ingestion against a business token with many MPs, read-only, responses under data/. Run by the lead with the owner's company or a friendly organisationA report of what differs from L1: consumerCVR, includeAll under a CVR, the size of the list, MPs without children, quarter-settled consumption, tariff levels, the answer at access edges, latency and limits at volume. No statement about scale is made in the README or the documentation before this report exists (the lead's ruling, A1v-17)B08, B24Lead; Claude · Opus · high for changes it causesCodex high
B29 Mix and municipality loaders, news watchDeclarationTransmissionEmission, both mix datasets with history, ReCoverageMunicipality for the municipalities in use; /NewsLoaded from 2021 within the call counts of §3.8; a new municipality among the MPs triggers its backfill; the monthly re-pull replaces and logs changed and vanished rows; a changed news item is stored and shownB11Claude · Sonnet · mediumCodex high
B30 Municipality methods, mix, renewable quantityLB-MU-125, LB-MU-200, calc.mix_month, the three variants as parameters, input status per hourGolden case with 30 % local renewables; Σ of the source split equals the base quantity plus the local part in every month; an hour without a coverage row is pending, not 0 % local; hours without mix rows are outside the renewable share and its denominator; the R15x flag; an MP without a municipality falls back and is flagged; changing a variant recomputes and raises the versionB12, B29, B22Claude · Opus · highCodex x
B31 Validation of the municipality methodsThe check of §5.9 through the report queryRun on the lead's machine against the owner's reports and the snapshot; the outcome (the matching combination, or the residuals) is recorded in docs/adr/ADR-002-municipality-variant.md without any of the owner's figuresB30Claude · Opus · high; run by the leadCodex high
B32 Yearly factor sets and methodsfx.factor_year seeds with sources; steward page to add a year; LB-AN-125, LB-AN-200; published CO2e ruleSeeds equal the values of R2 §3.3 with their source rows; a prior-year substitute is flagged and recomputed when the year is entered; months of the running year are labelled provisional; the published CO2e is used and labelled as §5.5 saysB12, B22Claude · Sonnet · highCodex high
B33 Prices and charges ingestionSpot (both datasets), DatahubPricelist per charge in use over its whole history, getcharges snapshots; charge basis rules; weekly probe of the charge links endpointThe spot series is continuous across 30 September 2025 in UTC; a charge is keyed by owner, type and code; a price valid since before 2021 and still valid is present; a future-dated link is stored and not yet applied; a new charge owner triggers its own backfillB07, B11Claude · Sonnet · highCodex high
B34 CostComponents, bases and precedence of §5.6; tariff positions; statusGolden cases: a 24-position tariff on a normal, a 23-hour and a 25-hour day; tax on D15, grid tariff on D07, national tariffs on E17, reproducing the sample's rates; the monthly subscription 187 / 12 = 15.583333 DKK prorated by days; a charge per kW and month is incomplete without a capacity and 1 000 DKK with 100 kW at 10 DKK; 100 kWh at spot 1 and a fixed price of 2 is 200 DKK with a benchmark of 100; a snapshot price is not used for days before the snapshot; the position mapping is one function, checked against one real invoice by the leadB10, B33, B22Claude · Opus · highCodex x
B35 Node-hours and load measuresagg.node_hour for large nodes; M05–M10 as queries within the row budgetRoot values equal brute-force sums; peak and base load of a site come from the summed load; a free selection above the budget returns too_large_for_grain; during a hierarchy rebuild the answer is preparingB25, B22Claude · Opus · highCodex high
B36 Charts I: dense seriesDense line with a time scale; hour and quarterHour grains; energy unit scaling744 hourly points lay out within the budget of R4 §6.2 and render as one path per series; a 23-hour and a 25-hour day show true widths; role-based layout tests as in the packageB13Claude · Opus · highCodex high
B37 Charts II: heat map, load duration, quality matrixCanvas heat map with paired totals; load duration curve; day × MP matrix9 150 cells render and stay interactive in the browser test; the hidden table and keyboard access exist; notation follows A2's manual (D6)B36, A2Claude · Opus · highCodex high
B38 Charts III: stacked bars, tier stack, tables, multiplesStacked bars; aligned tiers; virtualised table body; paged small multiples with a server scale1 000 table rows scroll without layout shift; page 2 of the multiples uses the scale of page 1B13Claude · Sonnet · highAgy
B39 Shell IIEntity picker with search over thousands of MPs, multi-select, tags; comparison model with A2's labelsThe picker finds one MP among 5 000 by GSRN fragment, address or node; a selection round-trips through the URLB14, B25Claude · Sonnet · highAgy
B40 Pages A2, A3, A7, D2, D3Structure, load profile, data quality, day and hour, data statusThe checks of B16's kind; the remainder row and the scale come from the server; the heat map of the demo site shows its night base load and the DST days correctly; quality states and chunk states match the generator's casesB35, B37, B38, B39Claude · Sonnet · highAgy
B41 Pages A4, A5, A6, D4; X1 extendedEmissions with the method comparison view and the decompositions of §7.2; cost; production; methods and factorsThe mixed-method tests 1–7 of §5.2; no view sums or subtracts across methods; the terms of each decomposition add up to the variance; cost shows its status split and never adds the spot benchmark; D4 shows a factor's historyB30, B32, B34, B38Claude · Sonnet · highCodex x
B42 Anomalies and notificationsQ05 with its parameters; anomaly status; the three e-mail events of §7.2The generator's flat line, zero run and base-load step are found, a normal weekend is not; a message holds no GSRN, address or quantity; no mail server configured means no error and a visible noticeB10, B23Claude · Sonnet · highCodex high
B43 ExportsExcel, interval export, export jobs, the access rule of §8.6Files open in Excel and LibreOffice with the method sheet; an export of a million interval rows completes as a job; another user cannot fetch the file; it is gone after the downloadB15, B26Claude · Sonnet · mediumCodex high
B44 OperationspgBackRest backup and restore runbook; retention; the removal job of §8.5; key rotation runbookA restore of scenario A to a clean host reproduces the figures and a login within the time B22 measured; the retention job drops a month partition; after a removal the search of §8.5 finds nothing, and a restore of an older backup followed by the replay of removals finds nothing eitherB22, B24Claude · Opus · highCodex x
B45 Design application IIThe pages of phase 2 brought to A2's manual; the heat map as the designed centrepieceAs B17, for the phase 2 pagesB40, B41, A2Claude · Opus · highThe lead; then the owner's view
B46 Documentation for an organisation that installs itdocs/guide/: install, create the token with a business login, operate, upgrade, back up; the controller template of §8.4A person who has not seen the repository installs the product on a clean host from the guide alone and loads the demo organisationB44Claude · Sonnet · mediumAgy

Exit of phase 2: the scale gate has passed or its remedy is built; the run against a business login is reported; an organisation with a hierarchy, several users and restricted access sees consumption, emissions by all location-based methods and cost.

Why these wait for phase 2: they need many MPs, a second user, or a loader that phase 1 does not need. Why market-based figures are not here: their fact grain depends on boundary weights and claims (§5.5), which are phase 3; building a residual-only version first would build the wrong grain.

10.3 Phase 3 – ESG reporting

EpicScopeAcceptance criteriaDepends onAgent · model · effortReview
B51 Boundary, production links and attributesorg.boundary_weight, org.boundary_status, org.production_link, org.production_attribute, page R2, weights in location-based queries; two approaches: the organisation's and the ESRS reporting boundaryA 30 % equity share contributes 30 % under equity share; a leased-out MP is outside own operations under the ESRS boundary and shown as its own line; the consolidated-group split sums to the total; an E18 plant linked to an E17 gives E02 and E05, an unlinked one leaves them unavailable; a proposed link changes nothing until confirmedB25Claude · Opus · highCodex high
B52 Claims register and eligibilitymb.claim, evidence upload, mb.claim_eligibility, mb.application_set, mb.application, page R3The same cancellation imported twice is refused; a claim for another beneficiary, another market or another period cannot be verified; an unverified claim is in no coverage; requested volume above the claim's is refusedB51Claude · Opus · highCodex x
B53 Market-based method at leaf graincalc.mb_*, the ten steps of §5.5, MB-AN-ENThe two cases of A1x-01 (3 000 g, not 900 g; A covered and B not); 100 MWh with 70 MWh of zero-factor claims and the 2025 general declaration gives 10.4421 t through the report query, labelled "published"; 120 MWh requested against 100 MWh applies 100 and reports a surplus of 20; claims at a node and at its ancestor never cover the same kWh; self-consumption with sold attributes is at the residual factor with the leaf's weight; Σ of leaf q equals the weighted consumptionB32, B52Claude · Opus · highCodex x
B54 Targets, budgets, base year, forecastplan.*; comparisons in queriesA variance to a target of another method is "not applicable" with the reason; the stored path, not an interpolation, is what is compared; the forecast is labelled with its modelB15Claude · Sonnet · highCodex high
B55 Locks, report editions, as-of inputs, restatementsrpt.*, closing sweep, ts.readings_as_of, the as-of interval function, page R1The tests listed in §5.8; the mixed-method rules 1 and 5 of §5.2 for a report's mapping; Q06 splits a difference into its causes; a restatement keeps both editions readableB51, B27Claude · Opus · highCodex x
B56 ESG pages X2, R1–R3 completed, print formThe executive ESG page and the report views; print stylesheets for X1 and X2Location-based and market-based always side by side and labelled "Scope 2, el"; requirement tags follow the report's framework settings; X1 and X2 print on one A4 page eachB53, B54, B55Claude · Sonnet · highCodex high
B57 Auditor's package, audit log, further rolesThe stored package of §6.5; the audit log page; roles steward, reporter, auditorThe manifest's hashes verify; every figure in report.xlsx is reproduced by an independent script from the package's files alone, also after the interval data of the period have been dropped; an auditor grant with an end date stops working on that dateB55Claude · Sonnet · highCodex high
B58 Quality measures as report outputsQ01a–Q04, Q06 in reports with applicability settingsMeasures equal duration-weighted hand calculations on the demo organisation, including an MP that joins the boundary mid-yearB55Claude · Sonnet · highAgy
B59 Demo buildStatic demo against a fixture API; banner; documentationThe demo runs without a backend; a scan finds no real identifier; the generator's seed and definition are in the repositoryB41, B56Claude · Sonnet · mediumAgy
B60 Design application IIIThe ESG pages and the print form brought to A2's manualAs B17B56, A2Claude · Opus · highThe lead; then the owner's view

Why these wait for phase 3: they need the organisation of phase 2 (hierarchy, users) and they are needed only when a figure is reported outside the organisation.

10.4 Phase 4 – Breadth (gated; each becomes an epic when its gate is met)

CapabilityGate
Third-party API as a second MeteringSource (D1)The owner or a user registers as a third party; the 730-day and "13 months" questions are answered (R1 open questions 3, 4)
Charge links endpoint as the source of dated links and pricesEnerginet enables it (the weekly probe of B33 stops answering 404)
LB-ANDK-125; MB-AN-AIB; an upstream factor set for G06The factor is obtained with its source (R3 open question 4)
The two other boundary approachesAn organisation that reports under them
Other energy carriers, purchased heat (E06 family, G19, G20), the audit thresholds M15a–c, the ESRS 2023 outputs G17, G18, M01, the RE100 check G08RManual input tables and a steward page; legal rules re-checked on the day
Weather-normalised consumption (M11), benchmarks against industry profilesA named degree-day series; the industry code mapping (R2 open question 13)
"Right now" tile (CO2Emis, CO2EmisProg), domestic mix (GenerationProdTypeExchange)Wanted by the owner; labelled as indicators, never in a Scope 2 total
MB-HR and the hourly matching scoreHourly guarantees of origin exist in Denmark (R3 open question 5)
English user interface; BBR and CVR enrichmentDemand; access to Datafordeler

10.5 Who owns what

A table is created by exactly one epic; another epic that needs a column adds it in its own migration block and says so in its brief.

EpicCreates
B03–B12 (phase 1)See phase-1.md §3 and §13.3: B03 creates every table of phase 1. The tables this document assigned to B10 and B12 (agg.mp_day, agg.mp_month, calc.emission_day, calc.emission_month) and calc.dirty, calc.run, core.mp_access, ts.reading_period are not created in phase 1; the re-plan of phase 2 assigns them
B23auth.app_user, auth.user_identity, auth.session, auth.invitation, audit.event
B24ingest.credential, ingest.access_token
B25org.node, org.node_closure, org.mp_allocation, org.dimension*, org.mp_dimension, org.method_default, org.node_attribute, org.site_calendar, org.setting; ops.config_version
B26auth.role_grant, auth.user_mp, sec.* functions and every policy
B27ingest.control_total
B29fx.mix_hour and its history, fx.re_coverage_hour and its history, ref.report_group, ref.connected_area
B30calc.mix_month
B32fx.factor_set, fx.factor_year
B33price.spot, price.charge, price.charge_price, price.charge_link, price.supply_contract, price.invoice_check
B34calc.cost_day, calc.cost_month
B35agg.node_hour
B51org.boundary_weight, org.boundary_status, org.production_link, org.production_attribute
B52mb.*, ref.threshold
B53calc.mb_run, calc.mb_leaf_year, calc.mb_leaf_instrument, calc.mb_leaf_month
B54plan.*
B55rpt.*

Shared files that version 1 had every page epic edit do not exist: each page directory has its own catalogue file, queries and strings module (§1.4). Lock files change in B01; an epic that needs a further dependency says so in its brief and is merged alone. Migration numbers of phase 1: phase-1.md §13.3; later phases continue in blocks of 20.

10.6 The scale gate (B22)

It runs beside the end of phase 1 and gates phase 2: the epics that build on ts, agg or calc at scale (B26, B30, B32, B34, B35, B44) list it under "Depends on".

What is loaded and measuredWhy
Scenario A (5 000 hourly series, five years): load rate, table and index sizes against §2.4, payload compression ratioThe base case
One calendar month of 5 000 quarter-hourly series (14.9 million rows): load, daily recomputation, a factor revision of that monthThe research points to quarter-hours (R1 §6.7); every recomputation is per partition (A1v-03)
Scenario A with the tree of L1 at 500 sitesThe cost of children in storage, aggregates and the daily run
Sizes of every agg and calc table; total disk; the requirement stated for scenarios A, L1 and C§2.4 gives estimates only
Time of a daily recomputation for 5 000 MPs (budget 15 minutes) and of a full-year factor restatement (budget 60 minutes)§5.7
Backup and restore time with pgBackRest at scenario A§8.6
PostgreSQL settings for a 16 GB hostThe image defaults are too small (§2.4)

Gate queries, each at 10 concurrent users as elo_api with row-level security on, budget 500 ms at the 95th percentile:

#Query
1The root at day grain over 400 days, emissions in one method (2 million rows of calc.emission_day: the row budget)
2The same for a user granted one tenth of the sites
3A tag selection of 1 000 MPs at day grain over one year
4The root at month grain over five years, with the previous year
5One MP at hour grain over 31 days, with factors (the interval view)
6A ranking of 5 000 MPs by variance to the previous year, from the month tables
7The root's heat map, hour grain over one year, from node-hours
8Query 1 over 750 days, measured without the budget, to show what the budget protects against

If query 1 or 2 misses: lower the row budget (the grain then falls to months sooner), and add the leaf × day × method aggregate only if day grain over the whole organisation is needed. Both are decided in the report.

10.7 What can run in parallel

WaveEpics
1a–1hPhase 1: see phase-1.md §13.3
2aB21 · B23 · B29 · B33 · B36 · B38
2bB22 · B24 · B25 · B27 · B37 · B42
2cB26 · B28 · B30 · B32 · B34 · B35 · B39
2dB31 · B40 · B41 · B43 · B44
2eB45 · B46
3aB51 · B54
3bB52 · B55
3cB53 · B57 · B58
3dB56, then B59 · B60

Epics of one wave touch different tables (§10.5) and different page directories.


11. Open decisions for the owner

Only what the owner must decide or supply himself. Each has a default, so no phase waits for an answer; the lead puts them to the owner.

#Decision or requestRecommendation, and what happens without an answer
1Confirm how D11 is stored. Every method is computed for every MP and interval and available down to one hour; the stored facts are per MP and day and per month, the hour level is a view over stored readings and factors (§1.6). The lead has accepted this on the owner's behalfConfirm. Storing the hour level adds 0.9 to 1.5 billion rows at design scale for values that are a product of two stored rows
2More reports from Eloverblik for the validation (the lead has asked): 2025 by price area with 125 % and with 200 %, 2025 by municipality with the other percentage, and one on preliminary data for a 2026 period ending before 15 SeptemberNeeded for the exit of phase 1 (price area) and for B31 (municipality). Without them the price-area methods ship with consumption validated and emissions checked only against golden cases, and say so
3A business login for one read-only run (B28): the owner's company, if it has one, or a friendly organisationEverything seen live comes from one private metering point (risk 3). Without it, no statement about organisations or scale is made
4Who the product is for. Organisations with a business login, or also private personsOrganisations. A private token works and is handled as personal data (§8.4), but no household features are built
5Language of the user interface. D4 fixes Danish number and date formats; the labels are not decidedDanish in the first version, one strings module per page so English can follow; identifiers, catalogue, README and documentation in English
6Product name. "Eloverblik" is the name of Energinet's service; NOTICE disclaims affiliation, and Energi Data Service's terms forbid suggesting Energinet's endorsement (R2 §1.9)A distinct public name before the repository is made public; the repository name and the internal names (elo_, @elo) can stay
7What may be public. (a) docs/sources/ holds Energinet's PDFs, portal texts and OpenAPI files, whose redistribution rights are not established. (b) docs/sources/eloverblik/samples/ is the owner's own metering point with scaled quantities: the shape of his consumption and his grid company's prices (A1v-08)Before going public: replace (a) by links and hashes unless redistribution is cleared; remove (b) from the tree and its history, unless the owner consents in writing to publishing it. The tests no longer need it (§8.7)
8Public demo. Wanted, and where?Yes: the static demo build of B59 with generated data, published when the repository becomes public

Settled by the lead's rulings and the reviews, recorded here because version 1 listed them as open:

WasNow
Default GWP setAR5 (28 / 265) is the product default: the only set whose values are verified, and the one that reconciles with Eloverblik and Energinet (advisor agrees). The set is selectable per organisation and report and stated on every figure. The lead saves the IPCC table as a source (R3 open question 13), after which an ESRS report template can propose AR6-fossil
Cost before a supply contract is enteredNetwork, tax and subscriptions are shown as computed and energy as "til spotpris, uden leverandørtillæg", an estimate; no unlabelled total anywhere (§5.6)
Default retention of interval dataKept while the MP is in the organisation; each organisation sets its limit; mandatory for private accounts; the setting page says that dropping interval data ends the hour-level drill-down (§8.5)
When to run the first loadBefore 31 December 2026, as epic B06, with the client alone (the lead's ruling)
The validation baselineSaved by the lead on 15 November 2026 under data/validation/declarations-2026-11-15/ (A1v-06)

12. Risks

Ranked by likelihood × impact.

#RiskLikelihoodImpactMitigation
1The declaration datasets change on 24 November 2026 (method, possibly columns, backfill from 17 September); values after 1 September are provisional (R2 §2.2.1)HighMediumFactor history and recomputation are ordinary paths (§2.6, §5.7); the re-pull is preconfigured; an unknown or missing column is reported, never defaulted (§3.8); pending hours are shown, not filled; B11 is built after that date or re-checked against it; the validation uses the snapshot of 15 November
2Eloverblik is slow or unstable; the first load of thousands of MPs takes days to a week (§3.7)HighMediumNewest-first, resumable chunks with a defined state machine; cooldown and parking; off-peak window; progress on the data status page; latency measured in B06 and B08 and the plan's numbers revised
3Everything seen live comes from one private metering point (L1: one E17 with three children, net settlement group 6). An organisation's responses were never seen: consumerCVR, includeAll under a CVR, hundreds of MPs in one list, MPs without children, quarter-settled consumption, other tariff levels, access edges (A1v-17)Certain todayHighThe run against a business login (B28) before any statement about scale; ref.mp_type and the allowlist are data; unknown fields and unsupported units are reported, not guessed
4The municipality method cannot be reproduced against the report: two sources disagree on the factor dataset and on the biogenic base (R2 §3.4.4, R3 §3.3.2)MediumHighThree variants as parameters and the data basis as a parameter; B31 decides on the snapshot; status unvalidated on screen until then; the price-area methods do not depend on it and are validated in phase 1
5Historical cost is wrong because past charge links cannot be obtained (R1 §8.3)Certain for historyMediumStatus "estimate" before the first observation; link snapshots from the first run; no observed price used for earlier days; the charge links endpoint is adopted when enabled; bill reconciliation
6The row model misses its budgets at 5 000 MPs, at quarter-hour resolution, or with row-level security onLow to mediumHighB22 is a gate for phase 2 with named scenarios and queries; row budgets at hour and day grain; remedies named in order of size (§10.6)
7A token leaks (logs, backups, repository, a compromised API)LowVery highSealed store with the private key only in the worker (it protects stored tokens; a compromised API can still see a token while it is being submitted); log allowlist and log scan; guard on tracked files; ciphertext-only backups; yearly expiry limits the damage. In phase 1 the token is only in the owner's .env
8Readers compare figures of different methods and draw wrong conclusionsMediumHighThe rules and tests of §5.2: one mapping per request, variances within a method, a labelled comparison view, mixed totals named as such; a Codex review of B41 on exactly this
9A market-based claim is counted twice or applied without being eligibleMediumHighNatural key on claims, recorded eligibility checks, application at leaf grain where a claim can only take what is uncovered (§5.5); tests of B52 and B53
10A child MP type or a net settlement group the research did not see behaves differently (groups 3, 4, 5, 7, 99 are undescribed, R1 §6.3)MediumMediumref.mp_type is data a steward can correct; the tree and each child's role are visible on D1; unknown types are fetched and kept out of totals
11A refresh token expires after a year and data stops (R1 §11)CertainMediumExpiry read at entry; warnings from 60 days, by e-mail from phase 2; the account state on the data status page
12The year 2021 ages out of the API on 1 January 2027MediumMediumB06 captures the owner's history before 31 December 2026 with the client alone
13Personal data survive where the policy says they do not (an unknown field, an error text, a request record, an export, a backup)MediumHighOne allowlist before any write; no GSRN outside one table; the removal closure with its replay after a restore; sentinel tests in B04, B07, B44
14A correction that leaves monthly totals unchanged is missed by the control sweepLowLow to mediumThe control compares quality as well; yearly re-fetch in January; closing sweep before every lock
15The tariff position on the two DST days is unverified (R1 open question 14)MediumLowOne function, one test, an invoice check in B34; two hours a year
16Eloverblik's grid area code does not match the public datasets' code (R2 open question 5)LowHigh for the MPs concernedChecked on the first real response in B07; an MP without a price area is visible and has no emission figures; a steward can set it
17The delivery rules attributed to D1 are not the rules in force (R1v-05)MediumLowThe windows are defaults; the coverage reconciliation and the sweeps do not depend on them
18AR6 values, the Klimakompasset factor and the upstream factor are not sourcedCertain todayLow to mediumSets and methods exist with status "unverified" or "unavailable"; nothing is computed from an unsourced number
19Licence and trademark: a claim of conformance or the standard's name slips into the product; the token attribution is lost in a bundle; and it is not established whether a bundle with the tokens compiled in is an adaptation under CC BY-SA (R4 §7 question 2)LowMediumGuard and notice checks in CI, including the design documents, proven by deliberate violations in B01 and B13; the build keeps the option of loading the tokens at run time from their own CC BY-SA file
20The design flair is squeezed out by the data workMediumMediumA2 before the first page; one design application epic per phase with the owner's view as acceptance (§7.3)
21The renamed packages drift from the S&OP originalsMediumLowThe rename is scripted and repeatable; VENDORED.md records the commit
22Phase 1 has many epics before the first viewMediumMediumSee phase-1.md §13: 23 epics of at most one session; the capture (B06b) is the fourth on its path and secures the deadline early
23One host failsLowUp to a day of changesOff-host encrypted backups with archived write-ahead log from phase 2, restore rehearsed at scale (B44). In phase 1 the database can be rebuilt from the capture and the API, but the capture itself cannot be fetched again once its oldest year leaves the API's window: it is a set of files the owner keeps (phase-1.md §12.2)

13. Rejected alternatives

AlternativeWhy notWhere
DuckDB and dbt with a medallion warehouse, as S&OPOne typed source, incremental corrections, transactional locks; a second engine and a batch rebuild buy nothing here§1.2
Immutable published generations for serving219 million rows rebuilt and reloaded for a day's corrections; locks give reproducibility where it is needed§1.2, §5.8
TimescaleDB for compression and continuous aggregatesThose features are not under an OSI-approved licence§2.4
One row per series and day with value arraysThe brief's grain; hourly joins and single-hour corrections get harder. Kept as the fallback of B22§2.4
Emission facts stored per interval and method0.9 to 1.5 billion derived rows, rewritten at every factor revision§1.6, §2.7
CO2e stored in the factsFixes the GWP set at calculation time; the gases are stored instead§2.6
Materialised views refreshed wholeOne corrected day would rewrite every aggregate§2.8
Filling missing hours or missing factors with estimatesAn invented number in an audited total; "pending" and "missing" are states§3.8, §5.10
730-day requests for the first loadAbout 15 MB per response and likely timeouts§3.5
Hour or Quarter aggregationActual returns every series at its own resolution§3.5
Calling relation/add automaticallyIt changes the organisation's Eloverblik overview and cannot be undone§3.2
The API process calling Eloverblik or Energi Data Service on a user's requestRate limits per IP and per dataset; the public API is "not meant as the source" for an application's users (R2 §1.6)§1.1
A cube or GraphQL endpoint instead of named queriesEvery free combination would have to be made correct, safe and fast§6.1
A cache serverOne more service for data that changes once a day§6.4
Server-rendered PDF for the auditorA heavy dependency for a cover sheet; auditors recompute from tables§6.5
A token encrypted with a key the API holds; an external vaultThe exposed process could decrypt; a vault is a service for one secret§8.1
Row-level security policies on ts.readingA per-row check on the largest table where every query names its MPs§8.3
Anonymised real data as the demoA scaled real profile is still someone's profile§8.7
A separate "showcase" presentation of the pagesD7: one style, the flair inside the analytical pages§7.3
A time zone or number format per userD4; and every aggregate would depend on the viewer§4
Storing local timestampsThe repeated hour collides§4
One blended price × one consumption series for costEach charge has its own billable series and dated rate§5.6
A Boolean "in boundary" flagAn equity share is a weight; consolidated-group membership and lease status are separate facts§2.3, §5.4
Upsert of readings by (series, interval start)Keeps intervals a correction withdrew: 7 kWh where 4 is right (A1x-02)§2.4, §3.9
One fact grain for location-based and market-based emissionsA market-based result is not linear in consumption: weights applied twice, node-specific claims lost (A1x-01)§2.7, §5.5
Locks with arbitrary datesWould need day slices of every fact and input for a case no reporting framework asks for (A1x-03)§5.8
Unknown master-data fields kept in a JSON columnKeeps whatever personal data Energinet adds next (A1x-06)§8.4
Payload bodies kept as long as the readings18.6 to 130 GB before compression and the larger personal-data footprint, for what the hash and the parsed rows already prove (A1v-15)§2.2
Node-hours for every node with more than one seriesAs many rows as the readings, rebuilt at every edit of the hierarchy (A1v-15)§2.8
The data basis ("Final only") as a variant of each methodDoubles the hourly methods and cannot split one figure by status (A1v-14, A1x-13)§5.7
Validity dates on method defaultsA default that changes in time changes the method inside a series (A1v-04)§5.2
Separate rate buckets for data and token callsThe limit is for all calls from the IP; a refilling bucket bursts (A1x-16)§3.3
Nightly pg_dump at scale; a dump per changed partitionThe first uploads everything every night; the second makes change tracking the product's job (A1v-10)§8.6
Identity, sealed store and row-level security before the first view16 epics before the owner sees his data (A1v-02)§1.1, §10
Contract tests on the saved samplesThey are the owner's metering point, scaled (A1v-08)§8.7
A third implementation of the report for the testsThe Python reference already is the readable loop (A1v-15)§5.9
A residual-only market-based figure in phase 2It would be built at the wrong grain and rebuilt in phase 3§10.2

Appendix A – What became of the research's design consequences and the review findings

"Accepted" means the design does what the item says, at the place named. Numbers are the items of each document's section "What this means for the design" in its corrected version.

ItemDispositionWhere
R1-1 Customer API first, Third-party as a second connectorAccepted§3.1, phase 4
R1-2 Token as a yearly, personal-data secretAccepted§8.1, §3.10
R1-3 One limiter per IP, cached access token, back-off, batch halvingAccepted§3.3, §3.4
R1-4 Parse per endpoint, status and content type; per-item outcomesAccepted; the outcome of a request window is kept apart from the state of the MP§3.2, §3.4, §2.2
R1-5 UTC start and end, resolution, qualityAccepted. The end of a 15- or 60-minute value is its start plus its resolution and is not stored a second time; calendar-resolution values store their end§2.4
R1-6 Typed tree; never parent plus childrenAccepted§2.3
R1-7 Child IDs requested explicitlyAccepted; m in every count§3.7
R1-8 Trailing re-fetch and a change logAccepted with other windows: 14 days daily instead of about 10; a tiered control sweep over 3 years, a coverage reconciliation, a yearly re-fetch and a closing sweep§3.6, §2.4
R1-9 Small resumable chunks (≤ 92 days hourly, ≤ 23 days quarter-hourly)Accepted for hourly. Changed for quarter-hourly: calendar months (up to 31 days, 2.5 MB instead of about 2 MB) so that checkpoints are calendar units; splitting down to one day covers a timeout§3.5
R1-10 Master data as versioned snapshotsAccepted§2.3
R1-11 Price area derived from reference dataAccepted§2.3, §2.5
R1-12 Future links, link snapshots, three-part charge identity, estimated history, cost per child series, VAT at displayAccepted§2.6, §5.6
R1-13 Missing data as a stateAccepted§4, §5.10, pages A7, D1
R1-14 Watch isalive, surface healthAccepted§3.10
R1-15 Minimal personal dataAccepted: an allowlist, both protection flags, a controller template§8.4
R1v-01…13All applied through the corrected R1; specifically parsing (§3.2), positions up to 100 (§3.2), historical links (§5.6), charge identity (§2.6), unverified D1 (§3.6), self-consumption only where measured (§2.3), calendar periods (§2.4), future links (§3.6)
R2-1 Cache everything locallyAccepted§1.1, §3.8
R2-2 Rows with dataset, key, version, retrieval and metadata time; upsertAccepted§2.6
R2-3 UTC for joins, local time for displayAccepted§4
R2-4 Declaration first, indicators secondAccepted; the indicator datasets are not loaded before phase 4§3.8
R2-5 The calculation as parameterised formulas saved with a reportAccepted; the GWP set and the data basis are query-time parameters, and a lock stores its recipe§5.2, §5.3, §5.7, §2.9
R2-6 Both municipality variants behind a switchAccepted, and extended to three variants§5.3, §5.9
R2-7 Never filter DeclarationProduction by one methodAccepted by not loading the dataset§3.8
R2-8 The 2026 gap as pending, rolling re-pullAccepted; the factors of 15 November 2026 are saved for the validation§3.8, §5.7, §5.9
R2-9 Price area through the grid areaAccepted§2.3, §2.5
R2-10 Price model of dated componentsAccepted. The electricity tax announced for 2028 is not seeded: its source is third-party; it arrives through the price list§5.6
R2-11 Charges from Eloverblik's charge links, price list as fallbackChanged: the charge links endpoint is disabled, so getcharges snapshots give the links and the public price list the dated prices§2.6, §5.6
R2-12 Benchmarks are industry aggregatesDeferred to phase 4§10
R2-13 Reference tables as data filesAccepted§1.5, §2.5
R2-14 AttributionAccepted§3.8, §7.2
R2-15 No DAWA, no old Datafordeler accessAccepted; BBR and CVR are phase 4§10
R3-1 Scope 2 always a labelled pairAccepted§5.2, §7.2
R3-2 Intervals are the source of truthAccepted§2.4
R3-3 Factors per gas with units, version, published CO2e; named GWP setsAccepted, except the default set: AR5, settled in §11§2.5, §2.6, §5.5
R3-4 Every method computed and kept; method a parameter; change of reported method loggedAccepted with the storage grain of §1.6 (for the owner's confirmation, §11)§2.7, §5.2, §5.8
R3-5 Recompute on changed values or metadata; pending hoursAccepted§3.8, §5.7
R3-6 Instruments registerAccepted, as a register of claims with a natural key and recorded eligibility§2.9, §5.5, B52
R3-7 Annual and hourly market-based engine; apply once, never beyond consumptionAccepted for annual, at the grain of the reporting leaf; hourly has a reserved method and table room, unavailable today§5.1, §5.5, B53
R3-8 Losses additive, Scope 3 category 3; upstream unavailable; biogenic memoAccepted§5.3, §5.5
R3-9 Boundary as data: holder, user, lease, weights per approach, group membership, validityAccepted. Sub-meter series entered by hand are not built before phase 4; a static allocation share is§2.3, §5.4
R3-10 Gross accounting; self-consumption onceAccepted; unavailable where production is not measured§5.4
R3-11 Mix for every method, approach named, all carriersAccepted for electricity; other carriers are phase 4§5.3, §5.5, §10
R3-12 Calculation version, approval, locks, restatementsAccepted§5.8
R3-13 Quality measures on durations, product controlsAccepted§5.10
R3-14 No "CO2-neutral" labels; claims with evidenceAccepted as a product rule§7.2
R3-15 Legal thresholds as configurationAccepted§2.5
R3v-01…21All applied through the corrected R3; specifically base units and explicit conversions (§2.7), the municipality recipe and its open points (§5.3), additive losses (§5.3), self-generation attributes and capped allocation (§5.5), numeric weights (§2.3), lease overrides (§5.4), unavailable upstream (§5.5), cost per charge series (§5.6), A05 not an estimate and duration-weighted coverage (§5.10), conditional applicability (§7.2), published CO2e kept (§2.6)
R4-1 Copy from an earlier internal project at the three commits; grant firstAccepted; the grant exists (D10)§7.5
R4-2 Token package stays CC BY-SA with notices and checksAccepted. Changed: the wording "follows the … standards" is dropped everywhere, because D5 allows no claim of conformance§7.5, §9.4
R4-3 Rename packages, prefixes and theme IDsAccepted (D5)§7.5
R4-4 Polarity −1 for consumption, cost and emissions; new scenario codesAccepted as data from the API; the codes are A2's (D8)§7.2, §2.9
R4-5 The notation manual is a deliverableAccepted: task A2, a row of the plan§7.3, §10.1
R4-6 Time as instants with a local label; hour and quarter-hour grains; time-based axisAccepted§4, §7.5, B36
R4-7 Server aggregates; 750 points, 150 rows; min, max and scale maximumAccepted§6.3
R4-8 Reuse the listed components as they areAccepted, renamed§7.5
R4-9 Build or extend the listed componentsAccepted§7.5, B36–B38
R4-10 Generalise the shell firstAccepted, in two steps: what three pages need, then the restB14, B39
R4-11 Purpose, message, title lines, footnotes on every pageAccepted§7.2
R4-12 Flair in typography, layout, motion, interactionAccepted: task A2 defines it, the design application epics build it§7.3, B17, B45, B60
R4-13 Decide the card chrome knowinglyAccepted: an output of A2§7.3
R4-14 Honest statesAccepted§6.2, §7.2
R4-15 Test in a browser before committing to a rendering approachAccepted: Playwright and an accessibility check in every page epic; the heat map's canvas is tested in B37§9.1

Appendix B – Reviews of version 1: what was changed

Reviews: reviews/architecture/advisor-1.md (A1v, approve with changes) and reviews/architecture/codex-1.md (A1x, not sound, two blockers), both on version 1 (commit 23278cd). Every finding was checked against the evidence it names and against version 1's text. Result: 36 accepted, 0 rejected. Three were accepted in another form than advised, as the rows say. Both blockers are accepted: no counter-example exists; the failures they construct follow from version 1's text.

Where the two reviews disagree, and what was decided:

PointAdvisorCodexDecided
SeverityNo blockerTwo blockersBoth blockers are real defects of the design, not of wording: A1x-01 gives wrong market-based totals, A1x-02 wrong sums of readings. Treated as blockers
The "Final only" data basisA fourth variant of the method (A1v-14)A parameter of query, report and lock, with status-separated facts (A1x-13)A parameter. A variant would double the hourly methods and still not let one figure be split by status; facts keyed by factor status serve both (§2.7, §5.7)
The per-day content hash"Keep it exactly"Must include bounds, resolution and unit, and the merge must delete (A1x-02)The mechanism is kept; what is hashed and what a changed hash does are extended (§3.9)
LocksGood as copies of every method's month facts; add as-of drill-down (A1v-05)Month copies cannot reproduce a calculation or a partial month (A1x-03)Both: whole local months only, and the lock freezes weights, recipe and input rows as well (§5.8)
Corrections detected by the monthly control totalKeep the idea, tier its frequency (A1v-12)The first control must verify, and coverage must be reconciled without it (A1x-10)Both (§3.6)
Scale tableCorrect as computed; L1 tree missingRecomputed by profile, with overheads (A1x-17)Codex's profiles and overheads are used (§3.7)
FindingDecisionReason (evidence checked)Sections changed
A1v-01 The frontier does not work with many metersAcceptedVersion 1 took the earliest complete-through day over all series: with values 2–7 days late (R1 §6.5, §11) the slowest of 5 000 series sets it, and one hour never delivered pins it for ever§4 (frontier on coverage, threshold 98 %, late series named); §9.2 (two generator cases); B10, B14
A1v-02 The plan cannot be run as drawnAccepted, with the lead's ruling16 epics preceded the first view; B15 and B16 of version 1 needed tables built two waves later; catalog.yaml and strings.ts were edited by every page epic§1.1 (local single-user mode), §1.4, §10 rewritten (phase 1 of 17 epics, splits, §10.5 owners, §10.7 waves), risk 22
A1v-03 The scale gate tests the mildest caseAcceptedOnly scenario A was loaded; day grain over the root reads up to 3.75 million wide rows; derived tables and disk were not sized§2.4 (L1 and growth rows, derived sizes, disk requirement), §2.8 (row budget at day grain), §6.3, §10.6 (scenarios and eight named queries)
A1v-04 "Each part's default" can compare two methodsAcceptedorg.method_default had validity dates, so a default changed mid-series§2.3 (no validity dates), §2.9 (rpt.report_method), §5.2 (seven rules with tests), B41, B55
A1v-05 A locked figure cannot be traced to its factorsAccepted, together with A1x-03The interval view was live; fx.mix_hour had no history; factors.csv came from current tables§2.6 (mix history), §2.9 (rpt.lock_input, rpt.lock_factor_month, rpt.lock_package), §5.8, §6.5, §8.5
A1v-06 The validation baseline can be lost on 24 NovemberAccepted; the lead has actedR2 §7 question 1 leaves open whether history is recalculated; version 1 validated nothing in phase 1§5.9 (snapshot of 15 November, price-area check in phase 1 through the report query), B11, B12, B31, §11
A1v-07 Self-consumption excludes E18 plantsAcceptedAn E18 is its own market MP and no API field links it to an E17 (R1 §6.3, open question 16)§2.3 (org.production_link, the two cases of E02), §5.4, §9.2, B51
A1v-08 Contract tests rest on scaled real dataAcceptedsamples/anonymise.py scales quantities; shape, export pattern and grid prices are intact; §8.7 of version 1 forbade exactly this§8.7, §9.1, §1.4 (fixtures/contract/), B04, B05, §11 decision 7
A1v-09 The flair has no epic, criterion or ownerAccepted, with the lead's rulingA2 was not a row of the plan and nothing applied its result§7.3 (what A2 delivers), §10 (A2 as a row; B17, B45, B60), §9.1 (axe), risk 20
A1v-10 The backup does not fit this volumeAccepted; of the two options offered, base backup with archived write-ahead log is chosenA compressed nightly dump of 35 to 300 GB uploads everything again§1.2, §1.3, §8.6, B22, B44
A1v-11 Personal data: four gapsAcceptedprotectedAddress was stored and ignored; the name of a non-business MP was not on the redaction list; the deletion job missed copies; export files had no access rule§8.4, §8.5 (removal closure), §8.6 (export files), §1.5 (make token-import)
A1v-12 Ingestion: five pointsAcceptedR1 §9.2 ("several years repeatedly"), §6.6 (30018 rejects the item), §9.4 (off-peak)§3.3 (cooldown, off-peak window), §3.4 (clamping), §3.6 (tiered sweep; quality compared)
A1v-13 Hierarchy changes missing from the triggersAccepted, together with A1x-11Node-hours contain allocation shares; a year's restatement queued 1.8 million rows§2.7 (calc.dirty by scope), §5.7 (trigger 7, debounce, preparing)
A1v-14 Two parameters the validation may needAccepted; the data basis as a parameter, not a variant (see above)§5.9 tried a basis that no query could express; months of an open year moved under yearly methods§5.7, §5.5 (provisional months), §2.7, §2.9, §6.1
A1v-15 Seven things the first version does not needAcceptedEach can wait or shrink without losing a requirement§2.2 (bodies 90 days), §5.9 (no third implementation), §2.8 (node-hours for large nodes only), §5.4 (two approaches built), §8.2 (three roles until phase 3), §1.1 and §10 (order); calc.emission_day is kept and measured in B22
A1v-16 Measures without a page; "monitor" without a signalAcceptedG03, G10, G12, G13a, G13b, M04, E11b had no page; Q05 was gated on things it does not need§7.1, §7.2 (decompositions, print form, monitoring), §7.4 (matrix), B41, B42, B56
A1v-17 Everything live comes from one private MPAccepted, with the lead's rulingL1 is one private loginRisk 3, B28, exit of phase 2, §11 decision 3
A1v-18 Small items droppedAcceptedR2 §1.8 (news), R2 §7 question 1 (columns), R4 §7 question 2, D5, R1 design item 15§3.8 (news, columns), risk 19, B01 (guard on design documents and guides), B46, §8.4 (controller template)
A1v-19 The narrowing of D11 is soundAccepted (a note)–§1.6, §11 decision 1
A1x-01 Market-based fact grain (blocker)AcceptedThe recipe weights eligible consumption, the query weighted again: 900 g instead of 3 000 g; a node's claims could not be told apart inside one MP fact§2.7 (calc.mb_*), §2.9 (mb.application_set), §5.4, §5.5 (ten steps, two test cases), B53; market-based figures moved to phase 3
A1x-02 The merge keeps withdrawn intervals (blocker)AcceptedVersion 1's §3.9 merged and never deleted: 7 kWh instead of 4§2.4 (ts.replace_day(), change log with presence and resolution, hash contents, source_requested_at), §3.9, B08
A1x-03 A lock cannot reproduce its calculation or a partial periodAcceptedMonth copies for arbitrary dates; no frozen weights, recipe or inputs§2.9, §5.8 (whole months; four things frozen; barrier; tests), §6.5 (package stored at lock time)
A1x-04 Instrument checks do not establish unique, eligible claimsAcceptedNo natural key and no eligibility state (R3 §1.1.2, §6)§2.9 (mb.claim, mb.claim_eligibility), §5.5 (step 3), B52
A1x-05 MP removal leaves identifiable raw metadataAccepteditem_key and request_key held the GSRN for five years§2.2 (no GSRN outside core.metering_point), §8.5 (closure, backups, replay)
A1x-06 Extras and error strings bypass the storage policyAcceptedextras kept every unknown field; error_text was stored verbatim§2.2, §2.3 (no extras), §3.2, §8.4 (allowlist, sentinel test), §8.6
A1x-07 Keys that PostgreSQL rejectsAcceptedA partitioned table's key must contain the partition column; a primary key column cannot be null§2.2 (raw.fetch unpartitioned; composite keys), §2.10 (grant_id, partial unique indexes), B03
A1x-08 Calendar-resolution readings have no calculation pathAcceptedA monthly reading had no route into aggregates or hourly methods§2.4, §2.8 (agg.mp_month.source), §3.9 step 7, §4 (what a period reading supports)
A1x-09 Period-specific access errors made permanentAccepted30018 also means "entirely outside the available period" (saved Swagger); 30010, 30016 are about a period§2.3 (core.mp_access), §3.4 (window outcome apart from MP state; discovery and clamping), §3.5, B27
A1x-10 Checkpoints and control sweep do not guarantee recoveryAcceptedno_data had no transition; a first control became the baseline§3.5 (state machine), §3.6 (verification on first observation, coverage reconciliation, yearly re-fetch scheduled)
A1x-11 Hierarchy edits leave node-hours and caches staleAcceptedNo trigger; the cache key lacked configuration§5.7 (trigger 7, ops.config_version), §6.4, B25
A1x-12 Annual CO2e contradicts the published factorAccepted348.17 from the gases against the printed 348.07; 10.4451 t against 10.4421 t§2.7 (co2e_published_g), §5.5 (rule and label), §6.2, B32, B53
A1x-13 No selectable "Final only" basisAcceptedValidation tried what production could not compute; missing coverage could read as 0 %§2.7 (facts keyed by factor status, kwh_mix_covered), §5.7, §5.9 (validation through the report query), §6.1
A1x-14 Cost lacks a charge basis and an energy-total ruleAcceptedR2 §2.6: charges per kW and month, monthly fees; spot and contract both listed as components§2.6 (basis), §2.7 (spot_benchmark_dkk), §5.6 (bases, one energy rule, price precedence, carry-in), B33, B34
A1x-15 Non-kWh series enter kWh calculationsAcceptedR1 §5.7 lists MWh, kW, reactive energy, counts§2.4 (to_kwh, quantity in kWh), §3.2, §3.9 step 8, B08
A1x-16 Rate and retry bounds incompleteAcceptedThe 120-a-minute limit is for all calls; a full bucket bursts; a 429 split batches; halving had no end§3.3 (one pacer, token reservation, cooldown), §3.4 (bounds, terminal state), B05
A1x-17 The scale table omits the mixed tree and overheadsAcceptedL1's tree is three hourly and one quarter-hourly series: 75 501 calls, not 52 001§3.7 (profiles, overheads, barrier), §2.4, §2.2 (130.4 GB)

Appendix C – Open findings for the re-plan of phases 2 to 4

Added in the third architect round. Every finding of the round 2 reviews (reviews/architecture/advisor-2.md, A2v; reviews/architecture/codex-2.md, A2x) that concerns a later phase, with the phase that must resolve it before it is built. The findings resolved for phase 1 are in phase-1.md, Appendix A; a finding listed in both places has a phase 1 part that is resolved there and a later part that is open here. Nothing below has been made sound in this document. The re-plan of phase 2 also starts from phase-1.md §1.4: each simplification of phase 1 names its cost at 5 000 metering points and what phase 2 must measure before replacing it.

FindingWhat is openPhase that must resolve it (epics as numbered here)
A2x-03A search for readable windows that needs no whole readable chunk and no manual probe: documented access bounds where the API gives them, several accounts and powers of attorney, the answer at the end of an access period2 (B27, with the report of B28)
A2x-04Calendar-resolution readings (P1D, P1M, P1Y, PXD): one series-wide rule of authoritative coverage across fixed and calendar readings, promotion and demotion, partial periods, the month aggregate's source. Phase 1 does not store them2 (B27 or its own epic, before B30–B35 read month figures)
A2x-05The lock barrier must include every writer of inputs and bind the frozen facts to exactly the input versions read; the as-of resolver must use the first-load seam that phase-1.md §3.4 defines3 (B55)
A2x-06A complete frozen input manifest for a lock, including consumption at a sufficient grain, dated weights and classifications, cost and denominator inputs; the key of rpt.locked_fact for a state that changes inside a month3 (B55, B57; retention in B44)
A2x-07Removal must reach report packages on the reports volume and the capture files; removal records kept outside the backup; the retention setting for private accounts enforced once an install is not the owner's own machine2 (B44) for captures, retention and tombstones; 3 (B55, B57) for report packages
A2x-08One ledger of underlying attributes behind guarantees of origin, PPAs, tariffs and supplier declarations; applications restricted to the verified beneficiary, market and period3 (B52, B53)
A2x-09Invalidation of market-based runs when a weight, share, production attribute, claim or residual factor changes; one current run per inventory scope3 (B51–B55)
A2x-10Method defaults resolved per dated reporting leaf, not per metering point; access to leaf facts by the granted node2 (B25, B41); carried into 3
A2x-11Node-hour totals cannot recover per-MP weights or methods: physical, single-method results only, or a grain that keeps them2 (B35) keeps them physical; 3 for boundary-weighted hour queries
A2x-12Mix coverage on the delivered consumption of the mix-covered hours; mix membership by method, source variant and factor version2 (B29–B32, B41), before the municipality validation is claimed
A2x-13Cost: link-effective, price-effective and observation dates kept apart; a rule for a link that disappears from a snapshot2 (B33, B34)
A2x-14Dated supplier declarations per contract and covered volume; their relation to the claims ledger3 (B53); the contract reference when B33 creates the table in 2
A2x-15Precision of weighted and mix aggregates: no rounding before display; a remainder rule2 (B25, B30, B35)
A2x-16Credential replacement in the sealed store: a generation that invalidates the cached access token, running jobs and in-flight results. Phase 1 covers replacement by restart only2 (B24)
A2x-18Elapsed time of large loads under a schedule; health, token, probe and retry counts at scale; several-call public loaders in the job table2 (B22, B27, B28)
A2v-10Candidates to drop or defer without losing a requirement of the brief: agg.node_hour until a query needs it, plan.forecast_value, price.invoice_check, the loss convention MB-KK, Excel beside CSVThe re-plan of 2 and of 3
A2v-12Keys and partitions of tables phase 1 does not create: core.mp_access, calc.dirty (text scopes, method, ranges), agg.node_hour and rpt.locked_fact (nullable key columns), the owner of calc.v_emission_day and of the anomaly table; partitioning of ts.reading_change, raw.fetch_item and raw.payload for retention2 (B22, B25, B35, B42, B44); 3 (B55)
A2v-13The scale gate: the daily run against the off-peak window; whether the comparison side counts in the row budget; factor rows changed per day inside the 120-day window; ts.day_load in the disk requirement (1.4 to 5.5 GB, phase-1.md §3.4)2 (B22)
A2v-14The read-only look at a business login before phase 2 is planned: the capture tool of phase-1.md B06b runs on any Customer API tokenBefore the re-plan of 2 (the lead; B28 remains the full run)
A2v-15Texts of this document left behind: the job table of §1.3 (monthly re-pull, calls per dataset), Appendix A items R1-7 and R3-7The re-plan of 2
A2v-16Mapping from reporting leaf to method; the allocation behind the loss kWh of §5.5 step 7; where pgBackRest runs; waves in which policies and plan.base_year.lock_id precede their tables2 (B25, B26, B44); 3 (B53, B54, B55)
A2v-17One electricity bill, if possible for a month with a DST day2 (B34)

Kilde: docs/architecture/solution.md i løsningens repository.