From fb1b8c3db882fef2d5217525021e1b330ea87fc3 Mon Sep 17 00:00:00 2001 From: Konstantin Knizhnik Date: Wed, 2 Dec 2026 14:17:19 +0200 Subject: [PATCH v11] Fix "missing chunk" errors during heap rewrites and index builds A transaction in another database can hold back the xmin of the backend running CLUSTER, VACUUM FULL, REPACK or a non-concurrent CREATE INDEX, as GetSnapshotData() does not filter by database. ComputeXidHorizons() does, so a concurrent VACUUM or on-access pruning can remove the TOAST chunks of a tuple deleted or updated by a committed transaction while HeapTupleSatisfiesVacuum() in the rewrite still classifies the tuple as HEAPTUPLE_RECENTLY_DEAD. Fetching its TOAST data then fails with "missing chunk number 0 for toast value ...". Such a tuple is invisible to every snapshot that can still look at the relation, so it is safe to treat it as dead. This is done entirely in heapam_handler.c, with two new heap-only functions in heaptoast.c that check or fetch the chunks of an on-disk external value and report missing chunks to the caller instead of raising an error. No table AM, detoast or toast_helper interfaces change. - In a heap rewrite, the TOAST data of a RECENTLY_DEAD tuple is checked while scanning, and the tuple is treated as dead if it is gone. A dead tuple goes through rewrite_heap_dead_tuple() as usual, so update chains stashed in rewriteheap.c are handled as before. The rewrite holds AccessExclusiveLock on the TOAST relation, which keeps VACUUM and other backends out of it, but its own TOAST fetches still prune TOAST pages, with a horizon that can advance up to the xmin of the active snapshot. TOAST chunks deleted by a transaction that follows that xmin cannot go away before the tuple is written out. If some were deleted earlier, the TOAST data of the tuple is inlined while scanning, so that it is not needed anymore when the tuple is written out, possibly after a sort. Dropped columns are checked as well, as a whole-row reference in the sort expressions fetches their TOAST data too. - In a non-concurrent index build, nothing keeps VACUUM or pruning from removing the TOAST data of a RECENTLY_DEAD tuple while the index is built, so the varlena attributes referenced by the index (columns, expressions including whole-row references, and predicate) are fetched up front into a virtual slot, on which the predicate and the index expressions are evaluated. This is done only for RECENTLY_DEAD tuples; the tuple is left out of the index if its TOAST data is gone. The TOAST table of a user_catalog_table does not inherit that option, so its VACUUM ignores catalog_xmin, which the table itself respects. Logical decoding may still need such a tuple, so these relations keep raising the error rather than silently losing a row. REPACK CONCURRENTLY and CREATE INDEX CONCURRENTLY use MVCC snapshots and are not affected. An isolation test is added to contrib/dblink, which is used to hold an XID in another database. Another one, with an injection point between the scan and the sort of a rewrite, checks the case of TOAST chunks pruned by the rewrite itself. Reported-by: Alexander Lakhin Reported-by: Ekaterina Testova Author: Michael Paquier Co-authored-by: Matthias van de Meent Co-authored-by: Rui Zhao Reviewed-by: Robert Haas Discussion: https://postgr.es/m/18351-f6e06364b3a2e669@postgresql.org Discussion: https://postgr.es/m/19519-fe02d8ff679d834d@postgresql.org Discussion: https://postgr.es/m/1779078055.630771314@fmail2.qdit --- contrib/dblink/.gitignore | 2 + contrib/dblink/Makefile | 2 + .../dblink/expected/rewrite_stale_xmin.out | 900 ++++++++++++++++++ contrib/dblink/meson.build | 5 + contrib/dblink/specs/rewrite_stale_xmin.spec | 321 +++++++ src/backend/access/heap/heapam_handler.c | 312 +++++- src/backend/access/heap/heaptoast.c | 166 +++- src/include/access/heaptoast.h | 14 + src/test/modules/injection_points/Makefile | 1 + .../expected/heap_rewrite_toast_prune.out | 44 + src/test/modules/injection_points/meson.build | 1 + .../specs/heap_rewrite_toast_prune.spec | 97 ++ 12 files changed, 1861 insertions(+), 4 deletions(-) create mode 100644 contrib/dblink/expected/rewrite_stale_xmin.out create mode 100644 contrib/dblink/specs/rewrite_stale_xmin.spec create mode 100644 src/test/modules/injection_points/expected/heap_rewrite_toast_prune.out create mode 100644 src/test/modules/injection_points/specs/heap_rewrite_toast_prune.spec diff --git a/contrib/dblink/.gitignore b/contrib/dblink/.gitignore index 5dcb3ff9723..33bc8d8ffeb 100644 --- a/contrib/dblink/.gitignore +++ b/contrib/dblink/.gitignore @@ -2,3 +2,5 @@ /log/ /results/ /tmp_check/ +/output_iso/ +/tmp_check_iso/ diff --git a/contrib/dblink/Makefile b/contrib/dblink/Makefile index fde0b49ddbb..a0ba4128081 100644 --- a/contrib/dblink/Makefile +++ b/contrib/dblink/Makefile @@ -13,6 +13,8 @@ PGFILEDESC = "dblink - connect to other PostgreSQL databases" REGRESS = dblink REGRESS_OPTS = --dlpath=$(top_builddir)/src/test/regress +ISOLATION = rewrite_stale_xmin +ISOLATION_OPTS = --load-extension=dblink TAP_TESTS = 1 ifdef USE_PGXS diff --git a/contrib/dblink/expected/rewrite_stale_xmin.out b/contrib/dblink/expected/rewrite_stale_xmin.out new file mode 100644 index 00000000000..28dde5aa250 --- /dev/null +++ b/contrib/dblink/expected/rewrite_stale_xmin.out @@ -0,0 +1,900 @@ +Parsed test spec with 3 sessions + +starting permutation: s1_hold_xmin s2_begin s3_delete s3_vacuum_main_only s2_commit s3_vacuum_toast s3_cluster s1_release +step s1_hold_xmin: + SELECT dblink_connect('holder', + 'dbname=regress_other_db port=' || current_setting('port')); + SELECT dblink_exec('holder', 'BEGIN'); + SELECT dblink_exec('holder', 'CREATE TEMP TABLE xid_holder(x int)'); + +dblink_connect +-------------- +OK +(1 row) + +dblink_exec +----------- +BEGIN +(1 row) + +dblink_exec +------------ +CREATE TABLE +(1 row) + +step s2_begin: + BEGIN ISOLATION LEVEL REPEATABLE READ; + SELECT 1; + +?column? +-------- + 1 +(1 row) + +step s3_delete: + DELETE FROM rewrite_test WHERE id = 1; + +step s3_vacuum_main_only: + VACUUM (PROCESS_TOAST false) rewrite_test; + +step s2_commit: COMMIT; +step s3_vacuum_toast: + VACUUM pg_toast.rewrite_test_toast; + +step s3_cluster: + CLUSTER rewrite_test USING rewrite_test_pkey; + +step s1_release: + SELECT dblink_exec('holder', 'COMMIT'); + SELECT dblink_disconnect('holder'); + +dblink_exec +----------- +COMMIT +(1 row) + +dblink_disconnect +----------------- +OK +(1 row) + + +starting permutation: s1_hold_xmin s2_begin s3_delete s3_vacuum_main_only s2_commit s3_vacuum_toast s3_cluster_sort s3_check_rows s1_release +step s1_hold_xmin: + SELECT dblink_connect('holder', + 'dbname=regress_other_db port=' || current_setting('port')); + SELECT dblink_exec('holder', 'BEGIN'); + SELECT dblink_exec('holder', 'CREATE TEMP TABLE xid_holder(x int)'); + +dblink_connect +-------------- +OK +(1 row) + +dblink_exec +----------- +BEGIN +(1 row) + +dblink_exec +------------ +CREATE TABLE +(1 row) + +step s2_begin: + BEGIN ISOLATION LEVEL REPEATABLE READ; + SELECT 1; + +?column? +-------- + 1 +(1 row) + +step s3_delete: + DELETE FROM rewrite_test WHERE id = 1; + +step s3_vacuum_main_only: + VACUUM (PROCESS_TOAST false) rewrite_test; + +step s2_commit: COMMIT; +step s3_vacuum_toast: + VACUUM pg_toast.rewrite_test_toast; + +step s3_cluster_sort: + SET enable_indexscan = off; + CLUSTER rewrite_test USING rewrite_test_pkey; + RESET enable_indexscan; + +step s3_check_rows: + SELECT id, length(data), left(data, 1) FROM rewrite_test ORDER BY id; + SELECT reltuples FROM pg_class WHERE oid = 'rewrite_test'::regclass; + +id|length|left +--+------+---- + 2| 2500|y +(1 row) + +reltuples +--------- + 1 +(1 row) + +step s1_release: + SELECT dblink_exec('holder', 'COMMIT'); + SELECT dblink_disconnect('holder'); + +dblink_exec +----------- +COMMIT +(1 row) + +dblink_disconnect +----------------- +OK +(1 row) + + +starting permutation: s1_hold_xmin s2_begin s3_delete s3_vacuum_main_only s2_commit s3_vacuum_toast s3_vacuum_full s1_release +step s1_hold_xmin: + SELECT dblink_connect('holder', + 'dbname=regress_other_db port=' || current_setting('port')); + SELECT dblink_exec('holder', 'BEGIN'); + SELECT dblink_exec('holder', 'CREATE TEMP TABLE xid_holder(x int)'); + +dblink_connect +-------------- +OK +(1 row) + +dblink_exec +----------- +BEGIN +(1 row) + +dblink_exec +------------ +CREATE TABLE +(1 row) + +step s2_begin: + BEGIN ISOLATION LEVEL REPEATABLE READ; + SELECT 1; + +?column? +-------- + 1 +(1 row) + +step s3_delete: + DELETE FROM rewrite_test WHERE id = 1; + +step s3_vacuum_main_only: + VACUUM (PROCESS_TOAST false) rewrite_test; + +step s2_commit: COMMIT; +step s3_vacuum_toast: + VACUUM pg_toast.rewrite_test_toast; + +step s3_vacuum_full: + VACUUM FULL rewrite_test; + +step s1_release: + SELECT dblink_exec('holder', 'COMMIT'); + SELECT dblink_disconnect('holder'); + +dblink_exec +----------- +COMMIT +(1 row) + +dblink_disconnect +----------------- +OK +(1 row) + + +starting permutation: s1_hold_xmin s2_begin s3_delete s3_vacuum_main_only s2_commit s3_vacuum_toast s3_repack s1_release +step s1_hold_xmin: + SELECT dblink_connect('holder', + 'dbname=regress_other_db port=' || current_setting('port')); + SELECT dblink_exec('holder', 'BEGIN'); + SELECT dblink_exec('holder', 'CREATE TEMP TABLE xid_holder(x int)'); + +dblink_connect +-------------- +OK +(1 row) + +dblink_exec +----------- +BEGIN +(1 row) + +dblink_exec +------------ +CREATE TABLE +(1 row) + +step s2_begin: + BEGIN ISOLATION LEVEL REPEATABLE READ; + SELECT 1; + +?column? +-------- + 1 +(1 row) + +step s3_delete: + DELETE FROM rewrite_test WHERE id = 1; + +step s3_vacuum_main_only: + VACUUM (PROCESS_TOAST false) rewrite_test; + +step s2_commit: COMMIT; +step s3_vacuum_toast: + VACUUM pg_toast.rewrite_test_toast; + +step s3_repack: + REPACK rewrite_test; + +step s1_release: + SELECT dblink_exec('holder', 'COMMIT'); + SELECT dblink_disconnect('holder'); + +dblink_exec +----------- +COMMIT +(1 row) + +dblink_disconnect +----------------- +OK +(1 row) + + +starting permutation: s1_hold_xmin s2_begin s3_delete s3_vacuum_main_only s2_commit s3_vacuum_toast s3_create_index s1_release +step s1_hold_xmin: + SELECT dblink_connect('holder', + 'dbname=regress_other_db port=' || current_setting('port')); + SELECT dblink_exec('holder', 'BEGIN'); + SELECT dblink_exec('holder', 'CREATE TEMP TABLE xid_holder(x int)'); + +dblink_connect +-------------- +OK +(1 row) + +dblink_exec +----------- +BEGIN +(1 row) + +dblink_exec +------------ +CREATE TABLE +(1 row) + +step s2_begin: + BEGIN ISOLATION LEVEL REPEATABLE READ; + SELECT 1; + +?column? +-------- + 1 +(1 row) + +step s3_delete: + DELETE FROM rewrite_test WHERE id = 1; + +step s3_vacuum_main_only: + VACUUM (PROCESS_TOAST false) rewrite_test; + +step s2_commit: COMMIT; +step s3_vacuum_toast: + VACUUM pg_toast.rewrite_test_toast; + +step s3_create_index: + CREATE INDEX rewrite_test_data_idx ON rewrite_test (data); + +step s1_release: + SELECT dblink_exec('holder', 'COMMIT'); + SELECT dblink_disconnect('holder'); + +dblink_exec +----------- +COMMIT +(1 row) + +dblink_disconnect +----------------- +OK +(1 row) + + +starting permutation: s1_hold_xmin s2_begin s3_delete s3_vacuum_main_only s2_commit s3_vacuum_toast s3_create_index_wholerow s1_release +step s1_hold_xmin: + SELECT dblink_connect('holder', + 'dbname=regress_other_db port=' || current_setting('port')); + SELECT dblink_exec('holder', 'BEGIN'); + SELECT dblink_exec('holder', 'CREATE TEMP TABLE xid_holder(x int)'); + +dblink_connect +-------------- +OK +(1 row) + +dblink_exec +----------- +BEGIN +(1 row) + +dblink_exec +------------ +CREATE TABLE +(1 row) + +step s2_begin: + BEGIN ISOLATION LEVEL REPEATABLE READ; + SELECT 1; + +?column? +-------- + 1 +(1 row) + +step s3_delete: + DELETE FROM rewrite_test WHERE id = 1; + +step s3_vacuum_main_only: + VACUUM (PROCESS_TOAST false) rewrite_test; + +step s2_commit: COMMIT; +step s3_vacuum_toast: + VACUUM pg_toast.rewrite_test_toast; + +step s3_create_index_wholerow: + CREATE INDEX rewrite_test_row_idx ON rewrite_test ((rewrite_test IS NOT NULL)); + +step s1_release: + SELECT dblink_exec('holder', 'COMMIT'); + SELECT dblink_disconnect('holder'); + +dblink_exec +----------- +COMMIT +(1 row) + +dblink_disconnect +----------------- +OK +(1 row) + + +starting permutation: s1_hold_xmin s2_begin s3_update s3_vacuum_main_only s2_commit s3_vacuum_toast s3_vacuum_full s3_check_rows s1_release +step s1_hold_xmin: + SELECT dblink_connect('holder', + 'dbname=regress_other_db port=' || current_setting('port')); + SELECT dblink_exec('holder', 'BEGIN'); + SELECT dblink_exec('holder', 'CREATE TEMP TABLE xid_holder(x int)'); + +dblink_connect +-------------- +OK +(1 row) + +dblink_exec +----------- +BEGIN +(1 row) + +dblink_exec +------------ +CREATE TABLE +(1 row) + +step s2_begin: + BEGIN ISOLATION LEVEL REPEATABLE READ; + SELECT 1; + +?column? +-------- + 1 +(1 row) + +step s3_update: + UPDATE rewrite_test SET data = repeat('z', 2500) WHERE id = 1; + +step s3_vacuum_main_only: + VACUUM (PROCESS_TOAST false) rewrite_test; + +step s2_commit: COMMIT; +step s3_vacuum_toast: + VACUUM pg_toast.rewrite_test_toast; + +step s3_vacuum_full: + VACUUM FULL rewrite_test; + +step s3_check_rows: + SELECT id, length(data), left(data, 1) FROM rewrite_test ORDER BY id; + SELECT reltuples FROM pg_class WHERE oid = 'rewrite_test'::regclass; + +id|length|left +--+------+---- + 1| 2500|z + 2| 2500|y +(2 rows) + +reltuples +--------- + 2 +(1 row) + +step s1_release: + SELECT dblink_exec('holder', 'COMMIT'); + SELECT dblink_disconnect('holder'); + +dblink_exec +----------- +COMMIT +(1 row) + +dblink_disconnect +----------------- +OK +(1 row) + + +starting permutation: s1_hold_xmin s2_begin s3_update s3_vacuum_main_only s2_commit s3_vacuum_toast s3_repack s3_check_rows s1_release +step s1_hold_xmin: + SELECT dblink_connect('holder', + 'dbname=regress_other_db port=' || current_setting('port')); + SELECT dblink_exec('holder', 'BEGIN'); + SELECT dblink_exec('holder', 'CREATE TEMP TABLE xid_holder(x int)'); + +dblink_connect +-------------- +OK +(1 row) + +dblink_exec +----------- +BEGIN +(1 row) + +dblink_exec +------------ +CREATE TABLE +(1 row) + +step s2_begin: + BEGIN ISOLATION LEVEL REPEATABLE READ; + SELECT 1; + +?column? +-------- + 1 +(1 row) + +step s3_update: + UPDATE rewrite_test SET data = repeat('z', 2500) WHERE id = 1; + +step s3_vacuum_main_only: + VACUUM (PROCESS_TOAST false) rewrite_test; + +step s2_commit: COMMIT; +step s3_vacuum_toast: + VACUUM pg_toast.rewrite_test_toast; + +step s3_repack: + REPACK rewrite_test; + +step s3_check_rows: + SELECT id, length(data), left(data, 1) FROM rewrite_test ORDER BY id; + SELECT reltuples FROM pg_class WHERE oid = 'rewrite_test'::regclass; + +id|length|left +--+------+---- + 1| 2500|z + 2| 2500|y +(2 rows) + +reltuples +--------- + 2 +(1 row) + +step s1_release: + SELECT dblink_exec('holder', 'COMMIT'); + SELECT dblink_disconnect('holder'); + +dblink_exec +----------- +COMMIT +(1 row) + +dblink_disconnect +----------------- +OK +(1 row) + + +starting permutation: s1_hold_xmin s2_begin s3_update s3_update_again s3_vacuum_main_only s2_commit s3_vacuum_toast s3_vacuum_full s3_check_rows s1_release +step s1_hold_xmin: + SELECT dblink_connect('holder', + 'dbname=regress_other_db port=' || current_setting('port')); + SELECT dblink_exec('holder', 'BEGIN'); + SELECT dblink_exec('holder', 'CREATE TEMP TABLE xid_holder(x int)'); + +dblink_connect +-------------- +OK +(1 row) + +dblink_exec +----------- +BEGIN +(1 row) + +dblink_exec +------------ +CREATE TABLE +(1 row) + +step s2_begin: + BEGIN ISOLATION LEVEL REPEATABLE READ; + SELECT 1; + +?column? +-------- + 1 +(1 row) + +step s3_update: + UPDATE rewrite_test SET data = repeat('z', 2500) WHERE id = 1; + +step s3_update_again: + UPDATE rewrite_test SET data = repeat('w', 2500) WHERE id = 1; + +step s3_vacuum_main_only: + VACUUM (PROCESS_TOAST false) rewrite_test; + +step s2_commit: COMMIT; +step s3_vacuum_toast: + VACUUM pg_toast.rewrite_test_toast; + +step s3_vacuum_full: + VACUUM FULL rewrite_test; + +step s3_check_rows: + SELECT id, length(data), left(data, 1) FROM rewrite_test ORDER BY id; + SELECT reltuples FROM pg_class WHERE oid = 'rewrite_test'::regclass; + +id|length|left +--+------+---- + 1| 2500|w + 2| 2500|y +(2 rows) + +reltuples +--------- + 2 +(1 row) + +step s1_release: + SELECT dblink_exec('holder', 'COMMIT'); + SELECT dblink_disconnect('holder'); + +dblink_exec +----------- +COMMIT +(1 row) + +dblink_disconnect +----------------- +OK +(1 row) + + +starting permutation: s1_hold_xmin s2_begin s3_update s3_update_again s3_vacuum_main_only s2_commit s3_vacuum_toast s3_repack s3_check_rows s1_release +step s1_hold_xmin: + SELECT dblink_connect('holder', + 'dbname=regress_other_db port=' || current_setting('port')); + SELECT dblink_exec('holder', 'BEGIN'); + SELECT dblink_exec('holder', 'CREATE TEMP TABLE xid_holder(x int)'); + +dblink_connect +-------------- +OK +(1 row) + +dblink_exec +----------- +BEGIN +(1 row) + +dblink_exec +------------ +CREATE TABLE +(1 row) + +step s2_begin: + BEGIN ISOLATION LEVEL REPEATABLE READ; + SELECT 1; + +?column? +-------- + 1 +(1 row) + +step s3_update: + UPDATE rewrite_test SET data = repeat('z', 2500) WHERE id = 1; + +step s3_update_again: + UPDATE rewrite_test SET data = repeat('w', 2500) WHERE id = 1; + +step s3_vacuum_main_only: + VACUUM (PROCESS_TOAST false) rewrite_test; + +step s2_commit: COMMIT; +step s3_vacuum_toast: + VACUUM pg_toast.rewrite_test_toast; + +step s3_repack: + REPACK rewrite_test; + +step s3_check_rows: + SELECT id, length(data), left(data, 1) FROM rewrite_test ORDER BY id; + SELECT reltuples FROM pg_class WHERE oid = 'rewrite_test'::regclass; + +id|length|left +--+------+---- + 1| 2500|w + 2| 2500|y +(2 rows) + +reltuples +--------- + 2 +(1 row) + +step s1_release: + SELECT dblink_exec('holder', 'COMMIT'); + SELECT dblink_disconnect('holder'); + +dblink_exec +----------- +COMMIT +(1 row) + +dblink_disconnect +----------------- +OK +(1 row) + + +starting permutation: s1_hold_xmin s2_begin s3_update s3_update_again s3_vacuum_main_only s2_commit s3_vacuum_toast s3_cluster_sort s3_check_rows s1_release +step s1_hold_xmin: + SELECT dblink_connect('holder', + 'dbname=regress_other_db port=' || current_setting('port')); + SELECT dblink_exec('holder', 'BEGIN'); + SELECT dblink_exec('holder', 'CREATE TEMP TABLE xid_holder(x int)'); + +dblink_connect +-------------- +OK +(1 row) + +dblink_exec +----------- +BEGIN +(1 row) + +dblink_exec +------------ +CREATE TABLE +(1 row) + +step s2_begin: + BEGIN ISOLATION LEVEL REPEATABLE READ; + SELECT 1; + +?column? +-------- + 1 +(1 row) + +step s3_update: + UPDATE rewrite_test SET data = repeat('z', 2500) WHERE id = 1; + +step s3_update_again: + UPDATE rewrite_test SET data = repeat('w', 2500) WHERE id = 1; + +step s3_vacuum_main_only: + VACUUM (PROCESS_TOAST false) rewrite_test; + +step s2_commit: COMMIT; +step s3_vacuum_toast: + VACUUM pg_toast.rewrite_test_toast; + +step s3_cluster_sort: + SET enable_indexscan = off; + CLUSTER rewrite_test USING rewrite_test_pkey; + RESET enable_indexscan; + +step s3_check_rows: + SELECT id, length(data), left(data, 1) FROM rewrite_test ORDER BY id; + SELECT reltuples FROM pg_class WHERE oid = 'rewrite_test'::regclass; + +id|length|left +--+------+---- + 1| 2500|w + 2| 2500|y +(2 rows) + +reltuples +--------- + 2 +(1 row) + +step s1_release: + SELECT dblink_exec('holder', 'COMMIT'); + SELECT dblink_disconnect('holder'); + +dblink_exec +----------- +COMMIT +(1 row) + +dblink_disconnect +----------------- +OK +(1 row) + + +starting permutation: s1_hold_xmin s2_begin s3_delete_drop s3_vacuum_main_only_drop s2_commit s3_vacuum_toast_drop s3_cluster_sort_drop s3_check_rows_drop s1_release +step s1_hold_xmin: + SELECT dblink_connect('holder', + 'dbname=regress_other_db port=' || current_setting('port')); + SELECT dblink_exec('holder', 'BEGIN'); + SELECT dblink_exec('holder', 'CREATE TEMP TABLE xid_holder(x int)'); + +dblink_connect +-------------- +OK +(1 row) + +dblink_exec +----------- +BEGIN +(1 row) + +dblink_exec +------------ +CREATE TABLE +(1 row) + +step s2_begin: + BEGIN ISOLATION LEVEL REPEATABLE READ; + SELECT 1; + +?column? +-------- + 1 +(1 row) + +step s3_delete_drop: + DELETE FROM rewrite_drop WHERE id = 1; + +step s3_vacuum_main_only_drop: + VACUUM (PROCESS_TOAST false) rewrite_drop; + +step s2_commit: COMMIT; +step s3_vacuum_toast_drop: + VACUUM pg_toast.rewrite_drop_toast; + +step s3_cluster_sort_drop: + SET enable_indexscan = off; + CLUSTER rewrite_drop USING rewrite_drop_row_idx; + RESET enable_indexscan; + +step s3_check_rows_drop: + SELECT id FROM rewrite_drop ORDER BY id; + SELECT reltuples FROM pg_class WHERE oid = 'rewrite_drop'::regclass; + +id +-- + 2 +(1 row) + +reltuples +--------- + 1 +(1 row) + +step s1_release: + SELECT dblink_exec('holder', 'COMMIT'); + SELECT dblink_disconnect('holder'); + +dblink_exec +----------- +COMMIT +(1 row) + +dblink_disconnect +----------------- +OK +(1 row) + + +starting permutation: s1_hold_xmin s2_begin s3_delete_drop s3_vacuum_main_only_drop s2_commit s3_vacuum_toast_drop s3_create_index_wholerow_drop s3_check_rows_drop s1_release +step s1_hold_xmin: + SELECT dblink_connect('holder', + 'dbname=regress_other_db port=' || current_setting('port')); + SELECT dblink_exec('holder', 'BEGIN'); + SELECT dblink_exec('holder', 'CREATE TEMP TABLE xid_holder(x int)'); + +dblink_connect +-------------- +OK +(1 row) + +dblink_exec +----------- +BEGIN +(1 row) + +dblink_exec +------------ +CREATE TABLE +(1 row) + +step s2_begin: + BEGIN ISOLATION LEVEL REPEATABLE READ; + SELECT 1; + +?column? +-------- + 1 +(1 row) + +step s3_delete_drop: + DELETE FROM rewrite_drop WHERE id = 1; + +step s3_vacuum_main_only_drop: + VACUUM (PROCESS_TOAST false) rewrite_drop; + +step s2_commit: COMMIT; +step s3_vacuum_toast_drop: + VACUUM pg_toast.rewrite_drop_toast; + +step s3_create_index_wholerow_drop: + CREATE INDEX rewrite_drop_row2_idx ON rewrite_drop ((rewrite_drop IS NOT NULL)); + +step s3_check_rows_drop: + SELECT id FROM rewrite_drop ORDER BY id; + SELECT reltuples FROM pg_class WHERE oid = 'rewrite_drop'::regclass; + +id +-- + 2 +(1 row) + +reltuples +--------- + 1 +(1 row) + +step s1_release: + SELECT dblink_exec('holder', 'COMMIT'); + SELECT dblink_disconnect('holder'); + +dblink_exec +----------- +COMMIT +(1 row) + +dblink_disconnect +----------------- +OK +(1 row) + diff --git a/contrib/dblink/meson.build b/contrib/dblink/meson.build index e2489f41229..86fbd372b88 100644 --- a/contrib/dblink/meson.build +++ b/contrib/dblink/meson.build @@ -36,6 +36,11 @@ tests += { ], 'regress_args': ['--dlpath', meson.project_build_root() / 'src/test/regress'], }, + 'isolation': { + 'specs': [ + 'rewrite_stale_xmin', + ], + }, 'tap': { 'tests': [ 't/001_auth_scram.pl', diff --git a/contrib/dblink/specs/rewrite_stale_xmin.spec b/contrib/dblink/specs/rewrite_stale_xmin.spec new file mode 100644 index 00000000000..39dedc284d3 --- /dev/null +++ b/contrib/dblink/specs/rewrite_stale_xmin.spec @@ -0,0 +1,321 @@ +# Test that heap rewrites and index builds cope with RECENTLY_DEAD tuples +# whose TOAST data has already been removed. +# +# A transaction in another database holds back the xmin of the rewriting +# backend, but not the removal horizon of this database. The main table and +# its TOAST table are vacuumed separately, with a same-database snapshot that +# keeps the dead tuple released in between, so the tuple survives while its +# TOAST chunks are removed. + +setup +{ + CREATE DATABASE regress_other_db; +} + +setup +{ + CREATE EXTENSION IF NOT EXISTS dblink; + + CREATE TABLE rewrite_test (id int PRIMARY KEY, data text) + WITH (autovacuum_enabled = off); + ALTER TABLE rewrite_test ALTER COLUMN data SET STORAGE EXTERNAL; + INSERT INTO rewrite_test VALUES (1, repeat('x', 2500)); + INSERT INTO rewrite_test VALUES (2, repeat('y', 2500)); + + -- Rename the toast table to a known name so we can VACUUM it directly. + SET allow_system_table_mods TO true; + DO $$DECLARE r record; + BEGIN + SELECT INTO r reltoastrelid::regclass::text AS table_name + FROM pg_class WHERE oid = 'rewrite_test'::regclass; + EXECUTE 'ALTER TABLE ' || r.table_name || ' RENAME TO rewrite_test_toast;'; + END$$; + RESET allow_system_table_mods; + + -- Only a dropped column has TOAST data here. + CREATE TABLE rewrite_drop (id int PRIMARY KEY, data text) + WITH (autovacuum_enabled = off); + ALTER TABLE rewrite_drop ALTER COLUMN data SET STORAGE EXTERNAL; + INSERT INTO rewrite_drop VALUES (1, repeat('x', 2500)); + INSERT INTO rewrite_drop VALUES (2, repeat('y', 2500)); + ALTER TABLE rewrite_drop DROP COLUMN data; + CREATE INDEX rewrite_drop_row_idx ON rewrite_drop + ((rewrite_drop IS NOT NULL), id); + SET allow_system_table_mods TO true; + DO $$DECLARE r record; + BEGIN + SELECT INTO r reltoastrelid::regclass::text AS table_name + FROM pg_class WHERE oid = 'rewrite_drop'::regclass; + EXECUTE 'ALTER TABLE ' || r.table_name || ' RENAME TO rewrite_drop_toast;'; + END$$; + RESET allow_system_table_mods; +} + +teardown +{ + DROP DATABASE regress_other_db; +} + +# Session s1: use dblink to hold a transaction in another database. +# This must start before the DELETE so its XID is older, ensuring +# GetSnapshotData() holds back any rewrites. +session s1 +step s1_hold_xmin +{ + SELECT dblink_connect('holder', + 'dbname=regress_other_db port=' || current_setting('port')); + SELECT dblink_exec('holder', 'BEGIN'); + SELECT dblink_exec('holder', 'CREATE TEMP TABLE xid_holder(x int)'); +} +step s1_release +{ + SELECT dblink_exec('holder', 'COMMIT'); + SELECT dblink_disconnect('holder'); +} + +# Session s2: holds xmin in the SAME database temporarily, so the +# main-table vacuum preserves the dead tuple as RECENTLY_DEAD. +session s2 +step s2_begin +{ + BEGIN ISOLATION LEVEL REPEATABLE READ; + SELECT 1; +} +step s2_commit { COMMIT; } + +# Session s3: performs DML, split vacuum, and the rewrite. +session s3 +step s3_delete +{ + DELETE FROM rewrite_test WHERE id = 1; +} +step s3_update +{ + UPDATE rewrite_test SET data = repeat('z', 2500) WHERE id = 1; +} +step s3_update_again +{ + UPDATE rewrite_test SET data = repeat('w', 2500) WHERE id = 1; +} +step s3_check_rows +{ + SELECT id, length(data), left(data, 1) FROM rewrite_test ORDER BY id; + SELECT reltuples FROM pg_class WHERE oid = 'rewrite_test'::regclass; +} +step s3_vacuum_main_only +{ + VACUUM (PROCESS_TOAST false) rewrite_test; +} +step s3_vacuum_toast +{ + VACUUM pg_toast.rewrite_test_toast; +} +step s3_cluster +{ + CLUSTER rewrite_test USING rewrite_test_pkey; +} +# Use the seqscan-and-sort strategy, which checks the TOAST data while scanning +step s3_cluster_sort +{ + SET enable_indexscan = off; + CLUSTER rewrite_test USING rewrite_test_pkey; + RESET enable_indexscan; +} +step s3_delete_drop +{ + DELETE FROM rewrite_drop WHERE id = 1; +} +step s3_vacuum_main_only_drop +{ + VACUUM (PROCESS_TOAST false) rewrite_drop; +} +step s3_vacuum_toast_drop +{ + VACUUM pg_toast.rewrite_drop_toast; +} +# Sorting evaluates the whole-row reference, which includes the dropped column +step s3_cluster_sort_drop +{ + SET enable_indexscan = off; + CLUSTER rewrite_drop USING rewrite_drop_row_idx; + RESET enable_indexscan; +} +step s3_create_index_wholerow_drop +{ + CREATE INDEX rewrite_drop_row2_idx ON rewrite_drop ((rewrite_drop IS NOT NULL)); +} +step s3_check_rows_drop +{ + SELECT id FROM rewrite_drop ORDER BY id; + SELECT reltuples FROM pg_class WHERE oid = 'rewrite_drop'::regclass; +} +step s3_vacuum_full +{ + VACUUM FULL rewrite_test; +} +step s3_repack +{ + REPACK rewrite_test; +} +step s3_create_index +{ + CREATE INDEX rewrite_test_data_idx ON rewrite_test (data); +} +step s3_create_index_wholerow +{ + CREATE INDEX rewrite_test_row_idx ON rewrite_test ((rewrite_test IS NOT NULL)); +} + +teardown { DROP TABLE IF EXISTS rewrite_test, rewrite_drop; } + +# CLUSTER +permutation + s1_hold_xmin + s2_begin + s3_delete + s3_vacuum_main_only + s2_commit + s3_vacuum_toast + s3_cluster + s1_release + +# CLUSTER, sorting +permutation + s1_hold_xmin + s2_begin + s3_delete + s3_vacuum_main_only + s2_commit + s3_vacuum_toast + s3_cluster_sort + s3_check_rows + s1_release + +# VACUUM FULL +permutation + s1_hold_xmin + s2_begin + s3_delete + s3_vacuum_main_only + s2_commit + s3_vacuum_toast + s3_vacuum_full + s1_release + +# REPACK +permutation + s1_hold_xmin + s2_begin + s3_delete + s3_vacuum_main_only + s2_commit + s3_vacuum_toast + s3_repack + s1_release + +# CREATE INDEX +permutation + s1_hold_xmin + s2_begin + s3_delete + s3_vacuum_main_only + s2_commit + s3_vacuum_toast + s3_create_index + s1_release + +# CREATE INDEX on a whole-row expression +permutation + s1_hold_xmin + s2_begin + s3_delete + s3_vacuum_main_only + s2_commit + s3_vacuum_toast + s3_create_index_wholerow + s1_release + +# Preserve the live successor when a stashed prior version loses its TOAST. +permutation + s1_hold_xmin + s2_begin + s3_update + s3_vacuum_main_only + s2_commit + s3_vacuum_toast + s3_vacuum_full + s3_check_rows + s1_release + +permutation + s1_hold_xmin + s2_begin + s3_update + s3_vacuum_main_only + s2_commit + s3_vacuum_toast + s3_repack + s3_check_rows + s1_release + +permutation + s1_hold_xmin + s2_begin + s3_update + s3_update_again + s3_vacuum_main_only + s2_commit + s3_vacuum_toast + s3_vacuum_full + s3_check_rows + s1_release + +permutation + s1_hold_xmin + s2_begin + s3_update + s3_update_again + s3_vacuum_main_only + s2_commit + s3_vacuum_toast + s3_repack + s3_check_rows + s1_release + +permutation + s1_hold_xmin + s2_begin + s3_update + s3_update_again + s3_vacuum_main_only + s2_commit + s3_vacuum_toast + s3_cluster_sort + s3_check_rows + s1_release + +# CLUSTER, sorting on a whole-row expression, with TOAST data only in a +# dropped column +permutation + s1_hold_xmin + s2_begin + s3_delete_drop + s3_vacuum_main_only_drop + s2_commit + s3_vacuum_toast_drop + s3_cluster_sort_drop + s3_check_rows_drop + s1_release + +# CREATE INDEX on a whole-row expression, with TOAST data only in a dropped +# column +permutation + s1_hold_xmin + s2_begin + s3_delete_drop + s3_vacuum_main_only_drop + s2_commit + s3_vacuum_toast_drop + s3_create_index_wholerow_drop + s3_check_rows_drop + s1_release diff --git a/src/backend/access/heap/heapam_handler.c b/src/backend/access/heap/heapam_handler.c index 1437274b0c6..b08ece448d4 100644 --- a/src/backend/access/heap/heapam_handler.c +++ b/src/backend/access/heap/heapam_handler.c @@ -37,6 +37,7 @@ #include "commands/progress.h" #include "executor/executor.h" #include "miscadmin.h" +#include "optimizer/optimizer.h" #include "pgstat.h" #include "storage/bufmgr.h" #include "storage/bufpage.h" @@ -46,12 +47,24 @@ #include "storage/procarray.h" #include "storage/smgr.h" #include "utils/builtins.h" +#include "utils/injection_point.h" #include "utils/rel.h" +#include "utils/snapmgr.h" #include "utils/tuplesort.h" static void reform_and_rewrite_tuple(HeapTuple tuple, Relation OldHeap, Relation NewHeap, Datum *values, bool *isnull, RewriteState rwstate); +static bool recently_dead_toast_may_be_gone(Relation rel); +static bool check_recently_dead_toast(HeapTuple tuple, TupleDesc tupdesc, + Datum *values, bool *isnull, + TransactionId stable_xmin, + HeapTuple *inlined); +static Bitmapset *index_referenced_varlena_attrs(Relation heap, + IndexInfo *indexInfo); +static bool fetch_recently_dead_toast(TupleDesc tupdesc, + const Bitmapset *attrs, + Datum *values, bool *isnull); static void heap_insert_for_repack(HeapTuple tuple, Relation OldHeap, Relation NewHeap, Datum *values, bool *isnull, BulkInsertState bistate); @@ -608,6 +621,7 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap, bool is_system_catalog; Tuplesortstate *tuplesort; TupleDesc oldTupDesc = RelationGetDescr(OldHeap); + TransactionId stable_xmin; TupleDesc newTupDesc = RelationGetDescr(NewHeap); TupleTableSlot *slot; int natts; @@ -631,6 +645,13 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap, values = palloc_array(Datum, natts); isnull = palloc_array(bool, natts); + /* + * The active snapshot is held until we are done, so no horizon can pass + * its xmin in the meantime. + */ + stable_xmin = ActiveSnapshotSet() ? GetActiveSnapshot()->xmin : + InvalidTransactionId; + /* * In non-concurrent mode, initialize the rewrite operation. This is not * needed in concurrent mode. @@ -706,8 +727,10 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap, for (;;) { HeapTuple tuple; + HeapTuple inlined = NULL; Buffer buf; bool isdead; + bool recently_dead = false; CHECK_FOR_INTERRUPTS(); @@ -794,6 +817,7 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap, break; case HEAPTUPLE_RECENTLY_DEAD: *tups_recently_dead += 1; + recently_dead = true; pg_fallthrough; case HEAPTUPLE_LIVE: /* Live or recently dead, must copy it */ @@ -837,6 +861,30 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap, LockBuffer(buf, BUFFER_LOCK_UNLOCK); + /* + * Other backends may consider a RECENTLY_DEAD tuple dead already, + * so VACUUM or pruning of the TOAST relation may have removed its + * TOAST data before this command started. Nobody can see such a + * tuple anymore, so treat it as dead rather than fail to copy it. + * + * Our AccessExclusiveLock on the TOAST relation keeps VACUUM and + * other backends out of it, but our own TOAST fetches prune its + * pages too, and the horizon they use can still advance up to + * stable_xmin. So if any of the tuple's TOAST data was deleted + * before stable_xmin, it is inlined now, as it could be gone by + * the time the tuple is written out. + */ + if (recently_dead && HeapTupleHasExternal(tuple) && + recently_dead_toast_may_be_gone(OldHeap) && + !check_recently_dead_toast(tuple, oldTupDesc, values, isnull, + stable_xmin, &inlined)) + { + *tups_recently_dead -= 1; + isdead = true; + } + if (inlined != NULL) + tuple = inlined; + if (isdead) { *tups_vacuumed += 1; @@ -887,6 +935,9 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap, ct_val[1] = *num_tuples; pgstat_progress_update_multi_param(2, ct_index, ct_val); } + + if (inlined != NULL) + heap_freetuple(inlined); } if (indexScan != NULL) @@ -908,6 +959,8 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap, pgstat_progress_update_param(PROGRESS_REPACK_PHASE, PROGRESS_REPACK_PHASE_SORT_TUPLES); + INJECTION_POINT("heap-rewrite-before-sort", NULL); + tuplesort_performsort(tuplesort); /* Report that we are now writing new heap */ @@ -1161,6 +1214,8 @@ heapam_index_build_range_scan(Relation heapRelation, BlockNumber previous_blkno = InvalidBlockNumber; BlockNumber root_blkno = InvalidBlockNumber; OffsetNumber root_offsets[MaxHeapTuplesPerPage]; + Bitmapset *detoast_attrs = NULL; + TupleTableSlot *detoast_slot = NULL; /* * sanity checks @@ -1257,6 +1312,20 @@ heapam_index_build_range_scan(Relation heapRelation, !TransactionIdIsValid(OldestXmin)); Assert(snapshot == SnapshotAny || !anyvisible); + /* + * Find the varlena columns whose TOAST data the predicate and the index + * columns may need, for RECENTLY_DEAD tuples; see below. + */ + if (TransactionIdIsValid(OldestXmin) && + recently_dead_toast_may_be_gone(heapRelation)) + { + detoast_attrs = index_referenced_varlena_attrs(heapRelation, + indexInfo); + if (detoast_attrs != NULL) + detoast_slot = MakeSingleTupleTableSlot(RelationGetDescr(heapRelation), + &TTSOpsVirtual); + } + /* Publish number of blocks to scan */ if (progress) { @@ -1294,6 +1363,7 @@ heapam_index_build_range_scan(Relation heapRelation, while ((heapTuple = heap_getnext(scan, ForwardScanDirection)) != NULL) { bool tupleIsAlive; + bool recently_dead = false; CHECK_FOR_INTERRUPTS(); @@ -1416,6 +1486,7 @@ heapam_index_build_range_scan(Relation heapRelation, indexIt = true; /* In any case, exclude the tuple from unique-checking */ tupleIsAlive = false; + recently_dead = true; break; case HEAPTUPLE_INSERT_IN_PROGRESS: @@ -1594,6 +1665,38 @@ heapam_index_build_range_scan(Relation heapRelation, /* Set up for predicate or expression evaluation */ ExecStoreBufferHeapTuple(heapTuple, slot, hscan->rs_cbuf); + econtext->ecxt_scantuple = slot; + + /* + * Other backends may consider a RECENTLY_DEAD tuple dead already, and + * we hold no lock that keeps VACUUM or pruning of the TOAST relation + * from removing its TOAST data, before or while we look at the tuple. + * So fetch the TOAST data that the predicate and the index columns + * may need up front, into a virtual slot that they are evaluated on, + * and skip the tuple if that data is gone: nobody can see the tuple + * anymore. The TOAST data of the other tuples that we index cannot + * go away, as they are live or their deleter is still running. + */ + if (recently_dead && detoast_slot != NULL && + HeapTupleHasExternal(heapTuple)) + { + TupleDesc desc = RelationGetDescr(heapRelation); + MemoryContext oldcxt; + bool complete; + + ExecClearTuple(detoast_slot); + oldcxt = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory); + heap_deform_tuple(heapTuple, desc, detoast_slot->tts_values, + detoast_slot->tts_isnull); + complete = fetch_recently_dead_toast(desc, detoast_attrs, + detoast_slot->tts_values, + detoast_slot->tts_isnull); + MemoryContextSwitchTo(oldcxt); + if (!complete) + continue; + ExecStoreVirtualTuple(detoast_slot); + econtext->ecxt_scantuple = detoast_slot; + } /* * In a partial index, discard tuples that don't satisfy the @@ -1611,7 +1714,7 @@ heapam_index_build_range_scan(Relation heapRelation, * of any expressions needed. */ FormIndexDatum(indexInfo, - slot, + econtext->ecxt_scantuple, estate, values, isnull); @@ -1696,6 +1799,9 @@ heapam_index_build_range_scan(Relation heapRelation, UnregisterSnapshot(snapshot); ExecDropSingleTupleTableSlot(slot); + if (detoast_slot != NULL) + ExecDropSingleTupleTableSlot(detoast_slot); + bms_free(detoast_attrs); FreeExecutorState(estate); @@ -2359,6 +2465,210 @@ reform_and_rewrite_tuple(HeapTuple tuple, heap_freetuple(newtuple); } +/* + * Can a RECENTLY_DEAD tuple of rel whose TOAST data is gone be treated as + * dead? + * + * Not if logical decoding may still need the tuple. The TOAST table of a + * user_catalog_table does not inherit that option, so VACUUM of it ignores + * the replication slots' catalog_xmin, which the table itself respects. + * Skipping such a tuple could silently lose a row that logical decoding + * reads, so keep failing in that case. The TOAST table of a system catalog + * respects catalog_xmin as well. + */ +static bool +recently_dead_toast_may_be_gone(Relation rel) +{ + return !RelationIsAccessibleInLogicalDecoding(rel) || + IsCatalogRelation(rel); +} + +/* + * Check the TOAST data of the on-disk external values of a RECENTLY_DEAD + * tuple. Returns false if some of it is gone. + * + * Dropped columns are checked as well: reform_and_rewrite_tuple() throws + * them away, but a whole-row reference in the expressions of a sort still + * fetches their TOAST data. + * + * Otherwise, if some of it was deleted by a transaction that precedes + * stable_xmin, *inlined is set to a copy of the tuple with all those values + * fetched, so that the TOAST relation does not need to be accessed for the + * tuple anymore. It is set to NULL if the TOAST data is safe until + * stable_xmin goes away. + * + * values and isnull are caller-provided workspace of tupdesc->natts entries. + */ +static bool +check_recently_dead_toast(HeapTuple tuple, TupleDesc tupdesc, + Datum *values, bool *isnull, + TransactionId stable_xmin, HeapTuple *inlined) +{ + bool all_stable = true; + bool complete = true; + bool *fetched; + HeapTuple result; + + *inlined = NULL; + heap_deform_tuple(tuple, tupdesc, values, isnull); + + for (int i = 0; i < tupdesc->natts; i++) + { + CompactAttribute *att = TupleDescCompactAttr(tupdesc, i); + varlena *value; + bool stable; + + if (att->attlen != -1 || isnull[i]) + continue; + + value = (varlena *) DatumGetPointer(values[i]); + if (!VARATT_IS_EXTERNAL_ONDISK(value)) + continue; + if (!heap_toast_value_is_complete(value, stable_xmin, &stable)) + return false; + all_stable &= stable; + } + + if (all_stable) + return true; + + fetched = palloc0_array(bool, tupdesc->natts); + for (int i = 0; i < tupdesc->natts; i++) + { + CompactAttribute *att = TupleDescCompactAttr(tupdesc, i); + varlena *value; + + if (att->attlen != -1 || isnull[i]) + continue; + /* reform_and_rewrite_tuple() throws dropped columns away anyway */ + if (att->attisdropped) + { + isnull[i] = true; + continue; + } + + value = (varlena *) DatumGetPointer(values[i]); + if (!VARATT_IS_EXTERNAL_ONDISK(value)) + continue; + value = heap_toast_fetch_value_if_complete(value); + if (value == NULL) + { + complete = false; + break; + } + values[i] = PointerGetDatum(value); + fetched[i] = true; + } + + if (complete) + { + result = heap_form_tuple(tupdesc, values, isnull); + + /* rewriteheap.c needs the identity and visibility information */ + result->t_self = tuple->t_self; + result->t_tableOid = tuple->t_tableOid; + result->t_data->t_choice = tuple->t_data->t_choice; + result->t_data->t_ctid = tuple->t_data->t_ctid; + result->t_data->t_infomask &= ~HEAP_XACT_MASK; + result->t_data->t_infomask |= + tuple->t_data->t_infomask & HEAP_XACT_MASK; + result->t_data->t_infomask2 &= ~HEAP2_XACT_MASK; + result->t_data->t_infomask2 |= + tuple->t_data->t_infomask2 & HEAP2_XACT_MASK; + *inlined = result; + } + + for (int i = 0; i < tupdesc->natts; i++) + { + if (fetched[i]) + pfree(DatumGetPointer(values[i])); + } + pfree(fetched); + + return complete; +} + +/* + * Return the varlena columns of heap that the index columns, expressions and + * predicate of the index reference, as plain attribute numbers, or NULL if + * there are none. A whole-row reference needs all of them. + */ +static Bitmapset * +index_referenced_varlena_attrs(Relation heap, IndexInfo *indexInfo) +{ + TupleDesc desc = RelationGetDescr(heap); + Bitmapset *refattrs = NULL; + Bitmapset *result = NULL; + bool wholerow; + + for (int i = 0; i < indexInfo->ii_NumIndexAttrs; i++) + { + AttrNumber attnum = indexInfo->ii_IndexAttrNumbers[i]; + + if (attnum != 0) + refattrs = bms_add_member(refattrs, + attnum - FirstLowInvalidHeapAttributeNumber); + } + pull_varattnos((Node *) indexInfo->ii_Expressions, 1, &refattrs); + pull_varattnos((Node *) indexInfo->ii_Predicate, 1, &refattrs); + + wholerow = bms_is_member(InvalidAttrNumber - FirstLowInvalidHeapAttributeNumber, + refattrs); + + for (AttrNumber attnum = 1; attnum <= desc->natts; attnum++) + { + if (TupleDescCompactAttr(desc, attnum - 1)->attlen != -1) + continue; + if (wholerow || + bms_is_member(attnum - FirstLowInvalidHeapAttributeNumber, + refattrs)) + result = bms_add_member(result, attnum); + } + bms_free(refattrs); + + return result; +} + +/* + * Replace the on-disk external values of the columns in attrs, in the + * deformed tuple values/isnull, with their TOAST data, fetched into the + * current memory context. Dropped columns are nulled out, so that a + * whole-row reference does not try to fetch their TOAST data either. + * + * Returns false if TOAST data is gone. + */ +static bool +fetch_recently_dead_toast(TupleDesc tupdesc, const Bitmapset *attrs, + Datum *values, bool *isnull) +{ + int attnum = -1; + + while ((attnum = bms_next_member(attrs, attnum)) >= 0) + { + int i = attnum - 1; + varlena *value; + + if (isnull[i]) + continue; + if (TupleDescCompactAttr(tupdesc, i)->attisdropped) + { + isnull[i] = true; + continue; + } + + value = (varlena *) DatumGetPointer(values[i]); + if (!VARATT_IS_EXTERNAL_ONDISK(value)) + continue; + + value = heap_toast_fetch_value_if_complete(value); + if (value == NULL) + return false; + values[i] = PointerGetDatum(value); + } + + return true; +} + /* * Insert tuple when processing REPACK CONCURRENTLY. * diff --git a/src/backend/access/heap/heaptoast.c b/src/backend/access/heap/heaptoast.c index e329662b683..6d86b714637 100644 --- a/src/backend/access/heap/heaptoast.c +++ b/src/backend/access/heap/heaptoast.c @@ -28,11 +28,20 @@ #include "access/genam.h" #include "access/heapam.h" #include "access/heaptoast.h" +#include "access/table.h" #include "access/toast_helper.h" #include "access/toast_internals.h" +#include "catalog/pg_am.h" #include "utils/fmgroids.h" +static bool heap_fetch_toast_chunks(Relation toastrel, Oid8 valueid, + int32 attrsize, int32 sliceoffset, + int32 slicelength, varlena *result, + bool missing_ok, + TransactionId stable_xmin, bool *stable); + + /* ---------- * heap_toast_delete - * @@ -641,6 +650,30 @@ void heap_fetch_toast_slice(Relation toastrel, Oid8 valueid, int32 attrsize, int32 sliceoffset, int32 slicelength, varlena *result) +{ + (void) heap_fetch_toast_chunks(toastrel, valueid, attrsize, + sliceoffset, slicelength, result, false, + InvalidTransactionId, NULL); +} + +/* + * Workhorse of heap_fetch_toast_slice() and heap_toast_value_is_complete(). + * + * If result is NULL, the chunks are only checked, not copied. If missing_ok + * is true, returns false instead of raising an error when chunks are missing + * or do not have the expected numbers or sizes. + * + * If stable is not NULL, *stable is set to false if any chunk has been + * deleted, or locked by a multixact, by a transaction that does not follow + * stable_xmin. Such a chunk may be pruned away as soon as no snapshot needs + * it anymore, while the other chunks are safe for as long as a snapshot + * with xmin stable_xmin is held. + */ +static bool +heap_fetch_toast_chunks(Relation toastrel, Oid8 valueid, int32 attrsize, + int32 sliceoffset, int32 slicelength, + varlena *result, bool missing_ok, + TransactionId stable_xmin, bool *stable) { Relation *toastidxs; ScanKeyData toastkey[3]; @@ -656,6 +689,7 @@ heap_fetch_toast_slice(Relation toastrel, Oid8 valueid, int32 attrsize, int validIndex; int32 max_chunk_size; Oid toast_typid; + bool complete = true; /* Look for the valid index of toast relation */ validIndex = toast_open_indexes(toastrel, @@ -711,6 +745,8 @@ heap_fetch_toast_slice(Relation toastrel, Oid8 valueid, int32 attrsize, * The index is on (valueid, chunkidx) so they will come in order */ expectedchunk = startchunk; + if (stable != NULL) + *stable = true; while ((ttup = systable_getnext_ordered(toastscan, ForwardScanDirection)) != NULL) { int32 curchunk; @@ -749,9 +785,27 @@ heap_fetch_toast_slice(Relation toastrel, Oid8 valueid, int32 attrsize, chunkdata = NULL; } + if (stable != NULL && *stable) + { + HeapTupleHeader chunkhdr = ttup->t_data; + + if (!(chunkhdr->t_infomask & HEAP_XMAX_INVALID) && + !HEAP_XMAX_IS_LOCKED_ONLY(chunkhdr->t_infomask) && + ((chunkhdr->t_infomask & HEAP_XMAX_IS_MULTI) || + !TransactionIdIsValid(stable_xmin) || + !TransactionIdFollowsOrEquals(HeapTupleHeaderGetRawXmax(chunkhdr), + stable_xmin))) + *stable = false; + } + /* * Some checks on the data we've found */ + if (missing_ok && (curchunk != expectedchunk || curchunk > endchunk)) + { + complete = false; + break; + } if (curchunk != expectedchunk) ereport(ERROR, (errcode(ERRCODE_DATA_CORRUPTED), @@ -767,6 +821,11 @@ heap_fetch_toast_slice(Relation toastrel, Oid8 valueid, int32 attrsize, RelationGetRelationName(toastrel)))); expected_size = curchunk < totalchunks - 1 ? max_chunk_size : attrsize - ((totalchunks - 1) * max_chunk_size); + if (missing_ok && chunksize != expected_size) + { + complete = false; + break; + } if (chunksize != expected_size) ereport(ERROR, (errcode(ERRCODE_DATA_CORRUPTED), @@ -775,6 +834,11 @@ heap_fetch_toast_slice(Relation toastrel, Oid8 valueid, int32 attrsize, curchunk, totalchunks, valueid, RelationGetRelationName(toastrel)))); + expectedchunk++; + + if (result == NULL) + continue; + /* * Copy the data into proper place in our result */ @@ -789,14 +853,14 @@ heap_fetch_toast_slice(Relation toastrel, Oid8 valueid, int32 attrsize, (curchunk * max_chunk_size - sliceoffset) + chcpystrt, chunkdata + chcpystrt, (chcpyend - chcpystrt) + 1); - - expectedchunk++; } /* * Final checks that we successfully fetched the datum */ - if (expectedchunk != (endchunk + 1)) + if (missing_ok && expectedchunk != (endchunk + 1)) + complete = false; + else if (expectedchunk != (endchunk + 1)) ereport(ERROR, (errcode(ERRCODE_DATA_CORRUPTED), errmsg_internal("missing chunk number %d for toast value %" PRIu64 " in %s", @@ -806,4 +870,100 @@ heap_fetch_toast_slice(Relation toastrel, Oid8 valueid, int32 attrsize, /* End scan and close indexes. */ systable_endscan_ordered(toastscan); toast_close_indexes(toastidxs, num_indexes, AccessShareLock); + + return complete; +} + +/* + * Fetch, or with fetch = false only check, all chunks of an on-disk external + * value. Returns false if chunks are missing or inconsistent. See + * heap_fetch_toast_chunks() for stable_xmin and stable. + */ +static bool +heap_toast_fetch_if_complete(varlena *attr, bool fetch, varlena **result, + TransactionId stable_xmin, bool *stable) +{ + toast_external_data toast_ext_data; + int32 attrsize; + Relation toastrel; + varlena *value = NULL; + bool complete; + + Assert(VARATT_IS_EXTERNAL_ONDISK(attr)); + + toast_external_info_get(attr, &toast_ext_data); + attrsize = VARATT_EXTINFO_GET_EXTSIZE(toast_ext_data.extinfo); + + if (fetch) + { + value = (varlena *) palloc(attrsize + VARHDRSZ); + if (VARATT_EXTINFO_IS_COMPRESSED(toast_ext_data.extinfo, + toast_ext_data.rawsize)) + SET_VARSIZE_COMPRESSED(value, attrsize + VARHDRSZ); + else + SET_VARSIZE(value, attrsize + VARHDRSZ); + *result = value; + } + + if (stable != NULL) + *stable = true; + if (attrsize == 0) + return true; + + toastrel = table_open(toast_ext_data.toastrelid, AccessShareLock); + Assert(toastrel->rd_rel->relam == HEAP_TABLE_AM_OID); + complete = heap_fetch_toast_chunks(toastrel, toast_ext_data.valueid, + attrsize, 0, attrsize, value, true, + stable_xmin, stable); + table_close(toastrel, AccessShareLock); + + if (!complete && fetch) + { + pfree(value); + *result = NULL; + } + + return complete; +} + +/* ---------- + * heap_toast_value_is_complete + * + * Check that all chunks of an on-disk external value stored in a heap + * TOAST relation are there. *stable is set to false if some of them may + * still be pruned away while a snapshot with xmin stable_xmin is held, + * because they were deleted by a transaction that precedes stable_xmin. + * + * Only meant for the TOAST data of a RECENTLY_DEAD tuple, which VACUUM or + * pruning of the TOAST relation may have removed already, as other + * backends may consider the tuple dead. Returns false if chunks are + * missing, out of sequence or of an unexpected size, which is what a value + * that is gone or being removed looks like. + * ---------- + */ +bool +heap_toast_value_is_complete(varlena *attr, TransactionId stable_xmin, + bool *stable) +{ + return heap_toast_fetch_if_complete(attr, false, NULL, + stable_xmin, stable); +} + +/* ---------- + * heap_toast_fetch_value_if_complete + * + * Like detoast_external_attr() for an on-disk external value stored in a + * heap TOAST relation, but returns NULL instead of raising an error if + * chunks are missing. Like heap_toast_value_is_complete(), only meant for + * the TOAST data of a RECENTLY_DEAD tuple. + * ---------- + */ +varlena * +heap_toast_fetch_value_if_complete(varlena *attr) +{ + varlena *result; + + (void) heap_toast_fetch_if_complete(attr, true, &result, + InvalidTransactionId, NULL); + return result; } diff --git a/src/include/access/heaptoast.h b/src/include/access/heaptoast.h index 4c3fda8a5f9..9f4a78d6958 100644 --- a/src/include/access/heaptoast.h +++ b/src/include/access/heaptoast.h @@ -160,4 +160,18 @@ extern void heap_fetch_toast_slice(Relation toastrel, Oid8 valueid, int32 attrsize, int32 sliceoffset, int32 slicelength, varlena *result); +/* ---------- + * heap_toast_value_is_complete + * heap_toast_fetch_value_if_complete + * + * Check or fetch an on-disk external value stored in a heap TOAST + * relation, reporting missing chunks to the caller instead of raising an + * error. Only meant for the TOAST data of RECENTLY_DEAD tuples. + * ---------- + */ +extern bool heap_toast_value_is_complete(varlena *attr, + TransactionId stable_xmin, + bool *stable); +extern varlena *heap_toast_fetch_value_if_complete(varlena *attr); + #endif /* HEAPTOAST_H */ diff --git a/src/test/modules/injection_points/Makefile b/src/test/modules/injection_points/Makefile index a7a16d5016a..4a57b7c7edc 100644 --- a/src/test/modules/injection_points/Makefile +++ b/src/test/modules/injection_points/Makefile @@ -20,6 +20,7 @@ REGRESS_OPTS = --dlpath=$(top_builddir)/src/test/regress WAIT_CLEANUP_TST = $(if $(filter win32,$(PORTNAME)),,wait_cleanup) ISOLATION = basic \ + heap_rewrite_toast_prune \ inplace \ reindex_concurrently_deferred \ reindex_concurrently_toast \ diff --git a/src/test/modules/injection_points/expected/heap_rewrite_toast_prune.out b/src/test/modules/injection_points/expected/heap_rewrite_toast_prune.out new file mode 100644 index 00000000000..c45ed7e9e37 --- /dev/null +++ b/src/test/modules/injection_points/expected/heap_rewrite_toast_prune.out @@ -0,0 +1,44 @@ +Parsed test spec with 3 sessions + +starting permutation: s1_begin s3_update s2_begin s3_cluster s1_commit s2_commit s2_wakeup s3_check_rows +step s1_begin: + BEGIN ISOLATION LEVEL REPEATABLE READ; + SELECT 1; + +?column? +-------- + 1 +(1 row) + +step s3_update: + UPDATE rewrite_test SET data = repeat('z', 7900) WHERE id = 1; + +step s2_begin: + BEGIN; + CREATE TEMP TABLE xid_holder (x int); + +step s3_cluster: + CLUSTER rewrite_test USING rewrite_test_k_idx; + +step s1_commit: COMMIT; +step s2_commit: COMMIT; +step s2_wakeup: + SELECT FROM injection_points_detach('heap-rewrite-before-sort'); + SELECT FROM injection_points_wakeup('heap-rewrite-before-sort'); + +step s3_cluster: <... completed> +step s3_check_rows: + SELECT id, k, length(data), left(data, 1) FROM rewrite_test ORDER BY id; + SELECT reltuples FROM pg_class WHERE oid = 'rewrite_test'::regclass; + +id|k|length|left +--+-+------+---- + 1|a| 7900|z + 2|b| 7900|y +(2 rows) + +reltuples +--------- + 3 +(1 row) + diff --git a/src/test/modules/injection_points/meson.build b/src/test/modules/injection_points/meson.build index cf9cb219548..762779c6e75 100644 --- a/src/test/modules/injection_points/meson.build +++ b/src/test/modules/injection_points/meson.build @@ -28,6 +28,7 @@ test_install_data += files( injection_points_isolation = [ 'basic', + 'heap_rewrite_toast_prune', 'inplace', 'reindex_concurrently_deferred', 'reindex_concurrently_toast', diff --git a/src/test/modules/injection_points/specs/heap_rewrite_toast_prune.spec b/src/test/modules/injection_points/specs/heap_rewrite_toast_prune.spec new file mode 100644 index 00000000000..2c38a550b8e --- /dev/null +++ b/src/test/modules/injection_points/specs/heap_rewrite_toast_prune.spec @@ -0,0 +1,97 @@ +# Test that a heap rewrite copes with the TOAST data of a RECENTLY_DEAD +# tuple being pruned away by the rewrite itself. +# +# A snapshot held by s1 makes the old version of the updated row +# RECENTLY_DEAD, while the xmin of the rewrite is held back only by the XID +# of s2, which is newer than the update. Once both are gone, the TOAST +# fetches of the rewrite can prune the TOAST chunks of the old version, +# before it is written out after the sort. The enum sort key makes the +# sort look up pg_enum, which takes a new catalog snapshot and so lets the +# rewrite see the new horizon. + +setup +{ + CREATE EXTENSION injection_points; + + CREATE TYPE rewrite_enum AS ENUM ('b'); +} + +# Values added before an existing one need a lookup in pg_enum to compare. +setup +{ + ALTER TYPE rewrite_enum ADD VALUE 'a' BEFORE 'b'; +} + +setup +{ + CREATE TABLE rewrite_test (id int, k rewrite_enum, data text) + WITH (autovacuum_enabled = off); + ALTER TABLE rewrite_test ALTER COLUMN data SET STORAGE EXTERNAL; + CREATE INDEX rewrite_test_k_idx ON rewrite_test (k); + -- four TOAST chunks per value, which fill a TOAST page + INSERT INTO rewrite_test VALUES (1, 'a', repeat('x', 7900)); + INSERT INTO rewrite_test VALUES (2, 'b', repeat('y', 7900)); +} + +teardown +{ + DROP TABLE rewrite_test; + DROP TYPE rewrite_enum; + DROP EXTENSION injection_points; +} + +# s1 holds back the removal horizon with a snapshot. +session s1 +step s1_begin +{ + BEGIN ISOLATION LEVEL REPEATABLE READ; + SELECT 1; +} +step s1_commit { COMMIT; } + +# s2 holds back the xmin of the rewrite with an XID that follows the update, +# and sends invalidations when it commits. +session s2 +step s2_begin +{ + BEGIN; + CREATE TEMP TABLE xid_holder (x int); +} +step s2_commit { COMMIT; } +step s2_wakeup +{ + SELECT FROM injection_points_detach('heap-rewrite-before-sort'); + SELECT FROM injection_points_wakeup('heap-rewrite-before-sort'); +} + +session s3 +setup +{ + SELECT FROM injection_points_set_local(); + SELECT FROM injection_points_attach('heap-rewrite-before-sort', 'wait'); + SET enable_indexscan = off; +} +step s3_update +{ + UPDATE rewrite_test SET data = repeat('z', 7900) WHERE id = 1; +} +step s3_cluster +{ + CLUSTER rewrite_test USING rewrite_test_k_idx; +} +# reltuples counts the old version of the row, if it was kept +step s3_check_rows +{ + SELECT id, k, length(data), left(data, 1) FROM rewrite_test ORDER BY id; + SELECT reltuples FROM pg_class WHERE oid = 'rewrite_test'::regclass; +} + +permutation + s1_begin + s3_update + s2_begin + s3_cluster + s1_commit + s2_commit + s2_wakeup + s3_check_rows -- 2.54.0 (Apple Git-157)