Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 303ba05

Browse files
Test that vacuum removes tuples older than OldestXmin
If vacuum fails to prune a tuple killed before OldestXmin, it will decide to freeze its xmax and later error out in pre-freeze checks. Add a test reproducing this scenario to the recovery suite which creates a table on a primary, updates the table to generate dead tuples for vacuum, and then, during the vacuum, uses a replica to force GlobalVisState->maybe_needed on the primary to move backwards and precede the value of OldestXmin set at the beginning of vacuuming the table. This test is coverage for a case fixed in 83c39a1. The test was originally committed to master in aa60798 but later reverted in efcbb76 due to test instability. The test requires multiple index passes. In Postgres 17+, vacuum uses a TID store for the dead TIDs that is very space efficient. With the old minimum maintenance_work_mem of 1 MB, it required a large number of dead rows to generate enough dead TIDs to force multiple index vacuuming passes. Once the source code changes were made to allow a minimum maintenance_work_mem value of 64kB, the test could be made much faster and more stable. Author: Melanie Plageman <[email protected]> Reviewed-by: John Naylor <[email protected]> Reviewed-by: Peter Geoghegan <[email protected]> Discussion: https://postgr.es/m/CAAKRu_ZJBkidusDut6i%3DbDCiXzJEp93GC1%2BNFaZt4eqanYF3Kw%40mail.gmail.com Backpatch-through: 17
1 parent 054beeb commit 303ba05

File tree

2 files changed

+280
-1
lines changed

2 files changed

+280
-1
lines changed

src/test/recovery/meson.build

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,8 @@ tests += {
5454
't/043_no_contrecord_switch.pl',
5555
't/044_invalidate_inactive_slots.pl',
5656
't/045_archive_restartpoint.pl',
57-
't/047_checkpoint_physical_slot.pl'
57+
't/047_checkpoint_physical_slot.pl',
58+
't/048_vacuum_horizon_floor.pl'
5859
],
5960
},
6061
}
Lines changed: 278 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,278 @@
1+
use strict;
2+
use warnings;
3+
use PostgreSQL::Test::Cluster;
4+
use Test::More;
5+
6+
# Test that vacuum prunes away all dead tuples killed before OldestXmin
7+
#
8+
# This test creates a table on a primary, updates the table to generate dead
9+
# tuples for vacuum, and then, during the vacuum, uses the replica to force
10+
# GlobalVisState->maybe_needed on the primary to move backwards and precede
11+
# the value of OldestXmin set at the beginning of vacuuming the table.
12+
13+
# Set up nodes
14+
my $node_primary = PostgreSQL::Test::Cluster->new('primary');
15+
$node_primary->init(allows_streaming => 'physical');
16+
17+
# io_combine_limit is set to 1 to avoid pinning more than one buffer at a time
18+
# to ensure test determinism.
19+
$node_primary->append_conf(
20+
'postgresql.conf', qq[
21+
hot_standby_feedback = on
22+
autovacuum = off
23+
log_min_messages = INFO
24+
maintenance_work_mem = 64
25+
io_combine_limit = 1
26+
]);
27+
$node_primary->start;
28+
29+
my $node_replica = PostgreSQL::Test::Cluster->new('standby');
30+
31+
$node_primary->backup('my_backup');
32+
$node_replica->init_from_backup($node_primary, 'my_backup',
33+
has_streaming => 1);
34+
35+
$node_replica->start;
36+
37+
my $test_db = "test_db";
38+
$node_primary->safe_psql('postgres', "CREATE DATABASE $test_db");
39+
40+
# Save the original connection info for later use
41+
my $orig_conninfo = $node_primary->connstr();
42+
43+
my $table1 = "vac_horizon_floor_table";
44+
45+
# Long-running Primary Session A
46+
my $psql_primaryA =
47+
$node_primary->background_psql($test_db, on_error_stop => 1);
48+
49+
# Long-running Primary Session B
50+
my $psql_primaryB =
51+
$node_primary->background_psql($test_db, on_error_stop => 1);
52+
53+
# Our test relies on two rounds of index vacuuming for reasons elaborated
54+
# later. To trigger two rounds of index vacuuming, we must fill up the
55+
# TIDStore with dead items partway through a vacuum of the table. The number
56+
# of rows is just enough to ensure we exceed maintenance_work_mem on all
57+
# supported platforms, while keeping test runtime as short as we can.
58+
my $nrows = 2000;
59+
60+
# Because vacuum's first pass, pruning, is where we use the GlobalVisState to
61+
# check tuple visibility, GlobalVisState->maybe_needed must move backwards
62+
# during pruning before checking the visibility for a tuple which would have
63+
# been considered HEAPTUPLE_DEAD prior to maybe_needed moving backwards but
64+
# HEAPTUPLE_RECENTLY_DEAD compared to the new, older value of maybe_needed.
65+
#
66+
# We must not only force the horizon on the primary to move backwards but also
67+
# force the vacuuming backend's GlobalVisState to be updated. GlobalVisState
68+
# is forced to update during index vacuuming.
69+
#
70+
# _bt_pendingfsm_finalize() calls GetOldestNonRemovableTransactionId() at the
71+
# end of a round of index vacuuming, updating the backend's GlobalVisState
72+
# and, in our case, moving maybe_needed backwards.
73+
#
74+
# Then vacuum's first (pruning) pass will continue and pruning will find our
75+
# later inserted and updated tuple HEAPTUPLE_RECENTLY_DEAD when compared to
76+
# maybe_needed but HEAPTUPLE_DEAD when compared to OldestXmin.
77+
#
78+
# Thus, we must force at least two rounds of index vacuuming to ensure that
79+
# some tuple visibility checks will happen after a round of index vacuuming.
80+
# To accomplish this, we set maintenance_work_mem to its minimum value and
81+
# insert and delete enough rows that we force at least one round of index
82+
# vacuuming before getting to a dead tuple which was killed after the standby
83+
# is disconnected.
84+
$node_primary->safe_psql($test_db, qq[
85+
CREATE TABLE ${table1}(col1 int)
86+
WITH (autovacuum_enabled=false, fillfactor=10);
87+
INSERT INTO $table1 VALUES(7);
88+
INSERT INTO $table1 SELECT generate_series(1, $nrows) % 3;
89+
CREATE INDEX on ${table1}(col1);
90+
DELETE FROM $table1 WHERE col1 = 0;
91+
INSERT INTO $table1 VALUES(7);
92+
]);
93+
94+
# We will later move the primary forward while the standby is disconnected.
95+
# For now, however, there is no reason not to wait for the standby to catch
96+
# up.
97+
my $primary_lsn = $node_primary->lsn('flush');
98+
$node_primary->wait_for_catchup($node_replica, 'replay', $primary_lsn);
99+
100+
# Test that the WAL receiver is up and running.
101+
$node_replica->poll_query_until($test_db, qq[
102+
SELECT EXISTS (SELECT * FROM pg_stat_wal_receiver);] , 't');
103+
104+
# Set primary_conninfo to something invalid on the replica and reload the
105+
# config. Once the config is reloaded, the startup process will force the WAL
106+
# receiver to restart and it will be unable to reconnect because of the
107+
# invalid connection information.
108+
$node_replica->safe_psql($test_db, qq[
109+
ALTER SYSTEM SET primary_conninfo = '';
110+
SELECT pg_reload_conf();
111+
]);
112+
113+
# Wait until the WAL receiver has shut down and been unable to start up again.
114+
$node_replica->poll_query_until($test_db, qq[
115+
SELECT EXISTS (SELECT * FROM pg_stat_wal_receiver);] , 'f');
116+
117+
# Now insert and update a tuple which will be visible to the vacuum on the
118+
# primary but which will have xmax newer than the oldest xmin on the standby
119+
# that was recently disconnected.
120+
my $res = $psql_primaryA->query_safe(
121+
qq[
122+
INSERT INTO $table1 VALUES (99);
123+
UPDATE $table1 SET col1 = 100 WHERE col1 = 99;
124+
SELECT 'after_update';
125+
]
126+
);
127+
128+
# Make sure the UPDATE finished
129+
like($res, qr/^after_update$/m, "UPDATE occurred on primary session A");
130+
131+
# Open a cursor on the primary whose pin will keep VACUUM from getting a
132+
# cleanup lock on the first page of the relation. We want VACUUM to be able to
133+
# start, calculate initial values for OldestXmin and GlobalVisState and then
134+
# be unable to proceed with pruning our dead tuples. This will allow us to
135+
# reconnect the standby and push the horizon back before we start actual
136+
# pruning and vacuuming.
137+
my $primary_cursor1 = "vac_horizon_floor_cursor1";
138+
139+
# The first value inserted into the table was a 7, so FETCH FORWARD should
140+
# return a 7. That's how we know the cursor has a pin.
141+
# Disable index scans so the cursor pins heap pages and not index pages.
142+
$res = $psql_primaryB->query_safe(
143+
qq[
144+
BEGIN;
145+
SET enable_bitmapscan = off;
146+
SET enable_indexscan = off;
147+
SET enable_indexonlyscan = off;
148+
DECLARE $primary_cursor1 CURSOR FOR SELECT * FROM $table1 WHERE col1 = 7;
149+
FETCH $primary_cursor1;
150+
]
151+
);
152+
153+
is($res, 7, qq[Cursor query returned $res. Expected value 7.]);
154+
155+
# Get the PID of the session which will run the VACUUM FREEZE so that we can
156+
# use it to filter pg_stat_activity later.
157+
my $vacuum_pid = $psql_primaryA->query_safe("SELECT pg_backend_pid();");
158+
159+
# Now start a VACUUM FREEZE on the primary. It will call vacuum_get_cutoffs()
160+
# and establish values of OldestXmin and GlobalVisState which are newer than
161+
# all of our dead tuples. Then it will be unable to get a cleanup lock to
162+
# start pruning, so it will hang.
163+
#
164+
# We use VACUUM FREEZE because it will wait for a cleanup lock instead of
165+
# skipping the page pinned by the cursor. Note that works because the target
166+
# tuple's xmax precedes OldestXmin which ensures that lazy_scan_noprune() will
167+
# return false and we will wait for the cleanup lock.
168+
#
169+
# Disable any prefetching, parallelism, or other concurrent I/O by vacuum. The
170+
# pages of the heap must be processed in order by a single worker to ensure
171+
# test stability (PARALLEL 0 shouldn't be necessary but guards against the
172+
# possibility of parallel heap vacuuming).
173+
$psql_primaryA->{stdin} .= qq[
174+
SET maintenance_io_concurrency = 0;
175+
VACUUM (VERBOSE, FREEZE, PARALLEL 0) $table1;
176+
\\echo VACUUM
177+
];
178+
179+
# Make sure the VACUUM command makes it to the server.
180+
$psql_primaryA->{run}->pump_nb();
181+
182+
# Make sure that the VACUUM has already called vacuum_get_cutoffs() and is
183+
# just waiting on the lock to start vacuuming. We don't want the standby to
184+
# re-establish a connection to the primary and push the horizon back until
185+
# we've saved initial values in GlobalVisState and calculated OldestXmin.
186+
$node_primary->poll_query_until($test_db,
187+
qq[
188+
SELECT count(*) >= 1 FROM pg_stat_activity
189+
WHERE pid = $vacuum_pid
190+
AND wait_event = 'BufferPin';
191+
],
192+
't');
193+
194+
# Ensure the WAL receiver is still not active on the replica.
195+
$node_replica->poll_query_until($test_db, qq[
196+
SELECT EXISTS (SELECT * FROM pg_stat_wal_receiver);] , 'f');
197+
198+
# Allow the WAL receiver connection to re-establish.
199+
$node_replica->safe_psql(
200+
$test_db, qq[
201+
ALTER SYSTEM SET primary_conninfo = '$orig_conninfo';
202+
SELECT pg_reload_conf();
203+
]);
204+
205+
# Ensure the new WAL receiver has connected.
206+
$node_replica->poll_query_until($test_db, qq[
207+
SELECT EXISTS (SELECT * FROM pg_stat_wal_receiver);] , 't');
208+
209+
# Once the WAL sender is shown on the primary, the replica should have
210+
# connected with the primary and pushed the horizon backward. Primary Session
211+
# A won't see that until the VACUUM FREEZE proceeds and does its first round
212+
# of index vacuuming.
213+
$node_primary->poll_query_until($test_db, qq[
214+
SELECT EXISTS (SELECT * FROM pg_stat_replication);] , 't');
215+
216+
# Move the cursor forward to the next 7. We inserted the 7 much later, so
217+
# advancing the cursor should allow vacuum to proceed vacuuming most pages of
218+
# the relation. Because we set maintanence_work_mem sufficiently low, we
219+
# expect that a round of index vacuuming has happened and that the vacuum is
220+
# now waiting for the cursor to release its pin on the last page of the
221+
# relation.
222+
$res = $psql_primaryB->query_safe("FETCH $primary_cursor1");
223+
is($res, 7,
224+
qq[Cursor query returned $res from second fetch. Expected value 7.]);
225+
226+
# Prevent the test from incorrectly passing by confirming that we did indeed
227+
# do a pass of index vacuuming.
228+
$node_primary->poll_query_until($test_db, qq[
229+
SELECT index_vacuum_count > 0
230+
FROM pg_stat_progress_vacuum
231+
WHERE datname='$test_db' AND relid::regclass = '$table1'::regclass;
232+
] , 't');
233+
234+
# Commit the transaction with the open cursor so that the VACUUM can finish.
235+
$psql_primaryB->query_until(
236+
qr/^commit$/m,
237+
qq[
238+
COMMIT;
239+
\\echo commit
240+
]
241+
);
242+
243+
# VACUUM proceeds with pruning and does a visibility check on each tuple. In
244+
# older versions of Postgres, pruning found our final dead tuple
245+
# non-removable (HEAPTUPLE_RECENTLY_DEAD) since its xmax is after the new
246+
# value of maybe_needed. Then heap_prepare_freeze_tuple() would decide the
247+
# tuple xmax should be frozen because it precedes OldestXmin. Vacuum would
248+
# then error out in heap_pre_freeze_checks() with "cannot freeze committed
249+
# xmax". This was fixed by changing pruning to find all
250+
# HEAPTUPLE_RECENTLY_DEAD tuples with xmaxes preceding OldestXmin
251+
# HEAPTUPLE_DEAD and removing them.
252+
253+
# With the fix, VACUUM should finish successfully, incrementing the table
254+
# vacuum_count.
255+
$node_primary->poll_query_until($test_db,
256+
qq[
257+
SELECT vacuum_count > 0
258+
FROM pg_stat_all_tables WHERE relname = '${table1}';
259+
]
260+
, 't');
261+
262+
$primary_lsn = $node_primary->lsn('flush');
263+
264+
# Make sure something causes us to flush
265+
$node_primary->safe_psql($test_db, "INSERT INTO $table1 VALUES (1);");
266+
267+
# Nothing on the replica should cause a recovery conflict, so this should
268+
# finish successfully.
269+
$node_primary->wait_for_catchup($node_replica, 'replay', $primary_lsn);
270+
271+
## Shut down psqls
272+
$psql_primaryA->quit;
273+
$psql_primaryB->quit;
274+
275+
$node_replica->stop();
276+
$node_primary->stop();
277+
278+
done_testing();

0 commit comments

Comments
 (0)