Dokumentation · Beregningerne
Stored day facts
B130 installs the tables, invalidation marks and version checks of
architecture/stored-facts.md v1.2. B131 supplies the maker and refresh; later epics supply readers.
The existing calculation functions remain the reference.
fact.day has one row per E17 root and Copenhagen local date. It holds consumption cell masks
and cost totals. fact.emission_day adds method and status (0–7) to that key, with unrounded
gas totals, estimated amounts, municipal energy and provenance. Numeric sums have no fixed
scale. Masks use 25 bits: clock hours 0–23, and bit 24 for the second 02:00 in autumn.
A row of fact.stale makes a root-day stale. Each input change and its mark commit together.
The maker must never assume that a marked day still has readings or is still a root: withdrawals,
demotions and moved series must remove obsolete facts too. fact.days_of includes stored day
summaries and existing fact.day rows. Renewing a mark assigns a new sequence value and clears
its failure. Refresh must delete only the (mp_id, local_date, seq) it processed.
Statement triggers use transition tables on every input and every reading partition. UPDATE
triggers compare the keys and calculation columns; confirmations, unchanged re-pulls and metadata
changes mark nothing. PostgreSQL disallows a column list with transition tables. TRUNCATE marks
all root-days. New reading partitions must call fact.arm_partition(regclass); writes through
the parent are covered by its triggers as well. Any ATTACH PARTITION, DETACH PARTITION, or
DROP of a ts.reading partition changes the readings without a trigger event and must be
followed by SELECT fact.mark_all() in the same transaction; no current writer does any of the
three.
fact.version() hashes the definitions of functions and views in calc and fact, and the
Copenhagen day lengths for 2015–2040. migrate.upgrade() invokes fact.check_version() after
migrating: a different hash increments fact.state.version and marks every root-day. B131 must
call the same check at refresh. Readers must accept only rows of the current version.
ELO_FACTS_LIVE=on is installed into fact.state.live by migrate.install_settings at every
start. It defaults to off; shell settings override .env.local. Later readers use this flag
to compute every day from readings. Changing the flag marks nothing.
Only the owner writes fact tables. The API can SELECT all four tables; the worker has no table rights and will use the refresh and status functions. Trigger functions run as the owner with a pinned search path and no PUBLIC execution rights.
Account removal tries the session lane's elo.facts advisory lock fifth, refusing while refresh
runs. It removes marks, emission facts and day facts after triggering input deletes and before
metering points, names each table once even when empty, and clears their planner statistics.
The maker and the store (B131)
fact.make_day(mp_ids, days, with_cost) and fact.make_emission_day(mp_ids, days, method_id)
return the rows of fact.day and fact.emission_day for the given root-days (the two arrays are
pairs). A pair whose point is no E17 root, or that has no stored interval of the root's own series,
returns nothing. Without the cost, the cost columns, the interval counts and p_cells are NULL and
no price is read. A NULL method means every available method; an unavailable one is refused
(22023). fact.cells(mp_ids, days, method_id) returns one row per root-day and cell, for a reader's
partial pairs: the hour's kWh, completeness, quantity, price for every interval, cost, the price's
generated flag, and under the method its status, three gases and the factor's generated flag.
The maker reads only inputs, never a table of fact; the version it returns is NULL.
fact.refresh stores its rows under the current version. It reads the functions' own building
blocks (calc.window_hours, calc.price_areas, calc.hour_prices, calc.mp_municipality,
calc.cost_sum, calc.cost_any) and the factor and share rows by their keys. It sums the
functions' hourly amounts by root-day and status, without rounding. Summed by bucket, the rows equal
every total column of calc.emission_buckets and calc.cost_buckets (cmp=none), value and
scale. CO2e is not stored: a reader makes it from the three gas sums with the GWP set's numbers.
"In the basis" is status 1–3 under best and status 3 under final. elo_devtools.fact_sums
holds the summation the tests use, column for column.
The readings are read per distinct local day of a request: the day's series in one array, and the
day's UTC range. Scattered stale days therefore never scan the range between them. The internal
functions fact.hours, fact.cost_hours and fact.emission_hours hold the hour-level rows. The
API may execute them, because the maker runs as the caller.
fact.refresh(max_days) is one batch of the facts lane, run by elo_worker as the owner. It first
calls fact.check_version(). It then claims at most max_days due marks, newest local day first,
then the lowest mp_id. It takes the locks in a writer's order, the point before the mark: first
the points of the due marks FOR SHARE, then their marks FOR UPDATE, both SKIP LOCKED. It
waits for no writer. A point or mark that an uncommitted writer holds is passed by and stays due;
that writer renews the mark. A writer that would make a held point a root or a child waits until
the batch commits, then sees the batch's rows and marks the day. Without the point's lock, a point
demoted during its first making could keep a fact with no mark. It replaces the stored rows and
deletes each mark by (mp_id, local_date, seq). If the batch raises, its root-days are made one by
one. A root-day that raises keeps its mark with attempts + 1, failed_at and the SQLSTATE in
error. A lock not had, a deadlock, a serialization failure, a timeout, or a resource or system
error (fact.transient: SQLSTATE classes 40, 53, 55, 57, 58) is no root-day's failure. The batch
raises it and is undone. No attempt is counted, and its marks are due again at once. A mark is due when attempts is 0, or
when failed_at lies 1 hour, 6 hours, or 1 day and more (daily) behind, for 1, 2, and 3 or more
attempts (fact.wait). A renewed mark is due at once. The function returns (made, failed, due).
It analyses a fact table once the rows written since its last analysis exceed a tenth of its rows.
fact.status() returns one row: the version, live, the stored root-days of the current version,
the marks, the due marks, the failed marks, the oldest mark that has not failed, and the oldest 100
failures by mp_id, day and SQLSTATE. fact.verify(sample, recent_days, seed) compares the stored
rows of unmarked root-days with the maker's rows, by row text (value and scale). It returns each
difference as mp_id, day and table. By default it covers the last 60 days and 2 000 seeded others;
a NULL sample covers every root-day. make verify runs it after ts.verify():
deploy/sql/verify.sql and its twin elo_worker.maintenance.VERIFY (elo admin verify) are one
text. The default sample applies unless the setting elo.verify_facts is all (e.g. PGOPTIONS='-c elo.verify_facts=all' in the environment of the psql that runs the script: inside the container,
through compose exec -e); make verify FACTS=all is B132's Makefile line.
The facts lane (B132)
The job facts-refresh (elo_worker.jobs.facts_refresh) runs in a third thread of the worker, the
facts lane, one job at a time. The job calls no service and waits for none, so it stands behind
neither a declaration job asleep in its wait nor the main loop's backfill, and **it runs in the demo
stack** (ELO_DEMO=1). The main loop's queue and the declaration lane's leave the kind alone.
Due is a due mark. Before each claim the lane asks fact.status() (facts_check,
facts_refresh.ensure_queued); when due is above 0, no facts-refresh is queued or running and
the failed jobs of the kind have waited out their ladder, it queues one under the dedup key
facts-refresh. due counts the marks with attempts 0 and the failed ones whose failed_at lies
the wait of their attempts behind them (1 hour, 6 hours, 1 day, then daily). So **one root-day that
fails, with nothing else due, queues no job for an hour**, and a day that keeps failing costs four
jobs on its first day and one a day after. The same ladder holds off a job that failed itself (an
error outside the root-days): its marks stay due, and the check does not queue another at the next
poll.
A run calls fact.refresh(ELO_FACTS_BATCH) (2 000 root-days; empty or unset is 2 000, and a value
that is not a whole number of 1 or more refuses the worker's start with a sentence) batch after batch, each in a transaction of its own, until no mark is due or 60 s have
passed, and then queues its successor on the claim's connection (dedup key
facts-refresh:after-<job id>, so it never clashes with the job that queues it; it commits with that
job's done). The marks are worked newest local day first, then the lowest mp_id
(fact.refresh's order). A batch that makes nothing while marks are due is one an uncommitted
writer holds: the run waits a second. A transient error (fact.transient: SQLSTATE class 40, 53,
55, 57, 58, or a lost connection) undoes the batch, counts no attempt of any root-day and is asked
again after a second; any other error fails the job's attempt, by class name. A stop ends the run
between two batches.
The lock. The run holds the advisory lock elo.facts as a session lock on a connection of its
own from before its first batch to after its last. It is taken with a lock_timeout of 60 s (reset
once held), the connection is discarded on any error, and the session is asked before every batch.
ops.remove_account tries the lock and refuses with the sentence of account_remove.REFUSALS; a
run that starts during a removal waits for its commit and reads what is left.
A worker killed in the middle of a batch leaves that batch's marks, seqs and rows as they were
(the batch is one transaction), holds no elo.facts (the lock ends with its session), and the job
stays queued with its attempt open: the next claim closes it as abandoned and the next run makes
the root-days.
make status prints a block stored facts: inside the runs section (not a section of its
own: the sections' count is pinned by other epics' tests). First, when ELO_FACTS_LIVE is on, "the
stored facts are switched off: every figure is computed from the readings (ELO_FACTS_LIVE)". Then
the root-days stored and the version; the stale ones with the age of the oldest mark that has not
failed; those due now; each failed root-day by mp_id, day and SQLSTATE, with the words "computed
from the readings on every request until it can be made" (flagged !); the last run's root-days,
seconds, rate and batches (from the job's detail); and a ! for a mark that has not failed and is
older than a day.
make verify [FACTS=all] runs fact.verify after ts.verify(). FACTS=all passes
PGOPTIONS='-c elo.verify_facts=all' to the psql inside the container through compose exec -e;
any other value is refused before anything runs.
make demo ends, after its last write (the removal of one root's price area, which marks that
root's days), by waiting until fact.status() reports no due mark (demo_load.wait_for_facts), and
says how many root-days are stored. No call is made. With no worker running it gives up after 30
minutes with a sentence.
The stack check (deploy/smoke.py) loads no reading, so no mark is due: it asserts that the
lane started and that fact.status() answers, and waits for nothing.
The readers I: the emission, its reason, the consumption's pairs (B133)
fact.emission_buckets, fact.emission_reason_hours and fact.consumption_matched take the
parameters and return the columns of calc.emission_buckets, calc.emission_reason_hours and
calc.consumption_matched (without p_export), in the same order, with the same refusals. A query
changes one name. Each returns what its function returns, value and scale. The equality is tested
on every named case and the demo, in four states: every root-day made, every one stale, a seeded half
stale, and ELO_FACTS_LIVE on.
What a reader reads. The comparison, the buckets and the calendar come from the functions'
helpers. Each side of a request (the period's days, the comparison's) is read for itself, as the
functions read it. A root-day that is not live gives its stored rows of the current version; a row
of another version is as if it were not there. A live root-day is one that holds a mark, or any
root-day while fact.state.live is on. Its hours are read once from the readings, by
fact.emission_hours for the emission (which returns the hour's complete since B133) or by
fact.hours for the consumption. Those hours give the day's masks, its rows and the cells of its
pair.
The pairs (§2.4). A period day of a root and its corresponding comparison day make a pair. The
corresponding day uses fact.cell_day: the day of the month is kept under a shift in months, and
under py 29 February has none. The counts are bit operations: K′ is fact.calendar_mask of the
comparison day's minutes, X = Q ∧ K′, and M = X ∧ C ∧ C′ ∧ G ∧ G′. For the emission, G is the cells
in the basis; for the consumption it is every cell. A pair with no bit in M adds to the counts
alone. A pair with M = S = S′ takes each side's totals; its generated flag is the two days' flags
in the basis. Every other pair is summed over M from the hours of both days, so a generated factor
outside M never makes generated_factors true. The stored partner of a live day is read whatever
its pair turns out to be, because fact.live_rows counts before the live day is read.
fact.emission_reason_hours counts the hours of each cause from the rows' quantity_hours by
status, and finds "every interval lacks a price area" when every row of the period has status 4.
A period of 0,000 kWh with its facts made reads no reading.
fact.live_rows(reader, mp_ids, from, to, cmp, cmp_date, method_id, basis) returns
live_rows, days, made and remaining_rows, from the marks and the masks, before a reading is
read. reader is emission_buckets, emission_reason_hours or consumption_matched. live_rows
is the ts.day_load.points of the root-days the reader reads from the readings. That is every live
root-day of each side, each side for itself, so a day on both sides of an overlapping py counts
twice. It also counts the stored partner of a live day in a pair, and both days of a partial pair of
stored days. The tests hold it equal to the reading rows of the reader's plans, in the four states.
days is the request's distinct stored root-days, and made those of them without a mark (none
under ELO_FACTS_LIVE). remaining_rows is what live_rows would be once the live days that have
not failed were made: the failed days and their partners, and the partial pairs of stored days. A
pair with an unfailed live day counts nothing there, because whether it will be partial is known
only once it is made. The cost's reader (B135) is not in the list yet.
Kilde: docs/facts.md i løsningens
repository.