Sub topic 5
Looking at real pages with pageinspect
Earlier chapters described the 8 KB page, its line pointers and its tuples. This chapter shows how to look at them. You will read raw pages from SQL, interpret the output, and cross-check it against the size functions that ship with PostgreSQL.
This chapter assumes you can run psql, that you know what a transaction is, and that you have read the previous chapters on page layout and line pointers. You need a scratch database where you can create an extension. Do not run these experiments on a production system.
What pageinspect is
pageinspect is a contrib extension. It adds functions that return the raw bytes of a page and decode those bytes into structured rows. It is not installed by default, and it is not a trusted extension. You need a superuser, or a superuser must grant you execute rights on the functions.
CREATE EXTENSION IF NOT EXISTS pageinspect;
CREATE TABLE accounts (id int PRIMARY KEY, owner text, balance numeric);
INSERT INTO accounts VALUES (1, 'alice', 100), (2, 'bob', 200);The extension works in two steps. First, get_raw_page fetches one 8192-byte page as a bytea value. Second, a decoder function parses that value.
SELECT length(get_raw_page('accounts', 0)) AS page_bytes;The result is 8192, which matches SHOW block_size. The second argument is a block number, counted from 0. Asking for a block past the end of the table raises an error such as block number 1 is out of range for relation "accounts". That error is a quick way to learn that the table is smaller than you assumed.
Where get_raw_page reads from
get_raw_page reads through shared buffers, the same cache that ordinary queries use. It returns a copy of the page as the server currently holds it. That page may include changes that have not yet been written to the data file. If you opened the file with an operating system tool you could see different bytes until the next checkpoint or write-back.
The function takes an optional fork name before the block number: 'main', 'fsm', 'vm' or 'init'. Without it, get_raw_page reads the main fork, which holds the rows. Decoders for index pages and the other forks exist, but they are specific to each kind of page. Passing a heap page to an index decoder, or the reverse, gives errors or meaningless output.
Reading the page header
SELECT lower, upper, special, pagesize, flags, prune_xid
FROM page_header(get_raw_page('accounts', 0));A result for the two-row table looks like this. The upper value will differ on your system.
lower | upper | special | pagesize | flags | prune_xid
-------+-------+---------+----------+-------+-----------
32 | 8096 | 8192 | 8192 | 0 | 0Each column tells you something specific:
loweris the byte offset where the line pointer array ends. The fixed page header takes 24 bytes and each line pointer takes 4. Two rows give 24 + 2 × 4 = 32.upperis the byte offset where the tuple area begins. Tuples are written from the end of the page backward, souppershrinks as rows are added.specialequalspagesizefor a heap page because heap pages have no special space. B-tree index pages use it for sibling links.prune_xidis a hint. A nonzero value means the page may contain dead tuples that a pruning pass could remove, and it holds the oldest transaction that could have made one.
Free space in the page is upper - lower. This is the gap in the middle of the page. It is not the same as reclaimable space held by dead tuples.
Reading the line pointers and tuples
heap_page_items returns one row per line pointer, including pointers that no longer lead to a live tuple.
SELECT lp, lp_off, lp_flags, lp_len, t_xmin, t_xmax, t_ctid
FROM heap_page_items(get_raw_page('accounts', 0));| Column | Meaning |
|---|---|
| `lp` | Line pointer number, starting at 1. This is the second half of a `ctid`. |
| `lp_off` | Byte offset of the tuple from the start of the page. |
| `lp_flags` | 0 unused, 1 normal, 2 redirect, 3 dead. |
| `lp_len` | Length of the tuple in bytes. It is 0 for unused and redirect pointers. |
| `t_xmin`, `t_xmax` | Transaction IDs that created and deleted or locked the tuple. |
| `t_ctid` | Address of this tuple, or of its newer version if one exists. |
Check the output against SELECT ctid, xmin, xmax, * FROM accounts;. The ctid (0,1) should match lp = 1 with the same t_xmin. Seeing the SQL-level system columns and the page-level fields agree is the quickest way to trust what the extension shows.
Not every row in the output is a live tuple. For unused and dead pointers, the tuple fields come back as null, because there may be no tuple data to read. When you write queries over this function, filter on lp_flags = 1 if you only want tuples that can be read.
Decoding the tuple header and data
The remaining columns of heap_page_items expose the rest of the tuple header: t_infomask, t_infomask2, t_hoff, t_bits and the raw bytes in t_data. The infomask fields are bit flags, so reading them by hand is tedious. Since PostgreSQL 13, heap_tuple_infomask_flags names the bits for you.
SELECT lp,
t_xmin,
t_xmax,
t_hoff,
(heap_tuple_infomask_flags(t_infomask, t_infomask2)).combined_flags
FROM heap_page_items(get_raw_page('accounts', 0))
WHERE lp_flags = 1;Flags such as HEAP_XMIN_COMMITTED tell you whether PostgreSQL has already cached the commit status of t_xmin in the tuple itself. These cached bits are called hint bits. A freshly inserted and committed row may not have them set until some query first reads the row. That is why the same page can look different before and after a SELECT.
To split the user data into columns, use tuple_data_split. It needs the table's OID so it can look up the column types.
SELECT lp,
tuple_data_split('accounts'::regclass, t_data, t_infomask, t_infomask2, t_bits) AS columns
FROM heap_page_items(get_raw_page('accounts', 0))
WHERE lp_flags = 1;The result is an array of bytea values, one per column. For row 1 the first element is \x01000000, the integer 1 as four little-endian bytes on most machines. The second element is \x0d616c696365. The first byte, 0d, is a one-byte length header for a short value. It encodes a total length of 6, which is the header plus the five characters of alice. The rest is the ASCII text. The numeric column uses its own internal format, which tuple_data_split does not decode for you.
You are looking at the exact bytes the earlier chapters described, with no layer of the SQL type system in between.
Watching an update change a page
The most useful habit is to inspect, change something, and inspect again.
UPDATE accounts SET balance = balance + 50 WHERE id = 1;
SELECT lp, lp_flags, lp_len, t_xmin, t_xmax, t_ctid
FROM heap_page_items(get_raw_page('accounts', 0));
SELECT lower, upper FROM page_header(get_raw_page('accounts', 0));You should see three line pointers. The old version of Alice's row has a nonzero t_xmax and a t_ctid that points to the new version. The new version has the next lp number and a t_ctid that points to itself. lower has grown by 4 and upper has shrunk by the size of the new tuple. The old tuple still occupies space until pruning or VACUUM reclaims it. Running VACUUM accounts; and repeating the query shows the effect on lp_flags.
Cross-checking with the size functions
The pageinspect functions look at one page. The size functions give totals, and the two should agree.
| Function | Counts |
|---|---|
| `pg_relation_size(rel)` | The main fork only. |
| `pg_relation_size(rel, 'fsm')` or `'vm'` | One named fork. |
| `pg_table_size(rel)` | Main fork, free space map, visibility map and TOAST table, but not indexes. |
| `pg_indexes_size(rel)` | All indexes on the table. |
| `pg_total_relation_size(rel)` | Everything above combined. |
Dividing pg_relation_size by the block size gives the number of pages. That number should be one more than the highest valid block number you can pass to get_raw_page.
SELECT pg_relation_size('accounts') / current_setting('block_size')::int AS pages;If the table has 1 page, get_raw_page('accounts', 0) works and block 1 fails. When this does not match, the likely cause is a stale size from a different relation than you meant, such as a table of the same name in another schema. Use pg_relation_filepath('accounts') to confirm which file you are looking at.
Common errors and gotchas
- Permission denied for function getrawpage. The role is not a superuser and was not granted execute rights.
- Out of range block number. The table has fewer pages than you assumed. Check the size first.
- Temporary tables. They live in your session's own buffers and files, so inspect them from the session that created them.
- Nulls in heappageitems. Unused and dead pointers have no tuple, so the tuple columns are null. This is expected.
- Results change between runs. Hint bits, pruning and autovacuum can all alter a page between two calls. Disable autovacuum on a scratch table with
ALTER TABLE accounts SET (autovacuum_enabled = off)if you need a stable view. - Wrong decoder. Use
bt_page_itemsfor B-tree pages, notheap_page_items.
Exercise
After inserting two rows into a fresh table, page_header reports lower = 32. Explain where 32 comes from, and say which expression gives the free space in the page.
Show answer
The page header takes 24 bytes and each line pointer takes 4 bytes, so two rows give 24 + 2 × 4 = 32. Free space is upper - lower, the gap between the end of the line pointer array and the start of the tuple area.
Exercise
You run heap_page_items on a page and some rows show null for t_xmin and t_data. What does that tell you about those rows, and how do you restrict a query to readable tuples only?
Show answer
Those line pointers are not normal, because they are unused or dead, so no tuple can be read through them. Add WHERE lp_flags = 1 to keep only normal line pointers.