Eloverblik

Dokumentation · Data og kilder

Storage

The database of phase 1 as B03 built it: every table of docs/architecture/phase-1.md §3, the pacer's two functions (§5.2), the recorder (§3.1, §7), the job queue (§1.2). The specification says what each column means; this page says where things are and how to use them.

Migrations

services/api/migrations/sql/, one SQL file per Alembic revision, applied by python -m elo_api.db.migrate as elo_owner (the Compose migrate service). B03's block is 0001-0019:

RevisionCreates
0001_schemas_opsSchemas ops, raw, ingest, core, ts, ref, fx, calc (and price, B52, 0200); ops.job, ops.job_run, ops.data_version (one row, version 0)
0002_refref.price_area (DK1, DK2), ref.grid_area, ref.code, ref.mp_type (seeded), ref.calendar_day (2015-2040), ref.gwp_set (AR5, KK2025), ref.method (LB-PA-125, LB-PA-200)
0003_ref_seedsThe 45 grid areas and the code lists of R1 §5
0004_coreingest.source_account, core.metering_point, core.mp_version, core.mp_geo
0005_rawraw.fetch, raw.fetch_item, raw.payload
0006_ingestExtension btree_gist (in schema ingest); ingest.pacer (one row) with ingest.reserve_start() and ingest.finish_call(); ingest.chunk with the exclusion constraint; ingest.mp_state, ingest.capture_import, ingest.dataset_state, ingest.unknown_field
0007_tsts.series, ts.reading with 144 month partitions (ts.reading_2020_01 … ts.reading_2031_12, no default), ts.day_load, ts.reading_change; ts.apply_day() and ts.observe_absence() as stubs that refused to run (their bodies are 0040's)
0008_fxfx.factor_hour, fx.factor_hour_history
0009_pace_settingingest.pace_setting (one row: the spacings, the owner's); ingest.pacer_clock(); ingest.reserve_start(kind) and ingest.finish_call(kind) replace 0006's functions, which took the spacings from the caller (B03v-01)
0010_ts_fx_alignmentThe alignment checks of ts.reading and fx.factor_hour on the exact stored instant (B03v-02); ts.reading.created_at (B03v-03)
0080_eds_loader_state (B11)Columns only (B11v): ingest.dataset_state.cooldown_level, in_flight, generated, observed_at; generated on fx.factor_hour and fx.factor_hour_history, filled from the raw.fetch.source of each row's fetch_id (a row without one fails the migration)
0040_merge_functions (B08a, block 0040-0059)The bodies of ts.apply_day() and ts.observe_absence(); ts.day_facts() and ts.day_line() (a day's summary and hash from its rows); ts.withdraw_day() (make withdraw-day) and ts.verify() (make verify); internal helpers ts.store_day_facts(), ts.withdraw_rows(), ts.withdraw_min_hours(); ts.set_withdraw_min_hours() (owner only, called by the migrate step to install ELO_WITHDRAW_MIN_HOURS). No table. See docs/readings.md
0100_emission (B12a, block 0100-0119)The view calc.v_emission_interval and the function calc.emission_matched(), the emission calculation of §9. No table: nothing derived is stored. See docs/emission.md
0120_api_queries (B15, block 0120-0139), parent 0020_master_dataThe building blocks of the named queries: calc.period_buckets, calc.emission_intervals (the emission view of one method, GWP set and basis), calc.consumption_buckets, calc.emission_buckets, calc.emission_matched_buckets, calc.series_intervals, calc.emission_series_intervals. Functions only, executable by elo_api only. No table. See docs/queries.md
0061_load_followups (B08b, block 0060-0079), parent 0120_api_queriesWhat the replay and the backfill job need: the table ingest.capture_held_back (every series-day whose captured content was held back as stale; metering point and dates only), the function ts.analyze_loaded() (ANALYZE of the tables a load fills, with the owner's rights) and the table ingest.analyze_owed (one row while that ANALYZE is owed). See docs/runner.md
0140_footprint (B12b, block 0140-0159), parent 0061_load_followupscalc.footprint(): the totals of Eloverblik's climate report for a period, a selection and one method, GWP set and basis, and the MP-hours they rest on (report.footprint, make validate). One function, executable by elo_api only. No table. See docs/queries.md and docs/validation.md
0141_emission_matched_plan (B12b, block 0140-0159), parent 0140_footprintcalc.emission_matched() (0100) planned without nested loops and without JIT, whatever the statistics (B15v2-07, B12bf). No table, no result changed. See docs/build/B12b-report.md
0160_daily_run (B09, block 0160-0179), parent 0141_emission_matched_planTwo columns: ingest.mp_state.access_failures (consecutive days on which the MP's item answered an access code; three end current access, CT-14) and access_failure_day (the local date of the last one counted: a second run on the same day adds nothing, B09v-02). No table. See docs/daily-run.md
0190_service_pace (B51, block 0190-0194), parent 0210_comparison_names (the head of main when B51 merged: the chain follows the parents, not the numbers)ingest.service_pace (one row, service = 3): one pace for every call to Energi Data Service, of every dataset (phase-2.md §2.2): next_start_at, cooldown_until, cooldown_level, in_flight, started with the latest deadlines, the highest level and a call in flight of ingest.dataset_state, whose four pace columns are no longer read (a comment on each says so). elo_api SELECT; elo_worker SELECT, UPDATE (no INSERT: the row exists). ingest.pace_setting.eds_spacing_s (B51f, B51v-05): the spacing of Energi Data Service, 60 by default, checked 1-3600, installed by migrate from ELO_EDS_SPACING_S as the owner; read by every process
0200_spot_prices (B52, block 0200-0209), parent 0225_comparison_periods (B55's, the head of main when B52 merged; the chain is … → 0210 → 0190 → 0212 → 0225 → 0200)Schema price; price.spot (PK price_area, interval_start; resolution 60 or 15, dataset 1 Elspotprices or 2 DayAheadPrices, dkk_per_mwh numeric(14,6) NOT NULL, eur_per_mwh NULL, retrieved_at, meta_updated_at, fetch_id, generated, extras) with the seam as a check (spot_seam: hourly rows of dataset 1 before 2025-09-30 22:00+00, quarters of dataset 2 from it) and spot_on_grid (the start a multiple of the resolution, on the exact instant); price.spot_history (PK price_area, interval_start, superseded_at; cause 1 changed, 2 vanished; the superseded row with its generated). elo_api SELECT on both; elo_worker SELECT, INSERT, UPDATE, DELETE on price.spot and SELECT, INSERT on the history. See docs/declarations.md, "The prices"
0215_grid_mix (B53, block 0215-0224), parent 0200_spot_prices (the head of the branch B53 was built on: the lead sets the parent again at the merge if another epic merged meanwhile)fx.mix_hour (PK price_area, hour_utc, connected_area, report_grp_code; share_ppm integer (NULL when the service delivers none) as delivered with its sign, share_mwh numeric(14,6), co2_emission_kg numeric(16,6), report_grp text the name as delivered, version 1-3 or NULL, retrieved_at, meta_updated_at, fetch_id, generated, extras; hour_utc on the hour to the microsecond). No history table (phase-2.md §2.4: the rows of an hour and price area are replaced as a set). No foreign key, no sign check and no NOT NULL on the code, the connected area, the share and the version (an hour with a NULL share or version is not complete): what the service delivers is stored and make status lists it. elo_api SELECT; elo_worker SELECT, INSERT, UPDATE, DELETE. See docs/declarations.md, "The grid's mix"
0216_mix_reference (B53), parent 0215_grid_mixref.mix_group (the eight groups of phase-2.md §3.3: sort, renewable_share numeric(3,2), nuclear), ref.mix_code (the 17 report group codes of R2 §2.2.4, each in one group) and the list connected_area of ref.code (11 codes). Seeds, data and not code; SELECT for elo_api and elo_worker
0285_accounts (B72, block 0285-0294), parent 0270_mix (set by the lead at the merge: B53, B67, B56 and B58 merged meanwhile; it was 0200_spot_prices when B72 branched)Several accounts (phase-2.md §6.3): core.company (PK company_id, name unique, created_at); ingest.source_account.company_id NOT NULL and a unique label; the existing account becomes env, of the company "Egen konto" (the worker renames it to ELO_COMPANY_NAME at its start when ELO_ACCOUNT_PARTY_KIND is 1); every writer of an account gives its company (no trigger, B72f). ingest.account_mp (PK account_id, mp_id; first_listed_at, last_listed_at, created_at): which account lists which point, filled with every point of the account, every status, and written by the worker's listing code (masterdata.Tree.register, in the list's transaction) for every point a list holds; a second lister's rows are B76's. No trigger and no function. elo_api SELECT on both; elo_worker SELECT, INSERT, UPDATE on both (UPDATE on core.company for its row locks) and DELETE on core.company (a company an account left empty)
0295_token_notices (B76, block 0295-0299), parent 0265_consumption_matched_export (set by the lead at the merge: B57 and B68 merged meanwhile; it was 0285_accounts when B76 branched)ingest.token_notice (PK notice_id; account_id nullable, REFERENCES ingest.source_account ON DELETE CASCADE; label of the label's form or NULL; kind, a reason's class; sentence, at most 600 characters; created_at): what the worker found at its start that make status says: a token file refused, a known account whose token file is gone, an access-token file that cannot be used, a stray of tokens/ (by its name alone). The worker deletes every row and writes its start's in the transaction that syncs the accounts; no token and nothing of a file's content is in it. An account with a row is not called with in that run (chunks.REQUESTABLE). Also B76, no migration: a second lister of a point writes its row of ingest.account_mp and nothing of core.metering_point (Registered.foreign). elo_api SELECT; elo_worker SELECT, INSERT, DELETE
0305_company_dimension (B74, block 0305-0309), parent 0295_token_notices (the lead sets it at the merge)No table. calc.root_dimensions() is replaced (CREATE OR REPLACE, the same signature and grants) with a ninth dimension per root, company: the id of the company (core.company.company_id, as text) of the account that owns the root (core.metering_point.account_id; ingest.source_account is read for company_id alone). It names no label, fingerprint or CVR number; the company's name is read by providers/dimensions.sql from core.company, which elo_api may SELECT (0285)
0315_mix_fossil_split (B78, block 0315-0319), parent 0305_company_dimensionNo table. ref.mix_group gains family text NOT NULL (the unit of step 2's rounding: the eight groups of B53) and nine rows: gas "Naturgas" (R04x) and coal_oil "Kul og olie" (R02, R05x, R06x) in the place of fossil, sort 7 and 8, family fossil; other sort 9. ref.mix_code moves the four codes. calc.mix_hours is dropped and created (two arrays more, group_sorts and group_family_sorts; the order of 0270) with its grants; calc.mix_buckets replaced (CREATE OR REPLACE, the same signature and grants) with step 2 by families (docs/mix.md). The seed of 0216 is not edited

| 0310_account_remove (B75, block 0310-0314), parent 0315_mix_fossil_split (set by the lead at the merge: B78 merged meanwhile; it was 0305_company_dimension when B75 branched) | No table. Three functions of make account-remove (phase-2.md §6.3), owned by elo_owner, executable by nobody else (PUBLIC revoked; neither elo_worker nor elo_api): ops.account_removal(label), what would go (the company and its number of accounts, the points and roots the account owns, the first and last day of their readings, the points another account lists too, the other accounts' points it lists); and ops.remove_account(label, account_id), the removal in the caller's one transaction: refuses a label not of the label's form ([a-z0-9][a-z0-9-]{0,30}, no eight digits in a row: the function matches no pattern on a label, B75f), env, a label that is no account, an account_id that is no longer the label's, a job's row locked by a claim and the advisory lock elo.ingest held by a call in flight (both held until the commit); then deletes the account's rows of every table that references ingest.source_account, core.metering_point, raw.fetch or ops.job, directly or through another (the list is in the migration, and tools/tests/test_b75_removal.py walks the catalogue's foreign keys and fails for a table it does not cover): the readings (ts.reading partition by partition: each partition is named in the answer with its rows, B75f2), day records, changes and series of its points; raw.payload and raw.fetch_item by the point and by the fetch's account; core.mp_version, core.mp_geo, ingest.chunk, ingest.mp_state, ingest.capture_held_back, ingest.account_mp (its listings and others' listings of its points); its points' and chunks' IDs in ingest.capture_import's maps; core.metering_point; its raw.fetch rows; ops.job whose payload names the account (account) or one of its points (any mp_id), never by its key, with their ops.job_run (another account's raw.fetch rows that such a run made keep their row and lose job_run_id, B75f); ingest.token_notice of the account or label and every notice of kind stray (the worker's next start writes those anew, B75f2); the account; its company when no account is left in it. Raises ops.data_version once; returns the rows deleted by table, once each (and the rows changed: ingest.capture_import, raw.fetch (run unset)). And ops.removal_statistics(tables), run by the command after the commit and its VACUUM (ANALYZE) of the tables the answer named (B75f2): ANALYZE ONLY of the partitioned parent of a partition named, and the planner's statistics of a table left empty cleared (pg_clear_attribute_stats: an ANALYZE of an empty table keeps the old values), so that pg_stats holds none of the account's values; NULL for every table of core, ingest, raw, ts and ops (a removal whose answer a kill took). A table that a later epic adds and that references an account, a point, a fetch or a job must be added to ops.remove_account (a revision of that epic's block replaces the function): until then the removal fails on its foreign key, or the test finds its rows | | 0311_removal_lock_timeout (B75f3, block 0310-0314), parent 0310_account_remove | No table. ALTER FUNCTION ops.remove_account(text, int) SET lock_timeout = '5s': the removal waits for a row lock 5 seconds at most, then fails with 55P03 (nothing changed), which the command answers with a refusal naming the row and the way out (B75r-10: another session holding a row of the account made it wait without an end). The function's body is 0310's. A revision that replaces ops.remove_account keeps SET lock_timeout = '5s' in its text (pg_get_functiondef gives it; tools/tests/test_b75f3_fixes.py fails without it) | | 0320_factor_dataset_te (B80, block 0320-0322), parent 0311_removal_lock_timeout (set by the lead at the merge: B75f3 merged meanwhile; it was 0310_account_remove when B80 branched) | No table, no column, no row rewritten. fx.factor_hour's check dataset = 1 (0008) becomes CHECK (dataset IN (1, 2)), constraint factor_hour_dataset_check: 1 is DeclarationGridEmission, 2 DeclarationTransmissionEmission (municipality-method.md §3.3). The key already carries the dataset, the history table has the column without a check, the privileges are as 0008 and 0010 gave them. Every SQL reader that names a dataset says dataset = 1, so every answer of phase 1 and 2 is what it was. No column of a foreign key is added: B75's catalogue walk is unchanged. See docs/declarations.md, "The transmission factors" | | 0323_municipal_share (B81, block 0323-0329), parent 0320_factor_dataset_te (the head of the branch B81 was built on; the lead sets it again at the merge) | ref.municipality (PK code char(3); name_da NULL, generated, created_at): the 98 codes of derived_grid-area-and-municipality-to-price-area_2026-08.json less 999, no name until the lead's ruling. fx.re_coverage_hour (PK municipality_code, hour_utc; municipality_code references ref.municipality; re_share_pct numeric(12,6), re_kwh_keep, consumption_kwh numeric(18,6), each NULL and as delivered, no check on the share's range; retrieved_at, meta_updated_at, fetch_id references raw.fetch, generated, extras; hour_utc on the hour). fx.re_coverage_hour_history (PK municipality_code, hour_utc, superseded_at; cause 1 changed, 2 vanished; fetch_id references raw.fetch). ingest.municipality_setting (one row, setting = 1; municipalities auto or ^[0-9]{3}(,[0-9]{3})*$, seeded auto). ingest.municipality_state (PK municipality_code referencing ref.municipality; state 0-3, reason 1-2 or NULL, wanted_since). ref.add_generated_municipality(char(3), text): SECURITY DEFINER, owned by elo_owner, executable by elo_worker alone; adds a generated row (the demo's 999 and 998), refuses a code of the reference and a database with a real share. elo_api SELECT on the five tables; elo_worker SELECT on ref.municipality and the setting, SELECT, INSERT, UPDATE, DELETE on fx.re_coverage_hour, SELECT, INSERT on its history (no DELETE: fx.forget_municipality is B92's, the owner's), SELECT, INSERT, UPDATE on the state. The two fx tables follow B75f3's rule for a column that holds a fetch's id (a foreign key to raw.fetch, NO ACTION): B75's catalogue walk reaches them through raw.fetch, and they stand in its list of tables that need no DELETE (NO_DELETE of tools/tests/test_b75f3_fixes.py, with the reason of the other figures of Energi Data Service) until B92 names them in ops.remove_account (municipality-method.md §3.2). See docs/declarations.md, "The municipal share" | | 0375_method_default (B93, block 0375-0379), parent 0323_municipal_share (set by the lead at the merge: B75f3, B80 and B81 merged meanwhile; it was 0310_account_remove when B93 branched) | No table. ref.method.is_default boolean NOT NULL DEFAULT false, true on LB-PA-125 (the method a request without m is answered by, and the first of meta.context's methods); a unique partial index method_one_default (at most one default) and a check method_default_is_available (it is an available method). migrate moves the flag as the owner at every run from ELO_DEFAULT_METHOD (elo_api.db.migrate.install_settings; a code that is not an available method refuses the start and installs nothing of that run); elo_api and elo_worker have SELECT only, as on the rest of ref.method. No reference to an account, a point, a series, a fetch or a job: nothing for make account-remove's walk. See docs/queries.md | | 0335_municipal_emission (B83, block 0335-0344), parent 0375_method_default (set by the lead at the merge: B93 merged meanwhile; it was 0323_municipal_share when B83 branched) | No table, no column. ref.method gains rows 3 LB-MU-125 (geography municipality, allocation 1, available) and 4 LB-MU-200 (allocation 2, reserved). New function calc.mp_municipality(int[]) (SQL, STABLE, inlined): per E17 root the usable code of its current master-data version and whether ingest.municipality_setting wants it; elo_api executes it, elo_worker and PUBLIC may not. calc.v_emission_interval is replaced by the union of two new views, calc.v_emission_interval_price_area (0100's joins) and calc.v_emission_interval_municipal, with five columns after its old ones (re_share_pct, local_kwh, grid_kwh, pending_reason, no_municipality): the method's dataset of fx.factor_hour and, under a municipal method, the share of fx.re_coverage_hour (docs/emission.md). two new functions read one branch each, calc.emission_intervals_price_area and calc.emission_intervals_municipal (calc.emission_intervals is unchanged and reads the union), calc.emission_matched is replaced with the same signature, and calc.emission_buckets, calc.footprint, calc.emission_series_intervals and calc.weekday_hour_cells are dropped and created again with the same text but for noMunicipality apart from pending and new columns after their old ones; their grants as before. Under the price-area methods every old column answers as before (the test across the migration). Nothing is stored | | 0345_emission_reason (B84, block 0345-0349), parent 0335_municipal_emission (the head of the lead's rehearsal branch the epic was built on; the lead sets it again at the merge) | No table, no column, nothing stored. New function calc.emission_reason(boolean, boolean, numeric, numeric, numeric, numeric, numeric) (SQL, IMMUTABLE): why no hour is in an emission figure, as one place for the cards, G01's two queries, the footprint and the runner. Under a price-area method phase 1's rule (no_price_area when every reading lacks a price area, else no_factor); under a municipal method the cause that holds the largest part of the consumption, a tie in the order no_price_area, no_municipality, municipality_not_loaded, no_local_share, no_factor (docs/queries.md, "The municipal split in the queries"). elo_api executes it; elo_worker and PUBLIC may not. No reference to an account, a point, a series, a fetch or a job: nothing for make account-remove's walk | | 0346_emission_reason_hours (B84f, block 0345-0349), parent 0345_emission_reason | No table, no column, nothing stored. New function calc.emission_reason_hours(int[], date, date, int, text, text) (SQL, STABLE): the reason of a selection or bucket with no energy under a municipal method, from the hours' causes: calc.emission_reason over the hour counts of calc.footprint (B84v-01: with every reading 0,000 kWh no cause holds an amount above zero). Called only where the energy is 0. elo_api executes it; elo_worker and PUBLIC may not. No reference to an account, a point, a series, a fetch or a job: nothing for make account-remove's walk | | 0330_mix_dataset (B82, block 0330-0334), parent 0346_emission_reason_hours | No table. fx.mix_hour gains dataset smallint NOT NULL DEFAULT 1 with the check mix_hour_dataset_check (dataset IN (1, 2): 1 DeclarationGridmix, 2 DeclarationTransmissionGridmix), and its primary key becomes (dataset, price_area, hour_utc, connected_area, report_grp_code): every stored row is dataset 1 (a constant default is no rewrite), the key is built once over the table (about 3 million rows on the owner's stack; B82's report says how long it took). calc.mix_hours, the only SQL reader of the table, is replaced (CREATE OR REPLACE, same signature, return type and grants) with m.dataset = 1 in both its reads; B87 gives it the parameter. No privilege changes (elo_worker keeps SELECT, INSERT, UPDATE, DELETE, elo_api SELECT). No reference to an account, a point, a series, a fetch or a job is added: nothing for make account-remove's walk. Every answer of phase 1 and 2 is what it was, with TM loaded beside. See docs/declarations.md, "The transmission mix" | | 0370_municipality_list (B92, block 0370-0374), parent 0330_mix_dataset (set by the lead at the merge: B82 merged beside it; it was 0346_emission_reason_hours when B92 branched) | No table. ingest.municipality_setting.names boolean NOT NULL DEFAULT false (ELO_MUNICIPALITY_NAMES, §4): installed with municipalities by migrate as the owner at every run (elo_api.db.migrate.install_settings, which stores the list normalised: sorted, each code once, no space, or auto; a changed value raises ops.data_version); elo_api and elo_worker SELECT as before. New function fx.forget_municipality(char(3)) (PL/pgSQL, SECURITY DEFINER, search_path pinned), owned by elo_owner, executable by elo_worker alone (PUBLIC revoked; elo_api may not): refuses (P0001, no code in the message) a code whose ingest.municipality_state row is not state 0 or is absent; deletes that municipality's rows of fx.re_coverage_hour_history and fx.re_coverage_hour and nothing else; raises ops.data_version when it deleted a row; returns the rows deleted. Called by elo_worker.eds.recoverage.refresh for every code at state 0. The worker's role gains no DELETE. ops.remove_account(text, int) replaced (CREATE OR REPLACE, its text carries SET lock_timeout = '5s', every clause of 0310 word for word): under auto it reads the usable codes of the account's E17 roots before their master data goes and, after its points are gone, deletes the rows of fx.re_coverage_hour_history, fx.re_coverage_hour and ingest.municipality_state of each code no remaining E17 root of any account has; under a list none. Each of the three tables is named once in the answer, with 0 rows too; tools/tests/b75_mutations.py reads this file now. ops.removal_statistics(text[]) replaced: NULL covers the schema fx too (municipality-method.md §3.2, §4). The two fx tables are named by the removal now and are taken out of NO_DELETE of tools/tests/test_b75f3_fixes.py (B75f3's rule for a column that holds a fetch's id holds as before: their key to raw.fetch is NO ACTION, and RE's fetches carry no account). B92f: new function ingest.wanted_municipalities() (SQL, STABLE; elo_worker executes it, elo_api and PUBLIC may not): the codes wanted now, under auto those of the current master data of E17 roots, under a list the listed codes that are rows of ref.municipality; fx.forget_municipality also refuses a code it gives (and holds the setting's row FOR SHARE), and ops.remove_account keeps a code it gives; ops.remove_account refuses (elo-remove: share) while the advisory lock elo.eds.recoverage is held (the municipal share's jobs hold it for their whole run); both functions delete in one order: the state row, the history, the table | | 0350_municipal_sources (B87, block 0350-0359), parent 0370_municipality_list | No table, nothing stored. ref.mix_group gains municipal boolean NOT NULL DEFAULT false and a tenth row, local "Kommunal vedvarende energi" (sort 0, renewable share 1, not nuclear, family local, municipal true): a part only under the municipal split, so by price area the nine groups stay nine. calc.mix_hours gains p_dataset smallint DEFAULT 1 (dropped and created: 1 DeclarationGridmix, what B82's text read; 2 DeclarationTransmissionGridmix). New function calc.municipality_parts(int[]) → (mp_id, part, label): each municipality of a selection numbered m1, m2, … by the lowest mp_id of its roots, and its label only with ingest.municipality_setting.names on and every root of the selection in it unprotected (N4); elo_api EXECUTE. calc.mix_buckets gains p_geo text DEFAULT 'price_area' and the part municipality, and eleven columns after the old ones (part_own_kwh, part_own_share; per side and period the energy of noMunicipality, municipality_not_loaded and no_local_share; NULL under the price area's split); dropped and created, grants given again. Every answer under price_area is what it was (docs/mix.md, municipality-method.md §2.4) | | 0380_pace_learns (B95, block 0380-0384), parent 0350_municipal_sources (set by the lead at the merge) | No table. ingest.service_pace gains what the pace has learned from the service's 429s (elo_worker.eds.pace): learned_spacing_s integer (NULL, or 1-3600: the distance between the starts of two calls the service was seen to accept; the pace caps what it learns at 900 s and never goes below ingest.pace_setting.eds_spacing_s), learned_since timestamptz (when it last changed), last_accepted_start timestamptz (the start of the last call the service answered without a refusal), accepted_run integer NOT NULL DEFAULT 0 (accepted calls since the learned spacing changed), probe_run integer NOT NULL DEFAULT 10 (the run before the next step down, doubled to at most 160 after a refused step), probing boolean NOT NULL DEFAULT false and held_spacing_s integer (while probing, the spacing a refused step is put back to). No new grant: elo_worker has SELECT, UPDATE on the row (0190), elo_api SELECT. No reference to an account, a point, a series or a fetch: nothing for make account-remove's walk. See docs/operations.md section 2 | | 0390_state_home (B101, block 0390-0394), parent 0380_pace_learns (set by the lead at the merge) | ingest.state_home (PK one, a boolean that is true: one row; kind host or volume; since; created_at): where this install's state is (docs/architecture/packaging-and-setup.md §2.4, "The state has one home"). The migration writes host for a database that already holds an install (a row of ingest.source_account, raw.fetch, ops.job or ingest.capture_import); a database made new by the same run of migrate gets no row, and its first worker writes its own kind (host from the repository install's bind, volume from the packaged install). A worker whose kind is not the row's takes no lock, makes no call and marks no account absent. The move (B104: admin import-state, the owner's role: the worker's role may select and insert the row and cannot change it) and admin adopt-state after a restore set volume. Also B101, no migration: two kinds of ingest.token_notice that make status prints: state-home (account and label NULL; a packaged worker waits on a host row; deleted when the row is its kind) and removal-pending (a journal account-remove.<label> is in the state directory; the worker does not make that account; gone at the first start after the removal finished). elo_api SELECT; elo_worker SELECT, INSERT | | 0395_product_version (B103, block 0395-0399), parent 0441_emission_by_hour (set by the lead at the merge) | ops.product_version (PK one, a boolean that is true: one row; version X.Y.Z[+build]; major, minor, patch; since; created_at): the highest version of the product that has started on this database (docs/architecture/packaging-and-setup.md §2.6). Written by migrate as the owner at the end of a start that went through (elo_api.db.migrate.record_version: the row is raised to a higher version and left at a lower patch; a development version, 0.0.0 or 0.0.0+<commit>, is neither compared nor recorded), never by a migration. migrate reads the row and migration.alembic_version before it touches the roles or any migration, read only, and refuses in one line (migrate refused the start: …, both versions, "Nothing was changed") a revision its chain does not hold or a row of a later minor. No grant to elo_api or elo_worker (the owner's alone; test_storage lists the table under ops and the grants as before). A database that an earlier release started has no row until the first start of a release that holds this migration | | 0460_map_positions (K2, block 0460-0469), parent 0395_product_version (the head when K2 branched; the lead sets it at the merge) | ref.postcode_point (PK postcode four digits; name; x, y integer EPSG:25832 metres inside Denmark's extent; created_at): the midpoint of the land of each geographic postcode of DAGI, loaded by migrate at every start from the outline bundle (elo_api.db.postcodes, K2f): the repository holds no postcode table. core.mp_position (PK mp_id referencing core.metering_point; x, y as above; generated (the demo's); created_at): the exact position of a point, the only table that holds a coordinate of one; the owner's alone (elo_api SELECT; the worker no right). calc.mp_positions() (SQL, STABLE, elo_api executes): every metering point with precision_tag exact, postcode or none, x, y and the reason of a none (protected, no_master_data, no_postcode); placed only when the current version has protected_name IS FALSE AND protected_address IS FALSE (N4). core.replace_positions(text[], int[], int[], boolean) (the owner's; PUBLIC revoked): the owner's file as the whole list of its kind (generated or not), counts back, ops.data_version raised when a row changed; refuses a GSRN twice (elo-positions: twice). Trigger mp_version_forget_protected_position (AFTER INSERT OR UPDATE of the protection flags and observed_to, core.forget_protected_position(), SECURITY DEFINER): a current version that is not open deletes the point's position. ops.remove_account replaced: every clause of 0431, SET lock_timeout = '5s', and core.mp_position of the account's points deleted before the points, named once (tools/tests/b75_mutations.py reads this file now, D26). See docs/maps.md | | 0462_positions_lock (K2f3), parent 0460_map_positions | core.replace_positions replaced, its work 0460's (K2v-02, K2v-01). It locks the given points' current versions FOR SHARE in mp_id order before it reads their protection, so a version the worker is writing makes it wait, and the import makes the worker wait (whose trigger then deletes the coordinate). SET lock_timeout = '5s'. Any error inside it is raised again with its SQLSTATE as elo-positions: not stored (<SQLSTATE>), without the detail that could quote a row; twice and lengths as before. See docs/maps.md | | 0470_map_background (K3, block 0470-0479), parent 0462_positions_lock | ops.map_background_area (PK area: a municipality code of three digits or demo; x0, y0, x1, y1 integer EPSG:25832 metres inside 300 000-1 000 000, 5 950 000-6 500 000; zoom_min, zoom_max 0-20; layer; fetched_at; created_at): the rectangles of the map background make map-background fetched completely, replaced as a whole by the host's record (one transaction as the owner); the owner's alone (no grant). ops.map_background_state() (SQL, STABLE, SECURITY DEFINER, elo_api and elo_worker execute): counts alone, areas, fetched_at, placed, outside (placed points in no rectangle), coarse (exact points only in rectangles to zoom 7 or less), over calc.mp_positions(), which the worker may not run itself; read by make status. The tiles are in the volume map-tiles, never in the database. See docs/maps.md §5 |

Ids and the removal (B75f3, B75r-08). A column that holds an account's, a metering point's, a series', a fetch's, a job's or a run's id references its table by a foreign key (ingest.source_account, core.metering_point, ts.series, raw.fetch, ops.job, ops.job_run): a database cannot tell that a plain integer is an account, so an id kept without its key is found by no walk and no search, and make account-remove would leave it. The columns' names hold the rule: account_id, mp_id, series_id, fetch_id, job_id, run_id, and any name that ends so (job_run_id, last_fetch_id, parent_mp_id …), without such a key fail tools/tests/test_b75f3_fixes.py::test_s3_every_id_column_references_its_table; today's exceptions are the six tables' own keys and raw.payload.fetch_id (its key (fetch_id, item_no) references raw.fetch_item, whose fetch_id references raw.fetch), each with its reason in the test. And every table that references one of those six tables, directly or through another table, is either named by ops.remove_account (a DELETE or an UPDATE of it) or listed in that test's NO_DELETE with the reason it needs none (today the five tables of Energi Data Service's figures, fx.* and price.*, whose key to raw.fetch is NO ACTION): a new table fails ::test_s1_every_table_that_reaches_an_account_is_the_removals_or_excused as soon as its migration has run, empty or not, until the removal names it.

A later epic adds a revision in its own block with down_revision set to the head it starts from; the lead fixes the parent at the merge. Nothing outside B03 creates a table (§13.3).

Who may do what

Every grant is explicit; services/api/tests/test_storage.py::test_the_grants_are_exactly_those_of_the_roles holds the whole matrix.

RoleTables
elo_ownerOwns everything; runs the migrations; the two writing functions of ts run with its rights (SECURITY DEFINER)
elo_apiSELECT on ref, core, ingest, ts, fx, price, the four fact tables and ops.data_version. Nothing in raw, nothing in ops.job*, no function that writes
elo_workerSELECT, INSERT, UPDATE on ops.job*, raw.fetch, raw.fetch_item, ingest.*, core.*, ts.series; INSERT (no UPDATE) on raw.payload; UPDATE (no INSERT) on ops.data_version, ingest.pacer and ingest.service_pace (B51); only SELECT on ingest.pace_setting; DELETE only on fx.factor_hour, fx.mix_hour, price.spot, core.company (B72) and ingest.token_notice (B76); only SELECT, INSERT on ingest.state_home (B101: a new database's row); INSERT (no UPDATE) on price.spot_history. Only SELECT on ts.reading, ts.day_load, ts.reading_change: readings are written through ts.apply_day() and ts.observe_absence(). EXECUTE on those two, on the read-only ts.day_facts() and ts.day_line() (also elo_api), on the pacer's two functions and on ingest.pacer_clock(). ts.withdraw_day() and ts.verify() are the owner's: a person runs them (make withdraw-day, make verify)

core.metering_point and ingest.chunk take their ID from an identity that allows an explicit value, and the worker may call nextval() on their sequences: a root metering point has root_mp_id = mp_id, a root chunk lineage_id = chunk_id, so the ID is taken first (SELECT nextval('core.metering_point_mp_id_seq')).

Constraints worth knowing

The stored facts (B130)

Revisions 0430_fact_tables_marks (parent 0390_state_home, set by the lead at the merge) and 0431_removal_facts add schema fact: day, emission_day, stale, and singleton state. See facts.md for the grain, checks, masks, version and statement triggers. elo_api SELECTs all four; elo_worker has no table rights. Only the owner writes them. A new reading partition calls fact.arm_partition(regclass).

0431 replaces ops.remove_account with all of 0370's clauses and SET lock_timeout = '5s'. It tries elo.facts fifth; a held lock refuses with “a worker recomputes the stored facts; nothing changed: try again in a minute, or stop the worker (make down) and run make account-remove again”. It deletes fact.stale, fact.emission_day, fact.day after inputs whose triggers mark and before core.metering_point. Each is named once, including zero counts. The NULL branch of ops.removal_statistics includes fact as well as core, ingest, raw, ts, ops, fx. tools/tests/b75_mutations.py mutates 0431 for the removal; W01–W03 and F01 still target 0370's municipal helper functions. B75's foreign-key walk reaches all three point references.

The pacer's functions (§5.2)

SELECT pg_advisory_lock(hashtextextended('elo.ingest', 0));       -- R9, held until the completion commits
SELECT ingest.reserve_start(1::smallint);                         -- transaction A
-- wait until the returned start by ingest.pacer_clock(), send, receive
SELECT ingest.finish_call(1::smallint);                           -- transaction B
SELECT pg_advisory_unlock(hashtextextended('elo.ingest', 0));

Call kinds are those of B05's CallKind: 1 data, 2 token, 3 health. No caller chooses a spacing (B03v-01): both functions read them from the one row of ingest.pace_setting, owned by elo_owner and readable by the worker and the API: calls_per_minute (ELO_CALLS_PER_MINUTE, 60 by default, checked 1-100, so the ordinary spacing 60 / calls_per_minute is never below 0.6 s) and token_spacing_s (ELO_TOKEN_SPACING_S, 60 by default, checked at least 30: two token calls a minute). Reservation, completion and recovery therefore always use the same values. The row also holds eds_spacing_s (ELO_EDS_SPACING_S, 60 by default, checked 1-3600): the least seconds between two starts of calls to Energi Data Service, which the worker's ingest.service_pace reads (B51v-05). Only the owner changes them (UPDATE ingest.pace_setting SET ..., as the migrations' role); nothing in B03 copies the environment variables into the row. reserve_start locks the one ingest.pacer row, returns greatest(ingest.pacer_clock(), next_start_at, cooldown_until, token_next_start_at for a token call), pushes the deadlines past it and sets in_flight_kind; finish_call spaces the deadlines from the completion and clears in_flight_kind. Recovery at start (step 0): if in_flight_kind is set, call finish_call(in_flight_kind). The cooldown columns are set by the caller's own UPDATE (the response table of §5.2), always with greatest(). The advisory key hashtextextended('elo.ingest', 0) is what the tests use; B07's store should use the same.

ingest.pacer_clock() is clock_timestamp(), the database clock, in a function of the owner's. A caller waits by it too. A test that must wait out a 60 s token spacing replaces it, as the owner of its own test database, with a clock that runs faster (services/worker/tests/test_pacer.py::fast_clock): the time is injected, never a looser limit. The worker can call it and cannot replace it.

The recorder (§3.1, §7)

elo_worker.ingest.recorder.Recorder(connection) writes raw.* in the caller's transaction and never commits:

MethodWhenWrites
begin(source=…, endpoint=…, request_key=…, requested_at=…, …) -> fetch_idTransaction A, before the callraw.fetch with http_status NULL
complete(fetch_id, record: FetchRecord)Transaction BThe response's status, times, hash and size of the body, codes
item(fetch_id, item_no, item: ItemResult, outcome=None, dataset_window=None, content_sha256=None)Transaction Braw.fetch_item; mp_id from the item's ID; outcome defaults to the source's (1-6), the merge passes 7-9
count(fetch_id, item_no, DayCounts(...))After the merge applied the item's daysThe six day counters and three row counters
payload(fetch_id, item_no, body)For items that wrote, changed or withdrew something, and parse errorsraw.payload: the allowlisted body, projected, as zstd JSON (encoding 1)

The projection. Before a body, a request key, a dataset window or a correlation ID is stored, every metering point ID in it is replaced by its mp_id from core.metering_point: a whole value becomes the integer mp_id (the payload models still parse it), an ID inside a longer string or a key becomes the digits of the mp_id. Any run of exactly 18 digits that core.metering_point does not hold is refused with UnmappedMeteringPointId, whose message says where and never what: register the metering points of a response before recording it. The body of a token response is refused. decode_body() reads a stored body back.

The job queue

elo_worker.queue: enqueue(connection, kind, payload, dedup_key=None, max_attempts=3) queues in the caller's transaction; the worker runs run_once(PostgresQueue(engine), handlers) until nothing is due, then waits ELO_WORKER_POLL_SECONDS. A claim locks the job's row FOR NO KEY UPDATE SKIP LOCKED and commits the attempt in its own transaction before the handler runs; the handler gets the claim's connection, its work runs in a savepoint, and the job is marked done in the same transaction. So the effect and the acknowledgement commit together: a worker killed mid-job leaves the job queued and its effect rolled back; the next claim records the dead attempt as {"abandoned": true} and runs the job again; a job whose attempts are used up is marked failed without running. A failure records the exception's class name only and is retried after 30 s × attempt.

Kilde: docs/storage.md i løsningens repository.