Sub topic 8
How a row version is judged visible
This chapter covers the test PostgreSQL applies to each row version. It assumes you have read the earlier chapters on row versions, xmin/xmax, transaction IDs, commit status and snapshots. You also need two psql sessions open against the same database.
The question being answered
A table can hold several versions of one logical row. Every scan has to decide, version by version, whether the current query should see it. The decision depends on three inputs:
- The version's
xminandxmax. - The commit status of the transactions those IDs name.
- The snapshot the query is using.
PostgreSQL implements this check in its tuple visibility functions. They are called once for every tuple a scan touches. The check has two halves. The first asks whether the creation is visible. The second asks whether a visible deletion hides the version again.
Two facts that drive every decision
A transaction ID can be in one of three states: in progress, committed or aborted. The commit state lives in pg_xact. The snapshot adds a second, independent question: did that transaction finish before the snapshot was taken?
Recall the snapshot's fields:
xmin: the oldest transaction that was still active.xmax: the first ID not yet assigned.xip_list: the active IDs between them.
For any transaction ID X, the snapshot treats it as follows:
| Condition on X | Snapshot's view of X |
|---|---|
| X is greater than or equal to snapshot `xmax` | Started after the snapshot, so its effects are invisible |
| X is in `xip_list` | Was running at snapshot time, so its effects are invisible |
| X is lower than snapshot `xmin`, or in range and not listed | Finished before the snapshot, so its effects count if it committed |
"Finished" is not the same as "committed." A transaction that finished before the snapshot may have aborted. The visibility code therefore needs both the snapshot test and the pg_xact lookup.
The decision procedure
The simplified logic for one tuple is below. It follows the order in which the real code works.
- Check
xmin, the creator. - If
xminaborted, the version never existed. It is invisible. - If
xminis the current transaction, apply the command-ID rules described later in this chapter. - If
xminis in progress, or the snapshot does not see it as finished, the version is invisible. - If
xmincommitted and the snapshot sees it as finished, go on toxmax. - Check
xmax, the deleter or locker. - If
xmaxis 0, the version is visible. - If
xmaxonly records a row lock (fromSELECT ... FOR UPDATE, for example), nothing was deleted, so the version is visible. - If
xmaxaborted, the delete never happened, so the version is visible. - If
xmaxis in progress, or the snapshot does not see it as finished, the delete is not yet visible to this query, so the version is visible. - If
xmaxcommitted and the snapshot sees it as finished, the version is deleted as far as this query is concerned. It is invisible.
This gives the combinations that matter in practice:
| `xmin` | `xmax` | Visible? |
|---|---|---|
| Aborted | any | No |
| In progress (another transaction) | any | No |
| Committed, in snapshot | 0 | Yes |
| Committed, in snapshot | Aborted, or lock only | Yes |
| Committed, in snapshot | In progress, or committed after the snapshot | Yes |
| Committed, in snapshot | Committed, in snapshot | No |
Committed but still invisible
A common misconception is that a committed row is visible. It is visible only if its transaction finished before your snapshot. Try this with two sessions.
-- Session A
BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT pg_current_snapshot(); -- snapshot is fixed from here on
-- Session B
BEGIN;
INSERT INTO accounts VALUES (2, 50);
SELECT pg_current_xact_id(); -- note this ID, for example 801
COMMIT;
-- Session A
SELECT * FROM accounts WHERE id = 2; -- 0 rows
SELECT pg_visible_in_snapshot('801'::xid8, pg_current_snapshot()); -- false
COMMIT;
SELECT * FROM accounts WHERE id = 2; -- now 1 rowReplace 801 with the ID Session B printed. The new row's xmin is committed in pg_xact. Session A still rejects it, because that ID is at or above the snapshot's xmax, or in its xip_list. A new snapshot, taken after A's COMMIT, accepts it.
pg_visible_in_snapshot implements only the snapshot half of the test. It reports whether a transaction completed before the snapshot, not whether it committed.
Hint bits: caching the commit-status lookup
Looking up pg_xact for every tuple would be costly. The first backend that checks a tuple's xmin or xmax and finds the transaction's final state records it in the tuple header as a hint bit: HEAP_XMIN_COMMITTED, HEAP_XMIN_INVALID, HEAP_XMAX_COMMITTED or HEAP_XMAX_INVALID. Later readers skip the lookup. You can see these bits with pageinspect:
CREATE EXTENSION IF NOT EXISTS pageinspect;
SELECT lp, t_xmin, t_xmax, f.raw_flags
FROM heap_page_items(get_raw_page('accounts', 0)),
LATERAL heap_tuple_infomask_flags(t_infomask, t_infomask2) AS f
WHERE t_infomask IS NOT NULL OR t_infomask2 IS NOT NULL;The first SELECT after a bulk load may show no hint bits. After a second scan, HEAP_XMIN_COMMITTED usually appears.
Your own changes and command IDs
When xmin or xmax is the current transaction, the snapshot and pg_xact cannot help, because your own transaction is still in progress. PostgreSQL uses a per-transaction command ID (cmin and cmax, stored in the tuple). A statement sees changes made by earlier commands in its own transaction. It does not see changes made by itself or by later commands.
This explains two behaviors:
BEGIN; INSERT ...; SELECT ...;sees the new row, because the insert is an earlier command.- An
UPDATE ... WHEREdoes not loop forever over the new versions it writes, because those versions carry the current command ID and the scan ignores them.
A cursor is a related case. It remembers the command ID at the moment it was declared, so rows you change afterwards in the same transaction stay invisible through that cursor.
Where this test is applied, and where it is not
Visibility is evaluated per tuple, per scan. Three consequences follow:
- Index entries carry no visibility information. An index scan finds candidate tuples, then the heap tuple is checked. The visibility map and index-only scans, covered in a later chapter, are an optimization of this step.
- Two queries in the same instant can disagree about a row. They use different snapshots, so both answers are correct.
- Dead tuples are exactly those that fail the test for every snapshot that could still exist. Vacuum reuses the same reasoning, with the oldest snapshot's
xminas the cutoff.
Edge cases to remember
- Subtransactions (savepoints) get their own XIDs. A tuple created inside a rolled-back savepoint has an aborted
xmin, even though the main transaction commits. - Frozen tuples. Freezing marks
xminas visible to everyone, regardless of the snapshot, so old rows never depend on apg_xactlookup. A later chapter covers this. - Concurrent updates under Read Committed. If
xmaxis in progress on a row you want to update, the visibility test says "visible." TheUPDATEthen waits for that transaction and re-evaluates the newer version. This is write-conflict handling, not a visibility rule.
Exercise
A row version has xmin = 120 (committed) and xmax = 125. Transaction 125 committed. Your Repeatable Read snapshot is 123:124:123, written as xmin:xmax:xip_list, so transaction 123 was still running when you took it. Is the version visible to you, and why?
Show answer
Yes, it is visible. The creator 120 is lower than the snapshot xmin (123) and committed, so the creation is visible. The deleter 125 is greater than or equal to the snapshot xmax (124), so it started after the snapshot and its delete is invisible to you. The xmax is committed in pg_xact, but the snapshot test overrides that.
Exercise
Why does a plain SELECT sometimes write to disk, and what does the tuple header gain from it?
Show answer
The first reader to check a tuple's xmin or xmax against pgxact records the transaction's final state in the tuple's hint bits (for example HEAPXMINCOMMITTED). That modifies the page, so the page becomes dirty and is written later. Later readers skip the pgxact lookup. They still apply the snapshot test.