From 50e7efdeca0f13678d523f7ea74bd0e24079e889 Mon Sep 17 00:00:00 2001 From: Konstantin Knizhnik Date: Tue, 1 Dec 2026 16:44:15 +0200 Subject: [PATCH v9] 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. The rewrite holds AccessExclusiveLock on the TOAST relation, so nothing can be removed after the check, and the tuple does not need to be inlined before a sort. A dead tuple goes through rewrite_heap_dead_tuple() as usual, so update chains stashed in rewriteheap.c are handled as before. - 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. 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 | 752 ++++++++++++++++++ contrib/dblink/meson.build | 5 + contrib/dblink/specs/rewrite_stale_xmin.spec | 249 ++++++ src/backend/access/heap/heapam_handler.c | 213 ++++- src/backend/access/heap/heaptoast.c | 132 ++- src/include/access/heaptoast.h | 12 + 8 files changed, 1363 insertions(+), 4 deletions(-) create mode 100644 contrib/dblink/expected/rewrite_stale_xmin.out create mode 100644 contrib/dblink/specs/rewrite_stale_xmin.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..168c6ea3f4b --- /dev/null +++ b/contrib/dblink/expected/rewrite_stale_xmin.out @@ -0,0 +1,752 @@ +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) + 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..c0a9f390e69 --- /dev/null +++ b/contrib/dblink/specs/rewrite_stale_xmin.spec @@ -0,0 +1,249 @@ +# 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; +} + +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_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; } + +# 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 diff --git a/src/backend/access/heap/heapam_handler.c b/src/backend/access/heap/heapam_handler.c index 1437274b0c6..acea6539873 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" @@ -52,6 +53,14 @@ 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 heap_tuple_toast_is_complete(HeapTuple tuple, TupleDesc tupdesc, + Datum *values, bool *isnull); +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); @@ -708,6 +717,7 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap, HeapTuple tuple; Buffer buf; bool isdead; + bool recently_dead = false; CHECK_FOR_INTERRUPTS(); @@ -794,6 +804,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 +848,24 @@ 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. + * We hold AccessExclusiveLock on the TOAST relation, so no TOAST + * data can go away from now on, and it is enough to check here + * even if the tuple is written out only after the sort. + */ + if (recently_dead && HeapTupleHasExternal(tuple) && + recently_dead_toast_may_be_gone(OldHeap) && + !heap_tuple_toast_is_complete(tuple, oldTupDesc, + values, isnull)) + { + *tups_recently_dead -= 1; + isdead = true; + } + if (isdead) { *tups_vacuumed += 1; @@ -1161,6 +1190,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 +1288,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 +1339,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 +1462,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 +1641,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 +1690,7 @@ heapam_index_build_range_scan(Relation heapRelation, * of any expressions needed. */ FormIndexDatum(indexInfo, - slot, + econtext->ecxt_scantuple, estate, values, isnull); @@ -1696,6 +1775,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 +2441,135 @@ 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 that the TOAST data of the on-disk external values of a tuple, other + * than those of dropped columns, is all there. + * + * values and isnull are caller-provided workspace of tupdesc->natts entries. + */ +static bool +heap_tuple_toast_is_complete(HeapTuple tuple, TupleDesc tupdesc, + Datum *values, bool *isnull) +{ + heap_deform_tuple(tuple, tupdesc, values, isnull); + + for (int i = 0; i < tupdesc->natts; i++) + { + CompactAttribute *att = TupleDescCompactAttr(tupdesc, i); + varlena *value; + + /* reform_tuple() throws away dropped columns */ + if (att->attlen != -1 || isnull[i] || att->attisdropped) + continue; + + value = (varlena *) DatumGetPointer(values[i]); + if (VARATT_IS_EXTERNAL_ONDISK(value) && + !heap_toast_value_is_complete(value)) + return false; + } + + return true; +} + +/* + * 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..da3a3a02245 100644 --- a/src/backend/access/heap/heaptoast.c +++ b/src/backend/access/heap/heaptoast.c @@ -28,11 +28,19 @@ #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); + + /* ---------- * heap_toast_delete - * @@ -641,6 +649,22 @@ 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); +} + +/* + * 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. + */ +static bool +heap_fetch_toast_chunks(Relation toastrel, Oid8 valueid, int32 attrsize, + int32 sliceoffset, int32 slicelength, + varlena *result, bool missing_ok) { Relation *toastidxs; ScanKeyData toastkey[3]; @@ -656,6 +680,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, @@ -752,6 +777,11 @@ heap_fetch_toast_slice(Relation toastrel, Oid8 valueid, int32 attrsize, /* * 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 +797,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 +810,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 +829,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 +846,90 @@ 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. + */ +static bool +heap_toast_fetch_if_complete(varlena *attr, bool fetch, varlena **result) +{ + 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 (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); + 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. + * + * 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) +{ + return heap_toast_fetch_if_complete(attr, false, NULL); +} + +/* ---------- + * 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); + return result; } diff --git a/src/include/access/heaptoast.h b/src/include/access/heaptoast.h index 4c3fda8a5f9..6fa9e6ee46d 100644 --- a/src/include/access/heaptoast.h +++ b/src/include/access/heaptoast.h @@ -160,4 +160,16 @@ 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); +extern varlena *heap_toast_fetch_value_if_complete(varlena *attr); + #endif /* HEAPTOAST_H */ -- 2.54.0 (Apple Git-157)