Eloverblik

Dokumentation · Data og kilder

Readings: the merge (B08a)

How a time series response becomes stored readings: docs/architecture/phase-1.md §4 is the specification; this page says where each part is and how to use it. The guarantees: one value per series and instant, a stale response never over a newer one, a withdrawn value never left behind by accident, and every change after a day's first load logged.

PartWhere
Validation V1–V6 (pure)elo_core.readings.validate
The merge transaction, steps 1–4 of §4.3elo_worker.ingest.merge.merge
The two writers, steps A1–A5 and B1–B6ts.apply_day(), ts.observe_absence() (migration 0040_merge_functions)
A day's summary and hash from its rowsts.day_facts(), used by every writer and by make verify
Days not confirmed, and whyelo_worker.ingest.confirmation.unconfirmed_days
Series refused for their unit or resolutionelo_worker.ingest.confirmation.unsupported_series
What is kept of an item's bodyelo_core.readings.stored_body
ELO_WITHDRAW_MIN_HOURSinstalled by python -m elo_api.db.migrate (ts.set_withdraw_min_hours())
make verify, make withdraw-daydeploy/sql/verify.sql, deploy/sql/withdraw-day.sql; ts.verify(), ts.withdraw_day()

Applying a response

The caller (the backfill job, the daily run, the replay: B08b, B09) holds the session advisory lock elo.ingest (pg_advisory_lock(hashtextextended('elo.ingest', 0))) from before transaction A, writes the raw.fetch row in transaction A (Recorder.begin) and commits, sends, and then in transaction B:

# The live worker (B07's PostgresPaceStore): the client calls the observer's `completed` inside
# the store's transaction B, on the store's connection, which holds the session lock.
def completed(self, fetch, response):  # a CallObserver of elo_sources.eloverblik
    merge(store.connection, fetch_id, response, request)


# the store then commits the merge with ingest.finish_call: the whole response, or nothing

The merge must run on the store's connection (PostgresPaceStore.connection): the merge takes the transaction lock on the same key, which the store's own session already holds; on any other connection it would wait for that session, which is waiting for the merge (a deadlock). A source that is not the live client (the demo and replay sources) has no pacer: its caller runs transaction B on a connection of its own (elo_worker.eloverblik.observer.SourceFetcher shows the shape for master data).

request says what the response answers, and so what step 3 updates:

requestStep 3live
ChunkRequest(plan.Request(...))The chunks, through elo_core.plan.apply_response (§6.2 outcome table, edge search, readable anchor); new chunks take their IDs from ingest.chunk_chunk_id_seq and are written after the updates (C3); an invalid ID sets the MP's status 4true
DailyRequest(date_from, date_to)ingest.mp_state, §6.5 step 4 (B09): on 10000 daily_ok_through = the local day of the request, daily_failures = 0, access_failures = 0, access_failure_day NULL, last_daily_ok_at, and a suspension ends (current_access, status 1); otherwise daily_failures + 1 and last_daily_code, and an access code adds a day to access_failures when the request's local day is later than access_failure_day (any other answer sets both to 0/NULL; no answer leaves them) whose third day in a row ends current_access (status 3). A 429 counts as nothing. docs/daily-run.mdtrue
ReplayRequest(date_from, date_to)Nothing (§6.4). Only for raw.fetch.source = 8; the merge refuses a mismatchfalse

merge(…, now=…) (B08b) is the instant the planner reckons chunk waits from for a ChunkRequest (next_try_at, closed_at); by default the database's now(). The runner passes the clock it decides what is due on (docs/runner.md).

The window of the request is what V4 checks a period against. The response time t is read from raw.fetch.requested_at, never taken from the response object.

merge also takes the transaction advisory lock on the same key, so a second process that applies a response waits for the worker's transaction (R9). It returns Merged: per MP the item numbers, the verdict (Delivery or Refusal) and the result of every series-day.

Validation

Each MP's items in a response are validated together; the first check of the table that fails gives every item of the MP its outcome, and nothing of the MP is applied:

CheckOutcome
V1 an item not 10000, or without a document or TimeSeriesThe item's own (2 no data, 3 outside, 4 permanent, 5 retry later), or 6
V2 a unit other than KWH, MWH7
V3 a resolution other than PT15M, PT1H9 (also a P1M or PXD period beside a good one: UT-06)
V4 a period that is not exactly one local day inside the window; a series without businessType, or with one outside its code list (A01, A04, A64, R1 §5.6)6
V5 a position outside 1 … day length ÷ resolution, repeated or missing; a quality outside A01–A05; no quantity without A02; more than three decimals6
V6 two representations of one series-day (items or periods) with another resolution or other points6

A period whose Point array is absent, null or empty is not delivered: it neither replaces a day nor conflicts with another representation. Identical representations are one delivered day: ts.apply_day runs once for it. Quantities are converted to kWh exactly (MWH × 1 000) and never rounded.

An item whose every counted day was stale gets outcome 8. raw.payload keeps the body of an item that wrote or withdrew a day, and of a parse error; and of an item refused for an unsupported unit or resolution (7, 9), so that make status can name the series (§4.5).

No item keeps anything unchecked, accepted or refused (B08av-01, B08av-07). The allowlist keeps fields, not values. V1–V6 never read some fields (curveType, the series mRID, codingScheme), so even an accepted item may carry upstream free text there, and V1–V6 stop at the first failure, so any value of a refused item may be free text. Every stored body is therefore stored_body(body, outcome): a leaf survives only in the form its key allows, and anything else is dropped (an array entry becomes null):

FieldKept whenCode list
businessTypeA01, A04, A64Closed (R1 §5.6): any other value fails V4 with 6, so it never becomes ts.series.business_type
out_Quantity.qualityA01–A05Closed: any other value fails V5 with 6
curveType, codingSchemethe shape of a code, ^[A-Z][0-9]{2}$Open: the specification has none (R1 documents one value each, A01 and A10)
measurement_Unit.nameup to three capitals or digitsOpen: an unknown unit has its own outcome, 7
resolutionsuch as PT1H, P1M, PXDOpen: an unknown resolution has its own outcome, 9
position, errorCode; out_Quantity.quantityan integer; a decimal–
createdDateTime, start, enda UTC instant–
id, mRID, MarketEvaluationPoint.mRID.namean 18-digit metering point ID, which the recorder then replaces by its mp_id–

An accepted item (1, 8) and a parse error (6) keep their points; an unsupported unit or resolution (7, 9) keeps only each series' business type, unit, and its periods' resolution and bounds.

The series row (ts.series) is created by the first response that delivers a day of it, never by one with only empty periods. Its unit (source_unit, to_kwh) follows the watermark like every column a response writes (B08av-05): a response changes it only if its t is newer than the watermark of every stored day of the series. A response that is stale on any day of the series therefore cannot change it.

The two functions

Both lock the ts.day_load row of the series-day first. Their results and the item counter each goes to (N7):

ResultStepCounter
loadedA3: no row yetdays_written
confirmedA4: the same content hash; only the watermark moves and absent_since is cleareddays_confirmed
changedA5: the day replaced as a set; one ts.reading_change row per interval that differs, deletions first, then changed intervals, then insertions; all of them when the resolution differsdays_written
staleA2, B2: t not after the watermarkdays_stale
nothingB1: no row, or no readings; B3: a replayed absence–
markedB4: the first live absence; absent_since = tdays_marked
notedB5: a live absence less than 20 hours after absent_sincedays_noted
withdrawnB6: a second live absence at least 20 hours later; the readings deleted and loggeddays_withdrawn

The row counters (rows_inserted, rows_changed, rows_deleted) are the points of a loaded day and the change rows of a changed or withdrawn one. ops.data_version rises once for a response in which any day was neither stale nor nothing.

ts.apply_day(series_id, local_date, resolution, points, t, fetch_id) takes points as a JSON array of {"start": "<UTC instant>", "quantity": "<kWh>" | null, "quality": 1-5}. Although the merge has validated them, it refuses (SQLSTATE 22023) a point outside the day, off its resolution, repeated, with a fourth decimal or without a quantity and not A02, and an empty array: it is the only writer, so R1 is a property of the database.

The content hash h is the SHA-256 over one line per point, sorted by start: <start, YYYY-MM-DDTHH:MI:SSZ>,<resolution in minutes>,<kWh with three decimals, empty for none>,<quality 1-5>\n. The empty day hashes the empty string. The summary columns and content_sha256 of ts.day_load are never taken from the delivery: after every write they are read back from the stored rows (ts.day_facts), so R5 holds by construction and make verify checks the same computation.

ELO_WITHDRAW_MIN_HOURS (§1.3; 20 hours by default) is read by step B5 as ts.withdraw_min_hours(), a function of the owner: the worker cannot shorten the interval of R4 (B08av-02). The setting is an environment variable of the Compose migrate service (deploy/compose.yaml; put it in .env), which runs as elo_owner at every make up: python -m elo_api.db.migrate refuses anything but a positive, finite number of hours before it changes anything, and installs the value, or 20 when the variable is unset, with ts.set_withdraw_min_hours(). Only the owner may call that, or replace the function.

Days not confirmed

unconfirmed_days(connection, mp_id) lists the stored days that the latest attempted daily request did not observe (inside last_daily_date_from … last_daily_date_to, watermark older than last_daily_requested_at), with the reason verification_failed (and the code, e.g. 30015) or not_delivered, and apart from them, with observed_absent and the time, every day with absent_since set. make status (B09) and D1 (B16b) show them. Transaction A of the daily request must record the attempted window (§6.5 step 3), whatever the outcome.

The reason is read from every item of the MP in that attempt (B08av-04): not_delivered only if the response was HTTP 200 and every item passed V1–V6 (final outcome 1 or 8); otherwise verification_failed, with code the documented code of the first item, in response order, that did not answer 10000 (or the request's own), None when all answered 10000 and V2–V6 refused them, and outcome the refusal's outcome (6 for a conflicting second delivery of the day).

unsupported_series(connection, mp_id) lists, from the MP's latest response refused with outcome 7 or 9, each offending series as (business type, unit, resolution, outcome, requested_at): what make status lists for §4.5. Whether the MP has delivered since is the caller's comparison.

The two commands

Both run in the running stack's PostgreSQL, which is not published on the host, through docker compose exec postgres psql, as elo_owner.

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