DEV Community

The same audit query, two answers: 17.5% of rows disagree with themselves

The same query, two different answers

At 13:00:20 I ran one query against production. At 13:02:18 I ran it again, unchanged.

SELECT count(*), count(*) FILTER (WHERE settled) AS settled, count(*) FILTER (WHERE hit) AS hits FROM ai_predictions;
  • t0 51529 | 50494 | 28749
  • t90 51530 | 50494 | 28749

One row. But the same instability applied to a date instead of a second is not rounding.

I asked production "what did the direction distribution look like as of 15 November?" two defensible ways. On the 13,404 predictions where both answers exist, 2,346 - 17.50% - came back different.

A metric that moves 17.5% depending on how you phrase the question is not a metric. It is a story about the query.

One production instance throughout: PostgreSQL 15.18, 116 GB, shared_buffers 8 GB, xid 946,255,838.

Three things move at once

Growth is the small part. ai_predictions holds 51,532 rows and has absorbed 26,211,299 row updates since it was last bulk-loaded - 508 rewrites per surviving row.

Of those rows, 51,336 (99.62%) carry updated_at later than created_at by more than a second; 39,034 were rewritten more than a day after creation.

A "row" is not a stable object. It is a slot that values are poured into; reading it at 13:00 and 13:02 may return two different facts sharing a primary key.

The third mover is settlement: predictions are graded hours or weeks after the row exists, so two filters that sound like the same moment are not.

Counting rows with created_at < '2026-11-01' gives 37,179; counting rows with settled_at < '2026-11-01' gives 34,915.

Grade the graded ones and the rate shifts too: 57.29% under created_at (37,104 rows, 21,258 hits) against 57.64% under settled_at (34,912 rows, 20,123 hits).

Neither is wrong: they answer which predictions existed versus which verdicts existed, and a rate without its filter beside it is unfalsifiable.

The snapshot exists - it just has no name

Postgres can give a stable answer, by default, inside a transaction:

BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT txid_current_snapshot();
SELECT count(*), count(*) FILTER (WHERE settled) FROM ai_predictions;
-- 90 s pass, then the same statement again, same transaction:
-- t0 51530 | 50494 | 946259841:946259841:
-- t90 51530 | 50494 | 946259841:946259841:
-- identical = True

Ninety seconds, one insert committed by another session in between, byte-identical output. 946259841:946259841: is xmin:xmax:xip_list - the boundary of what the transaction sees. Two numbers and an empty in-progress list froze a 51,532-row table.

Why does nobody store that name? Because it is only valid inside the transaction; commit, and the next session gets a new one, the old one unaddressable.

Postgres does not keep row versions for you to travel through - autovacuum removed 936 dead tuples here at 13:00:33, and those are exactly the versions a historical read would need. Reproducibility has to be purchased at write time, not read time.

Two candidate watermarks already sit in the table. Both leak.

Watermark one: the id column

id is a bigserial, so its order is insertion order, and id <= 1454196 looks like "everything that existed at 13:00:20". Window functions over that order show the cost:

SELECT count(*) AS total, count(*) FILTER (WHERE created_at < prev_max) AS late_inserted, max(prev_max - created_at) AS max_backdate
FROM (
  SELECT created_at, max(created_at) OVER (ORDER BY id ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) AS prev_max
  FROM ai_predictions
) x WHERE prev_max IS NOT NULL;
-- 51531 | 4755 | 5 days 13:34:15

4,755 rows (9.2%) carry a created_at older than a row inserted before them; one was inserted more than five days after the timestamp it claims.

By month, this is not noise, it is a migration:

  • 2026-06: 2,735 rows, 2,031 inserted out of order (74.3%)
  • 2026-07: 2,637 rows, 2,516 inserted out of order (95.4%)
  • 2026-08: 164 rows, 0
  • 2026-09: 9,757 rows, 125 (1.3%)
  • 2026-10: 21,886 rows, 53 (0.2%)
  • 2026-11: 14,353 rows, 30 (0.2%)

June and July were backfilled wholesale: rows arrived in an order unrelated to the dates they carry. Since September the write path is honest at 0.2%, but 74-95% months make any id-based reconstruction of early history fiction.

That query also took 97.6 seconds, sorting a table whose n_live_tup claimed 89,575 against a truth of 51,532.

Watermark two: the timestamp you filtered on

Filter on created_at <= T and it holds up better than expected: 0 rows claim a created_at before 1 November while being physically written after the first post-cutoff row.

But it watermarks existence, not state. Between 15 November and today, 4,657 rows created before that date were rewritten after it - 9.92% of the pre-cutoff cohort - and every rewrite is invisible to that filter.

You read today's value, label it "as of 15 November", and the 17.50% appears.

A revisions table exists, and still cannot tell you when

I expected to conclude "there is no history". There is: ai_prediction_revisions holds 206,310 rows across 18,046 prediction slots, 6,858 matches and 2,102 models, capturing since 2026-10-30.

Of those slots 16,414 have more than one revision; the mean is 11.44 and the maximum is 898. 6,202 slots (34.4%) contain at least one change of direction - exactly the mutations the live table overwrites.

The defect: 21 columns, none of them the prediction's primary key. revisions.id is its own sequence (309,226 โ†’ 515,794), not a reference - joining on it returns 0.

The only usable key is the pair (match_id, model_id), unique in ai_predictions today - 51,532 rows, 51,532 distinct pairs - because of how the writer currently behaves. Nothing declares it; nothing stops it from ceasing to be true. A history table keyed by coincidence.

Its time axis is undocumented. If created_at were the capture moment it would equal the live updated_at; if it were a copied field it would always equal created_at. Over 206,379 joins:

  • what revisions.created_at equals / rows / share
  • the live updated_at (capture time) / 361 / 0.17%
  • the live created_at (copied field) / 17,727 / 8.59%
  • later than the live updated_at + 60 s / 5,785 / 2.80%

Neither hypothesis survives, and the third row cannot be produced by either semantics. You cannot build an as-of reconstruction on a clock you cannot read.

Coverage compounds it: 18,046 of 51,532 slots, 35.0%.

The 46 tables named like backups (ai_predictions_narrsync_bk_20261015 โ€ฆ _20261129) do not rescue this. They hold 41, 5, 13 and 20 rows on 1, 15, 28 and 29 November - the handful of rows a sync job touched, named after the run date, recording no transaction boundary.

Reconstructing an as-of answer, and its bill

The revisions table is still the best instrument available, defects included. One statement per time point:

WITH latest AS (
  SELECT DISTINCT ON (match_id, model_id) match_id, model_id, direction, created_at
  FROM ai_prediction_revisions
  WHERE created_at < '2026-11-15'
  ORDER BY match_id, model_id, created_at DESC, id DESC
)
SELECT direction, count(*) FROM latest GROUP BY 1 ORDER BY 2 DESC;

Against the naive reading - current values filtered by created_at:

  • direction / as-of reading (revisions) / naive reading (live rows)
  • home / 5,005 / 19,213
  • away/draw / 3,439 / 10,924
  • away / 3,196 / 10,510
  • home/draw / 1,706 / 5,930

Totals differ because denominators differ (13,404 covered slots versus 46,926 live rows), so compare shares, not levels. On the 13,404 slots where both exist: 2,346 disagree, 17.50%.

The query reads 206,310 rows and needs created_at DESC, id DESC; without the serial tie-break the result depends on plan order - 180 ms for one time point, 307 ms for join-and-compare.

The ledger: make the watermark part of the number

The fix is refusing to publish a number with no address. Every audit result gets stamped with the snapshot it was computed inside, in a row holding metric, as_of_xid, as_of_wall, the verbatim row_filter, row_count, value and fingerprint.

The fingerprint makes a rerun falsifiable. For ai_predictions right now: 51,532 rows, sum(id) 57,099,908,137, 28,749 hits, md5 e4464ff27c34985f3bd4630a17960ba2.

A changed digest means the table moved, and sum(id) inside it says by how much; an unchanged digest with a changed value means the query changed - a different bug with a different owner.

def audit(conn, metric, sql, row_filter):
    conn.set_session(isolation_level='REPEATABLE READ', autocommit=False)
    cur = conn.cursor()
    cur.execute("SELECT txid_current_snapshot()::text, now()"); snap, wall = cur.fetchone()
    cur.execute(sql); row_count, value, fp = cur.fetchone()
    cur.execute("INSERT INTO audit_ledger (metric, as_of_xid, as_of_wall, row_filter,"
                " row_count, value, fingerprint) VALUES (%s,%s,%s,%s,%s,%s,%s)",
                (metric, snap, wall, row_filter, row_count, value, fp))
    conn.commit()
    return {"as_of_xid": snap, "value": float(value), "fp": fp}

REPEATABLE READ means every statement in one report sees the same snapshot, so the 51,529/51,530 divergence becomes structurally impossible. And txid_current_snapshot() is a string you can paste into a ticket: this number was true inside 946259841:946259841: is a claim someone else can check.

The limits are honest: a snapshot is not re-readable after commit, so the ledger buys reproducibility of the record, not time travel. The latter needs row versions written down at update time, with a real foreign key, one unambiguous capture timestamp and a (prediction_id, captured_at) primary key. The revisions table is 70% of that design, missing the two columns that matter.

What I changed

Every metric ships with its WHERE clause and row count in the same sentence. A rate without a denominator is a rumour.

Reports run inside one REPEATABLE READ transaction and store txid_current_snapshot().

id is not a watermark. After the June-July backfill it is an insertion counter for a table that was rebuilt.

No ORDER BY ships without a tie-break down to a unique column: among 744 models with 20 or more graded rows there are only 212 distinct rounded rates, so ties are the norm and the top-20 boundary at 75.4% is unique today by luck.

The narrsync_bk tables are deltas, not snapshots, and are documented as such so nobody restores from one.

The one-row gap between 13:00:20 and 13:02:18 was never the interesting number. The interesting number is 17.50% - the share of rows that answer "as of 15 November" differently depending on which clock you hand them.

Analytics and research content. Not betting advice. 18+ ๆœฌๅ†…ๅฎนไป…ไพ›ๆ•ฐๆฎๅˆ†ๆžไธŽ็ ”็ฉถๅ‚่€ƒ๏ผŒไธๆž„ๆˆไปปไฝ•ๅ†ณ็ญ–ๅปบ่ฎฎใ€‚

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.