pg.ddx.io pgsql-bugs@postgresql.org mailing list archive
help / color / mirror / Atom feedBUG #19519: REPACK can fail due to missing chunk for toast value
33+ messages / 14 participants
[nested] [flat]
Related threads (commitfest entry Fix: VACUUM FULL or CREATE INDEX fails with error "missing chunk number 0 for toast value XXX"/6824):
VACUUM FULL or CREATE INDEX fails with error: missing chunk number 0 for toast value XXX
* BUG #19519: REPACK can fail due to missing chunk for toast value
@ 2026-06-14 07:00 PG Bug reporting form <noreply@postgresql.org>
0 siblings, 1 reply; 33+ messages in thread
From: PG Bug reporting form @ 2026-06-14 07:00 UTC (permalink / raw)
To: pgsql-bugs@lists.postgresql.org; +Cc: exclusion@gmail.com
The following bug has been logged on the website:
Bug reference: 19519
Logged by: Alexander Lakhin
Email address: exclusion@gmail.com
PostgreSQL version: 19beta1
Operating system: Ubuntu 24.04
Description:
The following script:
createdb db1
createdb db2
cat << EOF | psql db1
SET default_statistics_target = 1000;
CREATE TABLE t(i int, t text);
INSERT INTO t SELECT 1, g::text FROM generate_series(1, 50000) g;
ANALYZE t;
EOF
cat << EOF | psql db2 &
BEGIN;
CREATE TABLE t(i int);
SELECT pg_sleep(3);
EOF
sleep 1
cat << EOF | psql db1
DROP TABLE t;
VACUUM pg_toast.pg_toast_2619;
REPACK;
EOF
wait
triggers:
ERROR: missing chunk number 0 for toast value 16393 in pg_toast_2619
Reproduced starting from ac58465e0.
^ permalink raw reply [nested|flat] 33+ messages in thread
* Re: BUG #19519: REPACK can fail due to missing chunk for toast value
@ 2026-06-17 17:03 Srinath Reddy Sadipiralla <srinath2133@gmail.com>
parent: PG Bug reporting form <noreply@postgresql.org>
0 siblings, 1 reply; 33+ messages in thread
From: Srinath Reddy Sadipiralla @ 2026-06-17 17:03 UTC (permalink / raw)
To: exclusion@gmail.com; pgsql-bugs@lists.postgresql.org
Hi Alexander,
On Sun, Jun 14, 2026 at 10:37 PM PG Bug reporting form <
noreply@postgresql.org> wrote:
> The following bug has been logged on the website:
>
> The following script:
> createdb db1
> createdb db2
>
> cat << EOF | psql db1
> SET default_statistics_target = 1000;
> CREATE TABLE t(i int, t text);
> INSERT INTO t SELECT 1, g::text FROM generate_series(1, 50000) g;
> ANALYZE t;
> EOF
>
> cat << EOF | psql db2 &
> BEGIN;
> CREATE TABLE t(i int);
> SELECT pg_sleep(3);
> EOF
>
> sleep 1
>
> cat << EOF | psql db1
> DROP TABLE t;
> VACUUM pg_toast.pg_toast_2619;
> REPACK;
> EOF
> wait
>
> triggers:
> ERROR: missing chunk number 0 for toast value 16393 in pg_toast_2619
>
Thanks for the report and clean reproducer , I can also reproduce this.
I looked into this. It is not REPACK-specific, it reproduces with
plain VACUUM FULL on back branches too, so it predates
the REPACK command. AFAIU The root cause is a disagreement about
the removal horizon between a table rewrite and an independent vacuum
of that table's TOAST relation.
A rewrite (cluster_rel -> copy_table_data, copy_heap_data) preserves live
and RECENTLY_DEAD tuples, and detoasts a preserved tuple's external
values to move them into the new TOAST table.Its removal cutoff comes
from GetOldestNonRemovableTransactionId(), i.e. ComputeXidHorizons(),
which includes the rewriting backend's own snapshot xmin.
The rewrite holds an ordinary MVCC snapshot (taken so index expressions
can be evaluated) and deliberately does not set PROC_IN_VACUUM. So
The rewrite backend's snapshot xmin is the cluster-wide oldest
running xid, which the db2 transaction pins. Since that backend is
in db1 and lacks PROC_IN_VACUUM, its own xmin folds into the
relation's data/catalog horizon -> OldestXmin sits behind the
DROP, so the dead pg_statistic tuple is RECENTLY_DEAD and gets
copied.
The lazy vacuum of pg_toast_2619 sets PROC_IN_VACUUM, which excludes
its own xmin from the horizon, and the db2 transaction, being in another
database,
does not constrain a non-shared relation's horizon. Its cutoff advances
past the DROP
and the chunks are removed.The two operations thus disagree about the same
tuple,
and the rewrite ends up fetching TOAST the lazy vacuum already reclaimed.
Attached Fix:
The rewrite is simply too conservative,AFAIK it's snapshot is only there to
evaluate index expressions against other relations, and it is not a
reader of the rewritten relation's historical rows, so its own xmin
should not hold back that relation's removal horizon. Excluding it
yields exactly the horizon the lazy vacuum uses.
We cannot set PROC_IN_VACUUM on the rewrite, that would broadcast
"ignore my xmin" to every backend and let other vacuums remove tuples in
other relations that the index expressions may need (the documented
reason VACUUM FULL does not set it). The exclusion has to be local to
the rewrite's own horizon computation, so the patch adds
GetOldestNonRemovableTransactionIdForRewrite(): ComputeXidHorizons()
gains a flag to skip the calling backend (and to not publish the
resulting, more-aggressive horizons into the shared GlobalVisState), and
copy_table_data() uses it for OldestXmin.
--
Thanks :)
Srinath Reddy Sadipiralla
EDB: https://www.enterprisedb.com/
Attachments:
v1-0001-Fix-missing-chunk-errors-during-heap-rewrites-by-ign.patch (application/octet-stream, 9.4K) download
From fde0d4c4745d350ebf4b50e361683de532f2c283 Mon Sep 17 00:00:00 2001
From: Srinath Reddy Sadipiralla <srinath2133@gmail.com>
Date: Wed, 17 Jun 2026 20:58:43 +0530
Subject: [PATCH 1/1] Fix "missing chunk" errors during heap rewrites by
ignoring own xmin.
When performing a heap rewrite (CLUSTER, VACUUM FULL, REPACK),
the backend must hold an MVCC snapshot to evaluate
index expressions against other relations. However, this backend does
not use this snapshot to read the historical rows of the relation
currently being rewritten.
Previously, vacuum_get_cutoffs() used GetOldestNonRemovableTransactionId(),
which folds the backend's own xmin into the relation's OldestXmin horizon.
If this xmin is held back by a transaction that cannot even see the target
relation (e.g., a transaction in another database), the rewrite's horizon
becomes artificially conservative.
This creates a race condition with lazy vacuum. Lazy vacuum sets the
PROC_IN_VACUUM flag, allowing it to exclude its own xmin from the global
horizon. Consequently, a concurrent or prior lazy vacuum could calculate
a newer horizon and safely remove a recently-dead tuple's TOAST chunks.
When the heap rewrite later scans the heap, its artificially older horizon
dictates that the recently-dead tuple must be preserved. It attempts to
copy the tuple, fails to find the TOAST chunks, and raises a "missing
chunk number 0 for toast value" error.
This patch fixes the issue by introducing
GetOldestNonRemovableTransactionIdForRewrite(). This function calls
ComputeXidHorizons() with a new `excludeMyself` boolean parameter. By
excluding MyProc from the calculation, the rewrite generates the exact
same horizon that a lazy vacuum would use.
Also, we skip calling GlobalVisUpdateApply() when excludeMyself is true.
This prevents the artificially aggressive local horizon from being cached
in the backend's local GlobalVisState. If this fake horizon were cached,
it would poison the backend's own pruning logic. When the rewrite later
accesses other relations to evaluate index expressions, this poisoned
cache would cause the backend to physically prune tuples that its own
snapshot still strictly requires.
---
src/backend/commands/repack.c | 15 ++++++
src/backend/storage/ipc/procarray.c | 80 ++++++++++++++++++++++++++---
src/include/storage/procarray.h | 1 +
3 files changed, 89 insertions(+), 7 deletions(-)
diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index ec100e3eef5..93ec67f8aaf 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -69,6 +69,7 @@
#include "storage/lmgr.h"
#include "storage/predicate.h"
#include "storage/proc.h"
+#include "storage/procarray.h"
#include "utils/acl.h"
#include "utils/fmgroids.h"
#include "utils/guc.h"
@@ -1380,6 +1381,20 @@ copy_table_data(Relation NewHeap, Relation OldHeap, Relation OldIndex,
memset(¶ms, 0, sizeof(VacuumParams));
vacuum_get_cutoffs(OldHeap, ¶ms, &cutoffs);
+ /*
+ * vacuum_get_cutoffs() folds our own backend's xmin into OldestXmin. For
+ * a rewrite that is too conservative: the snapshot we hold exists only to
+ * evaluate index expressions against other relations, not to read
+ * OldHeap's historical rows. If our xmin is held back by a transaction
+ * that cannot even see OldHeap (e.g. one in another database), we would
+ * preserve a recently-dead tuple whose TOAST chunks a concurrent or prior
+ * lazy vacuum was free to remove, and then fail with "missing chunk" while
+ * copying it. Recompute OldestXmin ignoring our own backend so it matches
+ * the horizon lazy vacuum uses. This can only move OldestXmin forward, so
+ * the freeze cutoffs derived above remain valid.
+ */
+ cutoffs.OldestXmin = GetOldestNonRemovableTransactionIdForRewrite(OldHeap);
+
/*
* FreezeXid will become the table's new relfrozenxid, and that mustn't go
* backwards, so take the max.
diff --git a/src/backend/storage/ipc/procarray.c b/src/backend/storage/ipc/procarray.c
index f540bb6b23f..e2f1ea08e84 100644
--- a/src/backend/storage/ipc/procarray.c
+++ b/src/backend/storage/ipc/procarray.c
@@ -1671,7 +1671,7 @@ TransactionIdIsInProgress(TransactionId xid)
* code doesn't expect (breaking HOT).
*/
static void
-ComputeXidHorizons(ComputeXidHorizonsResult *h)
+ComputeXidHorizons(ComputeXidHorizonsResult *h, bool excludeMyself)
{
ProcArrayStruct *arrayP = procArray;
TransactionId kaxmin;
@@ -1770,6 +1770,21 @@ ComputeXidHorizons(ComputeXidHorizonsResult *h)
if (statusFlags & (PROC_IN_VACUUM | PROC_IN_LOGICAL_DECODING))
continue;
+ /*
+ * Optionally ignore our own backend's xmin. A heap rewrite (CLUSTER /
+ * VACUUM FULL / REPACK) holds an MVCC snapshot only so that index
+ * expressions can be evaluated against other relations; it never
+ * reads the historical rows of the relation being rewritten through
+ * that snapshot. Letting our own xmin hold back that relation's
+ * removal horizon makes the rewrite more conservative than the lazy
+ * vacuum that may already have removed a recently-dead tuple's TOAST
+ * chunks, which would then fail with "missing chunk" while copying the
+ * tuple. This mirrors how PROC_IN_VACUUM excludes a lazy vacuum's own
+ * xmin. See GetOldestNonRemovableTransactionIdForRewrite().
+ */
+ if (excludeMyself && proc == MyProc)
+ continue;
+
/* shared tables need to take backends in all databases into account */
h->shared_oldest_nonremovable =
TransactionIdOlder(h->shared_oldest_nonremovable, xmin);
@@ -1898,8 +1913,15 @@ ComputeXidHorizons(ComputeXidHorizonsResult *h)
TransactionIdPrecedesOrEquals(h->oldest_considered_running,
h->slot_catalog_xmin));
- /* update approximate horizons with the computed horizons */
- GlobalVisUpdateApply(h);
+ /*
+ * Update approximate horizons with the computed horizons. Skip this when
+ * excluding our own xmin: the resulting horizons are more aggressive than
+ * is globally safe and are only valid for the caller's own rewrite of a
+ * single relation, so they must not be published to the shared
+ * GlobalVisState.
+ */
+ if (!excludeMyself)
+ GlobalVisUpdateApply(h);
}
/*
@@ -1945,7 +1967,51 @@ GetOldestNonRemovableTransactionId(Relation rel)
{
ComputeXidHorizonsResult horizons;
- ComputeXidHorizons(&horizons);
+ ComputeXidHorizons(&horizons, false);
+
+ switch (GlobalVisHorizonKindForRel(rel))
+ {
+ case VISHORIZON_SHARED:
+ return horizons.shared_oldest_nonremovable;
+ case VISHORIZON_CATALOG:
+ return horizons.catalog_oldest_nonremovable;
+ case VISHORIZON_DATA:
+ return horizons.data_oldest_nonremovable;
+ case VISHORIZON_TEMP:
+ return horizons.temp_oldest_nonremovable;
+ }
+
+ /* just to prevent compiler warnings */
+ return InvalidTransactionId;
+}
+
+/*
+ * GetOldestNonRemovableTransactionIdForRewrite -- variant of
+ * GetOldestNonRemovableTransactionId() that ignores the calling backend's
+ * own xmin.
+ *
+ * A heap rewrite (CLUSTER / VACUUM FULL / REPACK) must preserve recently-dead
+ * tuples of the relation being rewritten so that other backends' snapshots
+ * still see them afterwards. It is not, however, a reader of that relation's
+ * historical rows itself: the MVCC snapshot it holds exists only to evaluate
+ * index expressions against *other* relations. Including our own xmin in the
+ * horizon therefore makes the rewrite needlessly conservative, and -- when our
+ * xmin is held back by a transaction that cannot even see the relation (for
+ * example one in another database) -- more conservative than the lazy vacuum
+ * which already removed a recently-dead tuple's TOAST chunks, leading to
+ * "missing chunk" errors while copying the tuple. Excluding our own xmin
+ * yields the same horizon a lazy vacuum would use (PROC_IN_VACUUM does the
+ * equivalent for lazy vacuum).
+ *
+ * The caller must hold a lock on rel strong enough that the set of backends
+ * that could read its rows cannot change underneath us.
+ */
+TransactionId
+GetOldestNonRemovableTransactionIdForRewrite(Relation rel)
+{
+ ComputeXidHorizonsResult horizons;
+
+ ComputeXidHorizons(&horizons, true);
switch (GlobalVisHorizonKindForRel(rel))
{
@@ -1974,7 +2040,7 @@ GetOldestTransactionIdConsideredRunning(void)
{
ComputeXidHorizonsResult horizons;
- ComputeXidHorizons(&horizons);
+ ComputeXidHorizons(&horizons, false);
return horizons.oldest_considered_running;
}
@@ -1987,7 +2053,7 @@ GetReplicationHorizons(TransactionId *xmin, TransactionId *catalog_xmin)
{
ComputeXidHorizonsResult horizons;
- ComputeXidHorizons(&horizons);
+ ComputeXidHorizons(&horizons, false);
/*
* Don't want to use shared_oldest_nonremovable here, as that contains the
@@ -4206,7 +4272,7 @@ GlobalVisUpdate(void)
ComputeXidHorizonsResult horizons;
/* updates the horizons as a side-effect */
- ComputeXidHorizons(&horizons);
+ ComputeXidHorizons(&horizons, false);
}
/*
diff --git a/src/include/storage/procarray.h b/src/include/storage/procarray.h
index d718a5b542f..ccfc31cdb5d 100644
--- a/src/include/storage/procarray.h
+++ b/src/include/storage/procarray.h
@@ -51,6 +51,7 @@ extern RunningTransactions GetRunningTransactionData(void);
extern bool TransactionIdIsInProgress(TransactionId xid);
extern TransactionId GetOldestNonRemovableTransactionId(Relation rel);
+extern TransactionId GetOldestNonRemovableTransactionIdForRewrite(Relation rel);
extern TransactionId GetOldestTransactionIdConsideredRunning(void);
extern TransactionId GetOldestActiveTransactionId(bool inCommitOnly,
bool allDbs);
--
2.43.0
^ permalink raw reply [nested|flat] 33+ messages in thread
* Re: BUG #19519: REPACK can fail due to missing chunk for toast value
@ 2026-07-03 06:45 Imran Zaheer <imran.zhir@gmail.com>
parent: Srinath Reddy Sadipiralla <srinath2133@gmail.com>
0 siblings, 1 reply; 33+ messages in thread
From: Imran Zaheer @ 2026-07-03 06:45 UTC (permalink / raw)
To: Srinath Reddy Sadipiralla <srinath2133@gmail.com>; +Cc: exclusion@gmail.com; pgsql-bugs@lists.postgresql.org
Hi,
The proposed fix (skipping own xmin while computing oldest xmin) did
solve the problem, but while testing this, I found another bug report
showing the same error: "missing chunks."
For example, this report [1] reproduces the same bug with a different
repro attached, but interestingly, this thread discussion also pointed
out that the bug is also reproducible with the CREATE INDEX command.
The following trace was reported by Alexander Lakhin there.
> The backtrace of the heap_fetch_toast_slice() call emitting error is:
> 2024-03-05 17:41:07.786 UTC|law|db10|65e75933.208c6b|ERROR: missing chunk number 0 for toast value 17314 in pg_toast_17289
> 2024-03-05 17:41:07.786 UTC|law|db10|65e75933.208c6b|BACKTRACE:
> heap_fetch_toast_slice at heaptoast.c:784:3
> toast_fetch_datum at detoast.c:379:2
> detoast_external_attr at detoast.c:54:12
> index_form_tuple_context at indextuple.c:111:21
> tuplesort_putindextuplevalues at tuplesortvariants.c:678:15
> _bt_spool at nbtsort.c:537:1
> _bt_build_callback at nbtsort.c:610:24
> heapam_index_build_range_scan at heapam_handler.c:1329:22
> table_index_build_scan at tableam.h:1781:9
> (inlined by) _bt_spools_heapscan at nbtsort.c:483:15
> btbuild at nbtsort.c:329:14
> index_build at index.c:3042:10
> index_create at index.c:1265:3
> DefineIndex at indexcmds.c:1166:3
Index building, together with lazy vacuum, can create similar
conditions as we saw with VACUUM FULL / CLUSTER / REPACK. In
heapam_index_build_range_scan(), we compute the OldestXmin, which
later is used to decide which tuples to index (in repack we use it to
decide which tuples to copy). I think we should also consider fixing
the index building path while addressing this bug.
```
OldestXmin = GetOldestNonRemovableTransactionId(heapRelation);
```
Can we safely use the same fix in the index build path too? Can we use
GetOldestNonRemovableTransactionIdforRewrite or something similar
here? Normal serial index builds use SnapShotAny and concurrent index
builds use MVCC, but the bug only exists in the serial index build
path.
Other than that, after applying your patch, the bug was not
reproducible with either this repro or the other report's repro [1] in
the rewrite path. However, the create index bug is still there. You
can use the following repro as mentioned in the thread [1].
> I've discovered that not only VACUUM FULL can stumble over such missing
> toast values. CREATE INDEX behaves similarly, as the following script
> shows:
> for ((c=1;c<=20;c++)); do createdb db$c; done
>
>
> for ((i=1;i<=100;i++)); do
> echo "iteration $i"
> for ((c=1;c<=20;c++)); do
> echo "\\d sometable" | psql -d db$c >psql-1-$c.log 2>&1 &
> echo "DROP TABLE IF EXISTS tbl;
> CREATE TABLE tbl (i int, t text);
> ALTER TABLE tbl ALTER COLUMN t SET STORAGE EXTERNAL;
> INSERT INTO tbl(i, t) VALUES (1, repeat('1234567890', 250));
> DELETE FROM tbl;
>
>
> VACUUM (VERBOSE) tbl;
> CREATE INDEX t_idx ON tbl(t);
> " | psql -d db$c >psql-2-$c.log 2>&1 &
> done
> wait
> grep 'missing chunk number' server.log && break;
> done
Regards,
Imran Zaheer
[1]: https://www.postgresql.org/message-id/flat/18351-f6e06364b3a2e669%40postgresql.org
On Wed, Jun 17, 2026 at 10:03 PM Srinath Reddy Sadipiralla
<srinath2133@gmail.com> wrote:
>
> Hi Alexander,
>
> On Sun, Jun 14, 2026 at 10:37 PM PG Bug reporting form <noreply@postgresql.org> wrote:
>>
>> The following bug has been logged on the website:
>>
>> The following script:
>> createdb db1
>> createdb db2
>>
>> cat << EOF | psql db1
>> SET default_statistics_target = 1000;
>> CREATE TABLE t(i int, t text);
>> INSERT INTO t SELECT 1, g::text FROM generate_series(1, 50000) g;
>> ANALYZE t;
>> EOF
>>
>> cat << EOF | psql db2 &
>> BEGIN;
>> CREATE TABLE t(i int);
>> SELECT pg_sleep(3);
>> EOF
>>
>> sleep 1
>>
>> cat << EOF | psql db1
>> DROP TABLE t;
>> VACUUM pg_toast.pg_toast_2619;
>> REPACK;
>> EOF
>> wait
>>
>> triggers:
>> ERROR: missing chunk number 0 for toast value 16393 in pg_toast_2619
>
>
> Thanks for the report and clean reproducer , I can also reproduce this.
>
> I looked into this. It is not REPACK-specific, it reproduces with
> plain VACUUM FULL on back branches too, so it predates
> the REPACK command. AFAIU The root cause is a disagreement about
> the removal horizon between a table rewrite and an independent vacuum
> of that table's TOAST relation.
>
> A rewrite (cluster_rel -> copy_table_data, copy_heap_data) preserves live
> and RECENTLY_DEAD tuples, and detoasts a preserved tuple's external
> values to move them into the new TOAST table.Its removal cutoff comes
> from GetOldestNonRemovableTransactionId(), i.e. ComputeXidHorizons(),
> which includes the rewriting backend's own snapshot xmin.
> The rewrite holds an ordinary MVCC snapshot (taken so index expressions
> can be evaluated) and deliberately does not set PROC_IN_VACUUM. So
> The rewrite backend's snapshot xmin is the cluster-wide oldest
> running xid, which the db2 transaction pins. Since that backend is
> in db1 and lacks PROC_IN_VACUUM, its own xmin folds into the
> relation's data/catalog horizon -> OldestXmin sits behind the
> DROP, so the dead pg_statistic tuple is RECENTLY_DEAD and gets
> copied.
> The lazy vacuum of pg_toast_2619 sets PROC_IN_VACUUM, which excludes
> its own xmin from the horizon, and the db2 transaction, being in another database,
> does not constrain a non-shared relation's horizon. Its cutoff advances past the DROP
> and the chunks are removed.The two operations thus disagree about the same tuple,
> and the rewrite ends up fetching TOAST the lazy vacuum already reclaimed.
>
> Attached Fix:
> The rewrite is simply too conservative,AFAIK it's snapshot is only there to
> evaluate index expressions against other relations, and it is not a
> reader of the rewritten relation's historical rows, so its own xmin
> should not hold back that relation's removal horizon. Excluding it
> yields exactly the horizon the lazy vacuum uses.
> We cannot set PROC_IN_VACUUM on the rewrite, that would broadcast
> "ignore my xmin" to every backend and let other vacuums remove tuples in
> other relations that the index expressions may need (the documented
> reason VACUUM FULL does not set it). The exclusion has to be local to
> the rewrite's own horizon computation, so the patch adds
> GetOldestNonRemovableTransactionIdForRewrite(): ComputeXidHorizons()
> gains a flag to skip the calling backend (and to not publish the
> resulting, more-aggressive horizons into the shared GlobalVisState), and
> copy_table_data() uses it for OldestXmin.
>
> --
> Thanks :)
> Srinath Reddy Sadipiralla
> EDB: https://www.enterprisedb.com/
^ permalink raw reply [nested|flat] 33+ messages in thread
* Re: BUG #19519: REPACK can fail due to missing chunk for toast value
@ 2026-07-06 06:36 Michael Paquier <michael@paquier.xyz>
parent: Imran Zaheer <imran.zhir@gmail.com>
0 siblings, 3 replies; 33+ messages in thread
From: Michael Paquier @ 2026-07-06 06:36 UTC (permalink / raw)
To: Imran Zaheer <imran.zhir@gmail.com>; +Cc: Srinath Reddy Sadipiralla <srinath2133@gmail.com>; exclusion@gmail.com; pgsql-bugs@lists.postgresql.org
On Fri, Jul 03, 2026 at 11:45:42AM +0500, Imran Zaheer wrote:
> Can we safely use the same fix in the index build path too? Can we use
> GetOldestNonRemovableTransactionIdforRewrite or something similar
> here? Normal serial index builds use SnapShotAny and concurrent index
> builds use MVCC, but the bug only exists in the serial index build
> path.
Yeah, I think that we should be able to safely reuse your ForRewrite()
API for the index build case (SnapshotAny part) as well to make the
horizon computations more conservative, exclusing one own XID as we
do in the lazy VACUUM case.
> Other than that, after applying your patch, the bug was not
> reproducible with either this repro or the other report's repro [1] in
> the rewrite path. However, the create index bug is still there. You
> can use the following repro as mentioned in the thread [1].
The assymetry between the global xmin computation and the per-database
horizon is what's killing us here. All these patterns are complicated
enough that they warrant some tests, even if it is necessary to have
multiple databases to trigger the buggy horizon computations. TAP
tests would be an obvious choice for that. Now I have a set of tricks
in my sleeves to make an isolation test fully deterministic:
- dblink() that opens a transaction to a different database than the
one of the isolation regression database.
- Rename of a TOAST table using allow_system_table_mods, for a VACUUM.
The second one is one of the dirtiest tricks I've done in the past for
a REINDEX CONCURRENTLY test with TOAST. Quite useful. If the backend
side change is reverted, the tests fail.
The attached includes both test suites for all four cases reported
(REPACK, VACUUM, CLUSTER, non-MVCC index builds). We'll need to
remove one of them, just keeping both posted as I am not sure if the
isolation tests would be entirely stable in the buildfarm..
I still need to dive more into the code, but for now this bit stands
out:
vacuum_get_cutoffs(OldHeap, ¶ms, &cutoffs);
+ /*
+ * vacuum_get_cutoffs() folds our own backend's xmin into OldestXmin. For
+ * a rewrite that is too conservative: the snapshot we hold exists only to
+ * evaluate index expressions against other relations, not to read
+ * OldHeap's historical rows. If our xmin is held back by a transaction
+ * that cannot even see OldHeap (e.g. one in another database), we would
+ * preserve a recently-dead tuple whose TOAST chunks a concurrent or prior
+ * lazy vacuum was free to remove, and then fail with "missing chunk" while
+ * copying it. Recompute OldestXmin ignoring our own backend so it matches
+ * the horizon lazy vacuum uses. This can only move OldestXmin forward, so
+ * the freeze cutoffs derived above remain valid.
+ */
+ cutoffs.OldestXmin = GetOldestNonRemovableTransactionIdForRewrite(OldHeap);
In copy_table_data() (for the data copy with repack, cluster, vacuum
full), I think that this is incorrect. For one, this breaks the
FreezeLimit which should always be older than OldestXmin, and this
patch enforces a new recomputation of OldestXmin ignoring most of the
internals of vacuum_get_cutoffs(). That's brittle, to say the least
if we change the way the vacuum cutoffs are calculated in the future.
Thoughts and comments from others are welcome for now. My day is
almost out, at least I got all these scenarios working some tests.
--
Michael
Attachments:
v2-0001-Fix-missing-chunk-errors-during-heap-rewrites-and.patch (text/plain, 24.1K) download
From 36fdec282e5c48866bf915f767502ccc3c6bc0b2 Mon Sep 17 00:00:00 2001
From: Michael Paquier <michael@paquier.xyz>
Date: Mon, 6 Jul 2026 15:27:54 +0900
Subject: [PATCH v2] Fix "missing chunk" errors during heap rewrites and index
builds
When performing a heap rewrite (CLUSTER, VACUUM FULL, REPACK) or a
non-concurrent index build, the backend holds an MVCC snapshot whose
xmin can be held back by a transaction in another database, since
GetSnapshotData() considers XIDs from all databases.
However, ComputeXidHorizons() only considers same-database backends for
data_oldest_nonremovable. This asymmetry means a concurrent VACUUM
can compute a more aggressive horizon and remove TOAST chunks for a
tuple that the rewrite/index-build backend still considers as recently
dead, leading to "missing chunk number 0 for toast value" errors when
attempting to copy or index a tuple.
This issue is fixed by introducing a ForRewrite() equivalent of
GetOldestNonRemovableTransactionId(). It calls ComputeXidHorizons()
with a new option called "excludeMyself", mirroring how PROC_IN_VACUUM
excludes a lazy VACUUM own's XID to make rewrites more conservative with
the computation of the XID horizon.
This problem has been reported recently by Alexander for REPACK, but it
is a much older issue (tested down to 9.5 for curiosity's sake, but I
suspect that it is much older than that).
Srinath has authored the C portion of the patch, while I got some tests
working for the four problematic cases reported.
XXX: This patch includes both TAP and isolation tests. We should remove
one pattern at the end.
Reported-by: Alexander Lakhin <exclusion@gmail.com>
Author: Srinath Reddy Sadipiralla <srinath2133@gmail.com>
Co-authored-by: Michael Paquier <michael@paquier.xyz>
Reviewed-by: Imran Zaheer <imran.zhir@gmail.com>
Discussion: https://postgr.es/m/18351-f6e06364b3a2e669@postgresql.org
Discussion: https://postgr.es/m/19519-fe02d8ff679d834d@postgresql.org
Backpatch-through: 14
---
src/include/storage/procarray.h | 1 +
src/backend/access/heap/heapam_handler.c | 2 +-
src/backend/commands/repack.c | 15 ++
src/backend/storage/ipc/procarray.c | 78 +++++-
src/test/recovery/meson.build | 1 +
src/test/recovery/t/055_rewrite_stale_xmin.pl | 124 +++++++++
contrib/dblink/.gitignore | 2 +
contrib/dblink/Makefile | 2 +
.../dblink/expected/rewrite_stale_xmin.out | 237 ++++++++++++++++++
contrib/dblink/meson.build | 5 +
contrib/dblink/specs/rewrite_stale_xmin.spec | 137 ++++++++++
11 files changed, 596 insertions(+), 8 deletions(-)
create mode 100644 src/test/recovery/t/055_rewrite_stale_xmin.pl
create mode 100644 contrib/dblink/expected/rewrite_stale_xmin.out
create mode 100644 contrib/dblink/specs/rewrite_stale_xmin.spec
diff --git a/src/include/storage/procarray.h b/src/include/storage/procarray.h
index d718a5b542f0..ccfc31cdb5d1 100644
--- a/src/include/storage/procarray.h
+++ b/src/include/storage/procarray.h
@@ -51,6 +51,7 @@ extern RunningTransactions GetRunningTransactionData(void);
extern bool TransactionIdIsInProgress(TransactionId xid);
extern TransactionId GetOldestNonRemovableTransactionId(Relation rel);
+extern TransactionId GetOldestNonRemovableTransactionIdForRewrite(Relation rel);
extern TransactionId GetOldestTransactionIdConsideredRunning(void);
extern TransactionId GetOldestActiveTransactionId(bool inCommitOnly,
bool allDbs);
diff --git a/src/backend/access/heap/heapam_handler.c b/src/backend/access/heap/heapam_handler.c
index 2268cc277bce..fb1540784236 100644
--- a/src/backend/access/heap/heapam_handler.c
+++ b/src/backend/access/heap/heapam_handler.c
@@ -1213,7 +1213,7 @@ heapam_index_build_range_scan(Relation heapRelation,
/* okay to ignore lazy VACUUMs here */
if (!IsBootstrapProcessingMode() && !indexInfo->ii_Concurrent)
- OldestXmin = GetOldestNonRemovableTransactionId(heapRelation);
+ OldestXmin = GetOldestNonRemovableTransactionIdForRewrite(heapRelation);
if (!scan)
{
diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index faa07d1a118b..1585d67f0b34 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -71,6 +71,7 @@
#include "storage/lmgr.h"
#include "storage/predicate.h"
#include "storage/proc.h"
+#include "storage/procarray.h"
#include "utils/acl.h"
#include "utils/fmgroids.h"
#include "utils/guc.h"
@@ -1390,6 +1391,20 @@ copy_table_data(Relation NewHeap, Relation OldHeap, Relation OldIndex,
memset(¶ms, 0, sizeof(VacuumParams));
vacuum_get_cutoffs(OldHeap, ¶ms, &cutoffs);
+ /*
+ * vacuum_get_cutoffs() folds our own backend's xmin into OldestXmin. For
+ * a rewrite that is too conservative: the snapshot we hold exists only to
+ * evaluate index expressions against other relations, not to read
+ * OldHeap's historical rows. If our xmin is held back by a transaction
+ * that cannot even see OldHeap (e.g. one in another database), we would
+ * preserve a recently-dead tuple whose TOAST chunks a concurrent or prior
+ * lazy vacuum was free to remove, and then fail with "missing chunk"
+ * while copying it. Recompute OldestXmin ignoring our own backend so it
+ * matches the horizon lazy vacuum uses. This can only move OldestXmin
+ * forward, so the freeze cutoffs derived above remain valid.
+ */
+ cutoffs.OldestXmin = GetOldestNonRemovableTransactionIdForRewrite(OldHeap);
+
/*
* FreezeXid will become the table's new relfrozenxid, and that mustn't go
* backwards, so take the max.
diff --git a/src/backend/storage/ipc/procarray.c b/src/backend/storage/ipc/procarray.c
index 60336b318036..a11c01eb9d42 100644
--- a/src/backend/storage/ipc/procarray.c
+++ b/src/backend/storage/ipc/procarray.c
@@ -1671,7 +1671,7 @@ TransactionIdIsInProgress(TransactionId xid)
* code doesn't expect (breaking HOT).
*/
static void
-ComputeXidHorizons(ComputeXidHorizonsResult *h)
+ComputeXidHorizons(ComputeXidHorizonsResult *h, bool excludeMyself)
{
ProcArrayStruct *arrayP = procArray;
TransactionId kaxmin;
@@ -1770,6 +1770,22 @@ ComputeXidHorizons(ComputeXidHorizonsResult *h)
if (statusFlags & (PROC_IN_VACUUM | PROC_IN_LOGICAL_DECODING))
continue;
+ /*
+ * Optionally ignore our own backend's xmin. A relation rewrite holds
+ * an MVCC snapshot only so that index expressions can be evaluated
+ * against other relations; it never reads the historical rows of the
+ * relation being rewritten through that snapshot. Letting our own
+ * xmin hold back that relation's removal horizon makes the rewrite
+ * more conservative than the lazy vacuum that may already have
+ * removed a recently-dead tuple's TOAST chunks, which would then fail
+ * with "missing chunk" while copying the tuple. This mirrors how
+ * PROC_IN_VACUUM excludes a lazy vacuum's own xmin.
+ *
+ * See also GetOldestNonRemovableTransactionIdForRewrite().
+ */
+ if (excludeMyself && proc == MyProc)
+ continue;
+
/* shared tables need to take backends in all databases into account */
h->shared_oldest_nonremovable =
TransactionIdOlder(h->shared_oldest_nonremovable, xmin);
@@ -1898,8 +1914,15 @@ ComputeXidHorizons(ComputeXidHorizonsResult *h)
TransactionIdPrecedesOrEquals(h->oldest_considered_running,
h->slot_catalog_xmin));
- /* update approximate horizons with the computed horizons */
- GlobalVisUpdateApply(h);
+ /*
+ * Update approximate horizons with the computed horizons. Skip this when
+ * excluding our own xmin: the resulting horizons are more aggressive than
+ * what is globally safe and are only valid for the caller's own rewrite
+ * of a single relation, so they must not be published to the shared
+ * GlobalVisState.
+ */
+ if (!excludeMyself)
+ GlobalVisUpdateApply(h);
}
/*
@@ -1945,7 +1968,48 @@ GetOldestNonRemovableTransactionId(Relation rel)
{
ComputeXidHorizonsResult horizons;
- ComputeXidHorizons(&horizons);
+ ComputeXidHorizons(&horizons, false);
+
+ switch (GlobalVisHorizonKindForRel(rel))
+ {
+ case VISHORIZON_SHARED:
+ return horizons.shared_oldest_nonremovable;
+ case VISHORIZON_CATALOG:
+ return horizons.catalog_oldest_nonremovable;
+ case VISHORIZON_DATA:
+ return horizons.data_oldest_nonremovable;
+ case VISHORIZON_TEMP:
+ return horizons.temp_oldest_nonremovable;
+ }
+
+ /* just to prevent compiler warnings */
+ return InvalidTransactionId;
+}
+
+/*
+ * GetOldestNonRemovableTransactionIdForRewrite -- variant of
+ * GetOldestNonRemovableTransactionId() that ignores the calling backend's
+ * own xmin.
+ *
+ * A rewrite must preserve recently-dead tuples of the relation being
+ * rewritten so that other backends' snapshots still see them afterwards.
+ *
+ * It is not, however, a reader of that relation's
+ * historical rows itself: the MVCC snapshot it holds exists only to evaluate
+ * index expressions against *other* relations. Excluding our own xmin yields
+ * the same horizon a lazy vacuum would use (PROC_IN_VACUUM does the equivalent
+ * for lazy vacuum). That matters for TOAST relations to prevent the removal of
+ * recently-dead tuple's TOAST chunks.
+ *
+ * The caller must hold a lock on rel strong enough that the set of backends
+ * that could read its rows cannot change underneath us.
+ */
+TransactionId
+GetOldestNonRemovableTransactionIdForRewrite(Relation rel)
+{
+ ComputeXidHorizonsResult horizons;
+
+ ComputeXidHorizons(&horizons, true);
switch (GlobalVisHorizonKindForRel(rel))
{
@@ -1974,7 +2038,7 @@ GetOldestTransactionIdConsideredRunning(void)
{
ComputeXidHorizonsResult horizons;
- ComputeXidHorizons(&horizons);
+ ComputeXidHorizons(&horizons, false);
return horizons.oldest_considered_running;
}
@@ -1987,7 +2051,7 @@ GetReplicationHorizons(TransactionId *xmin, TransactionId *catalog_xmin)
{
ComputeXidHorizonsResult horizons;
- ComputeXidHorizons(&horizons);
+ ComputeXidHorizons(&horizons, false);
/*
* Don't want to use shared_oldest_nonremovable here, as that contains the
@@ -4214,7 +4278,7 @@ GlobalVisUpdate(void)
ComputeXidHorizonsResult horizons;
/* updates the horizons as a side-effect */
- ComputeXidHorizons(&horizons);
+ ComputeXidHorizons(&horizons, false);
}
/*
diff --git a/src/test/recovery/meson.build b/src/test/recovery/meson.build
index ad0d85f41897..7e583ee39a10 100644
--- a/src/test/recovery/meson.build
+++ b/src/test/recovery/meson.build
@@ -63,6 +63,7 @@ tests += {
't/052_checkpoint_segment_missing.pl',
't/053_standby_login_event_trigger.pl',
't/054_unlogged_sequence_promotion.pl',
+ 't/055_rewrite_stale_xmin.pl',
],
},
}
diff --git a/src/test/recovery/t/055_rewrite_stale_xmin.pl b/src/test/recovery/t/055_rewrite_stale_xmin.pl
new file mode 100644
index 000000000000..dad95c0cf967
--- /dev/null
+++ b/src/test/recovery/t/055_rewrite_stale_xmin.pl
@@ -0,0 +1,124 @@
+# Copyright (c) 2025-2026, PostgreSQL Global Development Group
+#
+# Test that heap rewrites (CLUSTER, VACUUM FULL, REPACK) and index builds
+# work in the case when the backend's own xmin is held back by a transaction
+# in another database.
+
+use strict;
+use warnings;
+use PostgreSQL::Test::Cluster;
+use Test::More;
+
+my $node = PostgreSQL::Test::Cluster->new('primary');
+$node->init;
+# No Autovacuum, no random interferences.
+$node->append_conf(
+ 'postgresql.conf', qq[
+autovacuum = off
+]);
+$node->start;
+
+# Create two databases.
+$node->safe_psql('postgres', 'CREATE DATABASE db_holder');
+$node->safe_psql('postgres', 'CREATE DATABASE db_target');
+
+# Set up a table with TOAST data. Returns the toast table name.
+sub setup_table
+{
+ my ($tblname, $extra_ddl) = @_;
+ $extra_ddl //= '';
+
+ $node->safe_psql(
+ 'db_target', qq{
+ DROP TABLE IF EXISTS $tblname;
+ CREATE TABLE $tblname (id int PRIMARY KEY, data text)
+ WITH (autovacuum_enabled = off);
+ ALTER TABLE $tblname ALTER COLUMN data SET STORAGE EXTERNAL;
+ INSERT INTO $tblname VALUES (1, repeat('x', 2500));
+ INSERT INTO $tblname VALUES (2, repeat('z', 2500));
+ $extra_ddl
+ });
+
+ my $toast = $node->safe_psql(
+ 'db_target', qq{
+ SELECT 'pg_toast.' || relname FROM pg_class
+ WHERE oid = (SELECT reltoastrelid FROM pg_class
+ WHERE relname = '$tblname');
+ });
+ chomp $toast;
+ return $toast;
+}
+
+# Create precondition state. Requires that $holder is already running with
+# a write XID.
+sub create_missing_toast_state
+{
+ my ($tblname, $toast_table) = @_;
+
+ # Hold xmin in same DB to prevent main tuple removal.
+ my $xmin_holder = $node->background_psql('db_target', on_error_stop => 1);
+ $xmin_holder->query_safe("BEGIN ISOLATION LEVEL REPEATABLE READ");
+ $xmin_holder->query_safe("SELECT 1");
+
+ # Delete the row with TOAST data.
+ $node->safe_psql('db_target', "DELETE FROM $tblname WHERE id = 1");
+
+ # VACUUM main table only. The xmin_holder keeps the dead tuple.
+ $node->safe_psql('db_target', "VACUUM (PROCESS_TOAST false) $tblname");
+
+ # Release same-DB xmin.
+ $xmin_holder->query_safe("COMMIT");
+ $xmin_holder->quit;
+
+ # Vacuum toast table: toast chunks now DEAD and removed.
+ $node->safe_psql('db_target', "VACUUM $toast_table");
+}
+
+# Open a transaction holding an XID before any deletes. This XID will hold
+# back GetSnapshotData() globally, on a different database than the one
+# running the various rewrite operations.
+my $holder = $node->background_psql('db_holder', on_error_stop => 1);
+$holder->query_safe("BEGIN");
+$holder->query_safe("CREATE TEMP TABLE xid_holder(x int)");
+
+# Test 1: CLUSTER
+my $toast = setup_table('rewrite_test');
+create_missing_toast_state('rewrite_test', $toast);
+
+my ($ret, $stdout, $stderr) =
+ $node->psql('db_target', 'CLUSTER rewrite_test USING rewrite_test_pkey');
+is($ret, 0, "CLUSTER succeeds without missing-chunk error");
+unlike($stderr, qr/missing chunk/, "CLUSTER: no missing-chunk error");
+
+# Test 2: VACUUM FULL
+$toast = setup_table('rewrite_test');
+create_missing_toast_state('rewrite_test', $toast);
+
+($ret, $stdout, $stderr) =
+ $node->psql('db_target', 'VACUUM FULL rewrite_test');
+is($ret, 0, "VACUUM FULL succeeds without missing-chunk error");
+unlike($stderr, qr/missing chunk/, "VACUUM FULL: no missing-chunk error");
+
+# Test 3: REPACK
+$toast = setup_table('rewrite_test');
+create_missing_toast_state('rewrite_test', $toast);
+
+($ret, $stdout, $stderr) = $node->psql('db_target', 'REPACK rewrite_test');
+is($ret, 0, "REPACK succeeds without missing-chunk error");
+unlike($stderr, qr/missing chunk/, "REPACK: no missing-chunk error");
+
+# Test 4: CREATE INDEX on toasted column
+$toast = setup_table('rewrite_test');
+create_missing_toast_state('rewrite_test', $toast);
+
+($ret, $stdout, $stderr) = $node->psql('db_target',
+ 'CREATE INDEX rewrite_test_data_idx ON rewrite_test (data)');
+is($ret, 0, "CREATE INDEX succeeds without missing-chunk error");
+unlike($stderr, qr/missing chunk/, "CREATE INDEX: no missing-chunk error");
+
+# Cleanup.
+$holder->query_safe("COMMIT");
+$holder->quit;
+
+$node->stop;
+done_testing();
diff --git a/contrib/dblink/.gitignore b/contrib/dblink/.gitignore
index 5dcb3ff97235..33bc8d8ffeb3 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 fde0b49ddbbd..a0ba41280813 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 000000000000..2e5a7940ea26
--- /dev/null
+++ b/contrib/dblink/expected/rewrite_stale_xmin.out
@@ -0,0 +1,237 @@
+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_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)
+
diff --git a/contrib/dblink/meson.build b/contrib/dblink/meson.build
index e2489f41229f..86fbd372b880 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 000000000000..fe88e789f854
--- /dev/null
+++ b/contrib/dblink/specs/rewrite_stale_xmin.spec
@@ -0,0 +1,137 @@
+# Test that heap rewrites work when the rewriting backend's own xmin is
+# held back by a transaction in another database.
+
+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_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;
+}
+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);
+}
+
+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
+
+# 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
--
2.55.0
signature.asc (application/pgp-signature, 832B) download
^ permalink raw reply [nested|flat] 33+ messages in thread
* Re: BUG #19519: REPACK can fail due to missing chunk for toast value
@ 2026-07-06 13:38 Konstantin Knizhnik <knizhnik@garret.ru>
parent: Michael Paquier <michael@paquier.xyz>
2 siblings, 0 replies; 33+ messages in thread
From: Konstantin Knizhnik @ 2026-07-06 13:38 UTC (permalink / raw)
To: Michael Paquier <michael@paquier.xyz>; Imran Zaheer <imran.zhir@gmail.com>; +Cc: Srinath Reddy Sadipiralla <srinath2133@gmail.com>; exclusion@gmail.com; pgsql-bugs@lists.postgresql.org
On 06/07/2026 9:36 AM, Michael Paquier wrote:
> On Fri, Jul 03, 2026 at 11:45:42AM +0500, Imran Zaheer wrote:
>> Can we safely use the same fix in the index build path too? Can we use
>> GetOldestNonRemovableTransactionIdforRewrite or something similar
>> here? Normal serial index builds use SnapShotAny and concurrent index
>> builds use MVCC, but the bug only exists in the serial index build
>> path.
> Yeah, I think that we should be able to safely reuse your ForRewrite()
> API for the index build case (SnapshotAny part) as well to make the
> horizon computations more conservative, exclusing one own XID as we
> do in the lazy VACUUM case.
>
>> Other than that, after applying your patch, the bug was not
>> reproducible with either this repro or the other report's repro [1] in
>> the rewrite path. However, the create index bug is still there. You
>> can use the following repro as mentioned in the thread [1].
> The assymetry between the global xmin computation and the per-database
> horizon is what's killing us here. All these patterns are complicated
> enough that they warrant some tests, even if it is necessary to have
> multiple databases to trigger the buggy horizon computations. TAP
> tests would be an obvious choice for that. Now I have a set of tricks
> in my sleeves to make an isolation test fully deterministic:
> - dblink() that opens a transaction to a different database than the
> one of the isolation regression database.
> - Rename of a TOAST table using allow_system_table_mods, for a VACUUM.
>
> The second one is one of the dirtiest tricks I've done in the past for
> a REINDEX CONCURRENTLY test with TOAST. Quite useful. If the backend
> side change is reverted, the tests fail.
>
> The attached includes both test suites for all four cases reported
> (REPACK, VACUUM, CLUSTER, non-MVCC index builds). We'll need to
> remove one of them, just keeping both posted as I am not sure if the
> isolation tests would be entirely stable in the buildfarm..
>
> I still need to dive more into the code, but for now this bit stands
> out:
> vacuum_get_cutoffs(OldHeap, ¶ms, &cutoffs);
>
> + /*
> + * vacuum_get_cutoffs() folds our own backend's xmin into OldestXmin. For
> + * a rewrite that is too conservative: the snapshot we hold exists only to
> + * evaluate index expressions against other relations, not to read
> + * OldHeap's historical rows. If our xmin is held back by a transaction
> + * that cannot even see OldHeap (e.g. one in another database), we would
> + * preserve a recently-dead tuple whose TOAST chunks a concurrent or prior
> + * lazy vacuum was free to remove, and then fail with "missing chunk" while
> + * copying it. Recompute OldestXmin ignoring our own backend so it matches
> + * the horizon lazy vacuum uses. This can only move OldestXmin forward, so
> + * the freeze cutoffs derived above remain valid.
> + */
> + cutoffs.OldestXmin = GetOldestNonRemovableTransactionIdForRewrite(OldHeap);
>
> In copy_table_data() (for the data copy with repack, cluster, vacuum
> full), I think that this is incorrect. For one, this breaks the
> FreezeLimit which should always be older than OldestXmin, and this
> patch enforces a new recomputation of OldestXmin ignoring most of the
> internals of vacuum_get_cutoffs(). That's brittle, to say the least
> if we change the way the vacuum cutoffs are calculated in the future.
>
> Thoughts and comments from others are welcome for now. My day is
> almost out, at least I got all these scenarios working some tests.
> --
> Michael
I wonder if we also need to replace GetOldestNonRemovableTransactionId
with GetOldestNonRemovableTransactionIdForRewrite in vacuum.c:
inline patch 1: src/backend/commands/vacuum.c (+0/-0 lines) download inline-1.patch
diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c
index be863db81cb..aaa7e6eeeaa 100644
--- a/src/backend/commands/vacuum.c
+++ b/src/backend/commands/vacuum.c
@@ -1149,7 +1149,7 @@ vacuum_get_cutoffs(Relation rel, const
VacuumParams *params,
* that only one vacuum process can be working on a particular
table at
* any time, and that each vacuum is always an independent
transaction.
*/
- cutoffs->OldestXmin = GetOldestNonRemovableTransactionId(rel);
+ cutoffs->OldestXmin =
GetOldestNonRemovableTransactionIdForRewrite(rel);
Assert(TransactionIdIsNormal(cutoffs->OldestXmin));
For some reasons the problem is not reproduced with current master, but
when I applied your patch to PG18 and run repro script with REPACK
replaced with VACUUM FULL, then I still get missing chunk error.
^ permalink raw reply [nested|flat] 33+ messages in thread
* Re: BUG #19519: REPACK can fail due to missing chunk for toast value
@ 2026-07-06 18:00 Alexander Lakhin <exclusion@gmail.com>
parent: Michael Paquier <michael@paquier.xyz>
2 siblings, 0 replies; 33+ messages in thread
From: Alexander Lakhin @ 2026-07-06 18:00 UTC (permalink / raw)
To: Michael Paquier <michael@paquier.xyz>; +Cc: Imran Zaheer <imran.zhir@gmail.com>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; pgsql-bugs@lists.postgresql.org
Hello Michael,
06.07.2026 09:36, Michael Paquier wrote:
> Thoughts and comments from others are welcome for now. My day is
> almost out, at least I got all these scenarios working some tests.
Unfortunately, I still can produce that error running my repro script,
with higher concurrency:
for ((c=1;c<=50;c++)); do createdb db$c; done
for ((i=1;i<=100;i++)); do
echo "iteration $i"
for ((c=1;c<=50;c++)); do
echo "\\d sometable" | psql -d db$c >psql-1-$c.log 2>&1 &
echo "DROP TABLE IF EXISTS tbl;
CREATE TABLE tbl (i int, t text);
ALTER TABLE tbl ALTER COLUMN t SET STORAGE EXTERNAL;
INSERT INTO tbl(i, t) VALUES (1, repeat('1234567890', 250));
DELETE FROM tbl;
VACUUM (TRUNCATE, VERBOSE) tbl;
VACUUM FULL tbl;
" | psql -d db$c >psql-$c.log 2>&1 &
done
wait
grep 'missing chunk number' server.log && break;
done
...
iteration 45
iteration 46
iteration 47
2026-07-06 17:38:19.952 UTC|law|db22|6a4be80b.3ab9a8|ERROR: missing chunk number 0 for toast value 41866 in pg_toast_41849
I had failures on iterations 47, 58, 79.
(Konstantin's patch doesn't help either.)
Best regards,
Alexander
^ permalink raw reply [nested|flat] 33+ messages in thread
* Re: BUG #19519: REPACK can fail due to missing chunk for toast value
@ 2026-07-06 18:21 Matthias van de Meent <boekewurm+postgres@gmail.com>
parent: Michael Paquier <michael@paquier.xyz>
2 siblings, 1 reply; 33+ messages in thread
From: Matthias van de Meent @ 2026-07-06 18:21 UTC (permalink / raw)
To: Michael Paquier <michael@paquier.xyz>; +Cc: Imran Zaheer <imran.zhir@gmail.com>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; exclusion@gmail.com, pgsql-bugs@lists.postgresql.org, Konstantin Knizhnik <knizhnik@garret.ru>
On Mon, 6 Jul 2026 at 18:40, Michael Paquier <michael@paquier.xyz> wrote:
>
> On Fri, Jul 03, 2026 at 11:45:42AM +0500, Imran Zaheer wrote:
> > Can we safely use the same fix in the index build path too? Can we use
> > GetOldestNonRemovableTransactionIdforRewrite or something similar
> > here? Normal serial index builds use SnapShotAny and concurrent index
> > builds use MVCC, but the bug only exists in the serial index build
> > path.
>
> Yeah, I think that we should be able to safely reuse your ForRewrite()
> API for the index build case (SnapshotAny part) as well to make the
> horizon computations more conservative, exclusing one own XID as we
> do in the lazy VACUUM case.
>
> > Other than that, after applying your patch, the bug was not
> > reproducible with either this repro or the other report's repro [1] in
> > the rewrite path. However, the create index bug is still there. You
> > can use the following repro as mentioned in the thread [1].
>
> The assymetry between the global xmin computation and the per-database
> horizon is what's killing us here. All these patterns are complicated
> enough that they warrant some tests, even if it is necessary to have
> multiple databases to trigger the buggy horizon computations. TAP
> tests would be an obvious choice for that. Now I have a set of tricks
> in my sleeves to make an isolation test fully deterministic:
> - dblink() that opens a transaction to a different database than the
> one of the isolation regression database.
> - Rename of a TOAST table using allow_system_table_mods, for a VACUUM.
>
> The second one is one of the dirtiest tricks I've done in the past for
> a REINDEX CONCURRENTLY test with TOAST. Quite useful. If the backend
> side change is reverted, the tests fail.
>
> The attached includes both test suites for all four cases reported
> (REPACK, VACUUM, CLUSTER, non-MVCC index builds). We'll need to
> remove one of them, just keeping both posted as I am not sure if the
> isolation tests would be entirely stable in the buildfarm..
>
> I still need to dive more into the code, but for now this bit stands
> out:
> vacuum_get_cutoffs(OldHeap, ¶ms, &cutoffs);
>
> + /*
> + * vacuum_get_cutoffs() folds our own backend's xmin into OldestXmin. For
> + * a rewrite that is too conservative: the snapshot we hold exists only to
> + * evaluate index expressions against other relations, not to read
> + * OldHeap's historical rows. If our xmin is held back by a transaction
> + * that cannot even see OldHeap (e.g. one in another database), we would
> + * preserve a recently-dead tuple whose TOAST chunks a concurrent or prior
> + * lazy vacuum was free to remove, and then fail with "missing chunk" while
> + * copying it. Recompute OldestXmin ignoring our own backend so it matches
> + * the horizon lazy vacuum uses. This can only move OldestXmin forward, so
> + * the freeze cutoffs derived above remain valid.
> + */
> + cutoffs.OldestXmin = GetOldestNonRemovableTransactionIdForRewrite(OldHeap);
>
> In copy_table_data() (for the data copy with repack, cluster, vacuum
> full), I think that this is incorrect. For one, this breaks the
> FreezeLimit which should always be older than OldestXmin, and this
> patch enforces a new recomputation of OldestXmin ignoring most of the
> internals of vacuum_get_cutoffs(). That's brittle, to say the least
> if we change the way the vacuum cutoffs are calculated in the future.
>
> Thoughts and comments from others are welcome for now. My day is
> almost out, at least I got all these scenarios working some tests.
I don't think this approach actually fixes the underlying issue: As I
understand it; the problem is this:
1. OldestNonRemovableTransactionId() is based on the xmin state across
backends. It may increase at any point in time, could even decrease in
certain circumstances[0], and can be in an inconsistent state across
backends.
2. Data is only protected against concurrent cleanup while it's
visible to a MVCC snapshot in some backend, and this is advertised
through the xmin of the backend holding the snapshot being <= the xmin
of the snapshot.
This relation-level cleanup horizon is determined with
GlobalVisTestFor(), which uses the same data source as
OldestNonRemovableTransactionId().
3. All relevant cases of REPACK and CREATE INDEX use SnapshotAny + a
cached output of OldestNonRemovableTransactionId()
The issue here is that CREATE INDEX and REPACK (CI/R) can start with
an OldestXmin of (say) 100, then another backend that held back that
OldestXmin stops holding back the xmin (allowing the output of a new
invocation of OldestNonRemovableTransactionId() to return e.g. 200),
after which the cleanup starts for tuples deleted with transaction ID
< 200, rather than the <100 expected by INDEX/REPACK.
Because both CI and R use SnapshotAny, and stored the result of
OldestNonRemovableTransactionId() from the start of their command
processing, they'll consider any still-present tuple >= 100 to be
visible for their scan.
However, every other backend has stopped considering these tuples
visible for their MVCC, scans and therefore may have started cleaning
up the tuple data. For main relation's heap pages, this cleanup isn't
(much) of an issue, because the fully dead and removed tuples would
have to be cleaned up later anyway and are not interesting for the
scan, but the related toast tuples can also be cleaned up without
first having to wait for the main tuple to be cleaned up, which is
exactly what this issue shows: TOAST expects to be used in an MVCC
context, and thus errors when it fails to find the tuples that were
reclaimed. It's a de-sync between what this backend and what other
backends expect.
So, in effect, this is an issue that's quite similar to the CIC/RIC
bug of PG14<14.4, except that
1.) in this case it's SnapshotAny instead of a
registered-but-invisible MVCC snapshot;
2.) the issue in this case only happens when toast pointers were
cleaned up and then are dereferenced, rather than HOT chains updated
and reclaimed since the scan started; and finally
3.) this issue dates back a very long time, likely since TOAST, but
defininitely since PG14 introduced the GlobalVisTestFor apis.
So I think the only way to fix this is either
1.) we update every maintenance process that makes use of SnapshotAny
and could access TOAST tables to handle errors caused by missing TOAST
data when the base relation's tuple is RECENTLY_DEAD, and treat those
as "tuple cleanup has already started, we just weren't aware of it
yet, so ignore this tuple" (as I mentioned in [1]), or
2.) we set the xmin of the CI/R backend to the current OldestXmin for
the relation(s) we're currently processing, and so block all cleanup
of the relevant (toast) data for the duration of this statement or
whenever we check for a newer xmin for the relation (whilst ignoring
our current one).
Kind regards,
Matthias van de Meent
Databricks (https://www.databricks.com)
[0]: "BUG #17257: (auto)vacuum hangs within lazy_scan_prune()"
https://www.postgresql.org/message-id/flat/CAH2-WznTo_nkbTAoBO2mCR5TzWBj8fEa4%252Bk-K3x9YUYZ0AKVUQ%2...
[1]: "Re: VACUUM FULL or CREATE INDEX fails with error: missing chunk
number 0 for toast value XXX" at -hackers:
https://www.postgresql.org/message-id/CAEze2WgRUfoR%3DtSQQm8zexVNeBbEYi9ZSPztrK63ObyfPxKpBw%40mail.g...
^ permalink raw reply [nested|flat] 33+ messages in thread
* Re: BUG #19519: REPACK can fail due to missing chunk for toast value
@ 2026-07-06 23:18 Michael Paquier <michael@paquier.xyz>
parent: Matthias van de Meent <boekewurm+postgres@gmail.com>
0 siblings, 1 reply; 33+ messages in thread
From: Michael Paquier @ 2026-07-06 23:18 UTC (permalink / raw)
To: Matthias van de Meent <boekewurm+postgres@gmail.com>; +Cc: Imran Zaheer <imran.zhir@gmail.com>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; exclusion@gmail.com, pgsql-bugs@lists.postgresql.org, Konstantin Knizhnik <knizhnik@garret.ru>
On Mon, Jul 06, 2026 at 08:21:41PM +0200, Matthias van de Meent wrote:
> So, in effect, this is an issue that's quite similar to the CIC/RIC
> bug of PG14<14.4, except that
>
> 1.) in this case it's SnapshotAny instead of a
> registered-but-invisible MVCC snapshot;
> 2.) the issue in this case only happens when toast pointers were
> cleaned up and then are dereferenced, rather than HOT chains updated
> and reclaimed since the scan started; and finally
> 3.) this issue dates back a very long time, likely since TOAST, but
> defininitely since PG14 introduced the GlobalVisTestFor apis.
You mean 042b584c7f7d, revert of d9d076222f5b. That rings a bell.
> So I think the only way to fix this is either
> 1.) we update every maintenance process that makes use of SnapshotAny
> and could access TOAST tables to handle errors caused by missing TOAST
> data when the base relation's tuple is RECENTLY_DEAD, and treat those
> as "tuple cleanup has already started, we just weren't aware of it
> yet, so ignore this tuple" (as I mentioned in [1]), or
That seems like an option worth exploring to me, but I doubt that
we'll be able to get something that can be backpatched due to how
invasive it is. I strongly suspect that it would require at least one
table AM change to cope with the fact that we want to let the callers
be OK with TOAST chunks missing in some contexts when grabbing a toast
slice. That's perhaps for the best if we think about potential
regressions, this is scary and old enough that we may still be OK by
living without a backpatch.
> 2.) we set the xmin of the CI/R backend to the current OldestXmin for
> the relation(s) we're currently processing, and so block all cleanup
> of the relevant (toast) data for the duration of this statement or
> whenever we check for a newer xmin for the relation (whilst ignoring
> our current one).
Err, I don't think that would be safe anyway? It's rather uncommon in
practice in schemas, but we could trigger function calls, like index
expressions, domains, whatever, that access data of other tables while
processing one table with a SnapshotAny. The CIC revert of 14.4 was
about such cases.
--
Michael
Attachments:
signature.asc (application/pgp-signature, 832B) download
^ permalink raw reply [nested|flat] 33+ messages in thread
* Re: BUG #19519: REPACK can fail due to missing chunk for toast value
@ 2026-07-06 23:51 Matthias van de Meent <boekewurm+postgres@gmail.com>
parent: Michael Paquier <michael@paquier.xyz>
0 siblings, 1 reply; 33+ messages in thread
From: Matthias van de Meent @ 2026-07-06 23:51 UTC (permalink / raw)
To: Michael Paquier <michael@paquier.xyz>; +Cc: Imran Zaheer <imran.zhir@gmail.com>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; Alexander Lakhin <exclusion@gmail.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>; Konstantin Knizhnik <knizhnik@garret.ru>
On Tue, 7 Jul 2026, 01:19 Michael Paquier, <michael@paquier.xyz> wrote:
> On Mon, Jul 06, 2026 at 08:21:41PM +0200, Matthias van de Meent wrote:
> > So, in effect, this is an issue that's quite similar to the CIC/RIC
> > bug of PG14<14.4, except that
> >
> > 1.) in this case it's SnapshotAny instead of a
> > registered-but-invisible MVCC snapshot;
> > 2.) the issue in this case only happens when toast pointers were
> > cleaned up and then are dereferenced, rather than HOT chains updated
> > and reclaimed since the scan started; and finally
> > 3.) this issue dates back a very long time, likely since TOAST, but
> > defininitely since PG14 introduced the GlobalVisTestFor apis.
>
> You mean 042b584c7f7d, revert of d9d076222f5b. That rings a bell.
>
Indeed
> > So I think the only way to fix this is either
> > 1.) we update every maintenance process that makes use of SnapshotAny
> > and could access TOAST tables to handle errors caused by missing TOAST
> > data when the base relation's tuple is RECENTLY_DEAD, and treat those
> > as "tuple cleanup has already started, we just weren't aware of it
> > yet, so ignore this tuple" (as I mentioned in [1]), or
>
> That seems like an option worth exploring to me, but I doubt that
> we'll be able to get something that can be backpatched due to how
> invasive it is. I strongly suspect that it would require at least one
> table AM change to cope with the fact that we want to let the callers
> be OK with TOAST chunks missing in some contexts when grabbing a toast
> slice. That's perhaps for the best if we think about potential
> regressions, this is scary and old enough that we may still be OK by
> living without a backpatch.
>
I suspect that for indexing we're lucky, in that we have full control
internally over which tuple data get fed into IndexBuildCallback. We can
make sure only fully detoasted attributes get passed on, and can be
implemented with some (a lot) of TRY/CATCH work in or around
FormIndexDatum. That said, I don't think that's very nice, and I'm also a
bit concerned about leaking things (memory, buffers, ...) in such an
approach.
For REPACK/VACUUM FULL/CLUSTER, I think we can do something similar, given
that this code too has a central loop processing the tuple data, though I
suspect it'll need a bit more work than the reindex one.
> 2.) we set the xmin of the CI/R backend to the current OldestXmin for
> > the relation(s) we're currently processing, and so block all cleanup
> > of the relevant (toast) data for the duration of this statement or
> > whenever we check for a newer xmin for the relation (whilst ignoring
> > our current one).
>
> Err, I don't think that would be safe anyway? It's rather uncommon in
> practice in schemas, but we could trigger function calls, like index
> expressions, domains, whatever, that access data of other tables while
> processing one table with a SnapshotAny. The CIC revert of 14.4 was
> about such cases.
>
True, but in indexes that is forbidden: mislabeling of non-INMUTABLE
functions causes broken indexes every day, and we can't be expected to make
it work there. Similarly, for REPACK it shouldn't evaluate any
non-indexable expressions, right?
Either way, if we can register a snapshot in the REPACK/INDEX backend whose
xmin is (*correctly*) registered with the OldestNonRemovableTransactionId()
of the relation, then concurrent cleanup won't happen for toast, and we'd
also avoid dereferencing those dangling toast pointers. We won't need to
actually use that snapshot for any scans; it'll avoid the issue as long as
our backend advertises an xmin <= the OldestXmin used in maintenance to
hold back pruning/vacuum on the relation.
(we can adjust that xmin every once in a while with a newer
OldestNonRemovableTransactionId (excl. our own backend) as long as we also
adjust the OldestXmin cutoff for the SnapshotAny visibility tests, but I
don't suggest to backpatch that even newer system, it'd add significant
complications to an already complicated system)
- Matthias
ps. sorry for the formatting, I'm writing this on my phone.
^ permalink raw reply [nested|flat] 33+ messages in thread
* Re: BUG #19519: REPACK can fail due to missing chunk for toast value
@ 2026-07-07 01:42 Michael Paquier <michael@paquier.xyz>
parent: Matthias van de Meent <boekewurm+postgres@gmail.com>
0 siblings, 2 replies; 33+ messages in thread
From: Michael Paquier @ 2026-07-07 01:42 UTC (permalink / raw)
To: Matthias van de Meent <boekewurm+postgres@gmail.com>; +Cc: Imran Zaheer <imran.zhir@gmail.com>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; Alexander Lakhin <exclusion@gmail.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>; Konstantin Knizhnik <knizhnik@garret.ru>
On Tue, Jul 07, 2026 at 01:51:32AM +0200, Matthias van de Meent wrote:
> On Tue, 7 Jul 2026, 01:19 Michael Paquier, <michael@paquier.xyz> wrote:
>
>> On Mon, Jul 06, 2026 at 08:21:41PM +0200, Matthias van de Meent wrote:
>>> So, in effect, this is an issue that's quite similar to the CIC/RIC
>>> bug of PG14<14.4, except that
>>>
>>> 1.) in this case it's SnapshotAny instead of a
>>> registered-but-invisible MVCC snapshot;
>>> 2.) the issue in this case only happens when toast pointers were
>>> cleaned up and then are dereferenced, rather than HOT chains updated
>>> and reclaimed since the scan started; and finally
>>> 3.) this issue dates back a very long time, likely since TOAST, but
>>> defininitely since PG14 introduced the GlobalVisTestFor apis.
>>
>> You mean 042b584c7f7d, revert of d9d076222f5b. That rings a bell.
>>
>
> Indeed
>
>
>>> So I think the only way to fix this is either
>>> 1.) we update every maintenance process that makes use of SnapshotAny
>>> and could access TOAST tables to handle errors caused by missing TOAST
>>> data when the base relation's tuple is RECENTLY_DEAD, and treat those
>>> as "tuple cleanup has already started, we just weren't aware of it
>>> yet, so ignore this tuple" (as I mentioned in [1]), or
>>
>> That seems like an option worth exploring to me, but I doubt that
>> we'll be able to get something that can be backpatched due to how
>> invasive it is. I strongly suspect that it would require at least one
>> table AM change to cope with the fact that we want to let the callers
>> be OK with TOAST chunks missing in some contexts when grabbing a toast
>> slice. That's perhaps for the best if we think about potential
>> regressions, this is scary and old enough that we may still be OK by
>> living without a backpatch.
>>
>
> I suspect that for indexing we're lucky, in that we have full control
> internally over which tuple data get fed into IndexBuildCallback. We can
> make sure only fully detoasted attributes get passed on, and can be
> implemented with some (a lot) of TRY/CATCH work in or around
> FormIndexDatum. That said, I don't think that's very nice, and I'm also a
> bit concerned about leaking things (memory, buffers, ...) in such an
> approach.
I've quickly thought about some try/catch blocks while detoasting, but
I cannot really get how this would be entirely bullet-proof. It seems
to me that we'll live better if we bite the bullet and go for the
invasive change of passing a state across the stack to let detoasting
know that we are dealing with a rewrite.
> For REPACK/VACUUM FULL/CLUSTER, I think we can do something similar, given
> that this code too has a central loop processing the tuple data, though I
> suspect it'll need a bit more work than the reindex one.
While looking at the whole stack, the handling of dead tuples seems to
go through only index_build_range_scan() and
relation_copy_for_cluster() for heapam. A re-check for TOAST values
would be really bad if we have a lot of dead tuples.
>> 2.) we set the xmin of the CI/R backend to the current OldestXmin for
>>> the relation(s) we're currently processing, and so block all cleanup
>>> of the relevant (toast) data for the duration of this statement or
>>> whenever we check for a newer xmin for the relation (whilst ignoring
>>> our current one).
>>
>> Err, I don't think that would be safe anyway? It's rather uncommon in
>> practice in schemas, but we could trigger function calls, like index
>> expressions, domains, whatever, that access data of other tables while
>> processing one table with a SnapshotAny. The CIC revert of 14.4 was
>> about such cases.
>
> True, but in indexes that is forbidden: mislabeling of non-INMUTABLE
> functions causes broken indexes every day, and we can't be expected to make
> it work there. Similarly, for REPACK it shouldn't evaluate any
> non-indexable expressions, right?
Still I am pretty sure that the window would exist, users like fancy
definitions. It seems at least worth looking if we could make
something more stable across the board. Just playing with it now, and
it does not seem that bad in practice, actually..
> Either way, if we can register a snapshot in the REPACK/INDEX backend whose
> xmin is (*correctly*) registered with the OldestNonRemovableTransactionId()
> of the relation, then concurrent cleanup won't happen for toast, and we'd
> also avoid dereferencing those dangling toast pointers. We won't need to
> actually use that snapshot for any scans; it'll avoid the issue as long as
> our backend advertises an xmin <= the OldestXmin used in maintenance to
> hold back pruning/vacuum on the relation.
>
> (we can adjust that xmin every once in a while with a newer
> OldestNonRemovableTransactionId (excl. our own backend) as long as we also
> adjust the OldestXmin cutoff for the SnapshotAny visibility tests, but I
> don't suggest to backpatch that even newer system, it'd add significant
> complications to an already complicated system)
I doubt that anything would be backpatchable, based on how the
discussion is going. I'm OK to be proven wrong.
> ps. sorry for the formatting, I'm writing this on my phone.
No pb. Thanks.
--
Michael
Attachments:
signature.asc (application/pgp-signature, 832B) download
^ permalink raw reply [nested|flat] 33+ messages in thread
* Re: BUG #19519: REPACK can fail due to missing chunk for toast value
@ 2026-07-07 05:21 Michael Paquier <michael@paquier.xyz>
parent: Michael Paquier <michael@paquier.xyz>
1 sibling, 1 reply; 33+ messages in thread
From: Michael Paquier @ 2026-07-07 05:21 UTC (permalink / raw)
To: Matthias van de Meent <boekewurm+postgres@gmail.com>; +Cc: Imran Zaheer <imran.zhir@gmail.com>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; Alexander Lakhin <exclusion@gmail.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>; Konstantin Knizhnik <knizhnik@garret.ru>
On Tue, Jul 07, 2026 at 10:42:33AM +0900, Michael Paquier wrote:
> I've quickly thought about some try/catch blocks while detoasting, but
> I cannot really get how this would be entirely bullet-proof. It seems
> to me that we'll live better if we bite the bullet and go for the
> invasive change of passing a state across the stack to let detoasting
> know that we are dealing with a rewrite.
I have been playing with this idea, with two approaches. For the
REPACK and VACUUM cases, things looked pretty straight for both
approaches, but the index build got hairy in the first case:
1) Attempt to shortcut missing TOAST chunks when doing index builds.
For hash and btree, things get straight with index_form_tuple(). But
I've quickly faced a wall with GIN (extractValue support function) and
GiST (compress function). So at the end I gave up on that, as it
would require more facilities than this looks worth for.
2) A more aggressive pre-detoast when building a range of values for
tuples that we are seeing as already dead, which should be able to
work across all index AMs transparently when we are dealing with dead
tuples (that should be kept in a per-tuple context). That's what I
guess you've mentioned upthread.
Option 2 leads to a much nicer result overall, with the attached
passing my regression tests and Alexander's case as well (highly
concurrent thing sent yesterday). The rest of the patch is kind of
boring, where I have been trying to get a missing_ok state across the
stack to let the toast slice fetch bypass the case of missing chunks
when we are OK with it due to the rewrites. That still feels crude,
but the simplicity is appealing here, as much as the rather low
invasiveness.
Thoughts or comments?
--
Michael
Attachments:
v3-0001-Fix-missing-chunk-errors-during-heap-rewrites-and.patch (text/plain, 36.5K) download
From 2e9cc62deda3de859ee389772471734a2f4f9e5d Mon Sep 17 00:00:00 2001
From: Michael Paquier <michael@paquier.xyz>
Date: Tue, 7 Jul 2026 14:20:30 +0900
Subject: [PATCH v3] Fix "missing chunk" errors during heap rewrites and index
builds
Blah, blah.
This problem has been reported recently by Alexander for REPACK, but it
is a much older issue (tested down to 9.5 for curiosity's sake, but I
suspect that it is much older than that).
XXX: This patch includes both TAP and isolation tests. We should remove
one pattern at the end.
Reported-by: Alexander Lakhin <exclusion@gmail.com>
Discussion: https://postgr.es/m/18351-f6e06364b3a2e669@postgresql.org
Discussion: https://postgr.es/m/19519-fe02d8ff679d834d@postgresql.org
---
src/include/access/detoast.h | 9 +
src/include/access/heaptoast.h | 13 +-
src/include/access/rewriteheap.h | 4 +-
src/include/access/tableam.h | 24 +-
src/include/access/toast_helper.h | 2 +-
src/backend/access/common/detoast.c | 41 ++-
src/backend/access/heap/heapam.c | 4 +-
src/backend/access/heap/heapam_handler.c | 94 ++++++-
src/backend/access/heap/heaptoast.c | 22 +-
src/backend/access/heap/rewriteheap.c | 31 ++-
src/backend/access/table/toast_helper.c | 17 +-
src/test/recovery/meson.build | 1 +
src/test/recovery/t/055_rewrite_stale_xmin.pl | 124 +++++++++
contrib/dblink/.gitignore | 2 +
contrib/dblink/Makefile | 2 +
.../dblink/expected/rewrite_stale_xmin.out | 237 ++++++++++++++++++
contrib/dblink/meson.build | 5 +
contrib/dblink/specs/rewrite_stale_xmin.spec | 137 ++++++++++
18 files changed, 718 insertions(+), 51 deletions(-)
create mode 100644 src/test/recovery/t/055_rewrite_stale_xmin.pl
create mode 100644 contrib/dblink/expected/rewrite_stale_xmin.out
create mode 100644 contrib/dblink/specs/rewrite_stale_xmin.spec
diff --git a/src/include/access/detoast.h b/src/include/access/detoast.h
index fbd98181a3a1..c5eeed04b011 100644
--- a/src/include/access/detoast.h
+++ b/src/include/access/detoast.h
@@ -43,6 +43,15 @@ do { \
*/
extern varlena *detoast_external_attr(varlena *attr);
+/* ----------
+ * detoast_external_attr_extended() -
+ *
+ * Like detoast_external_attr, but returns NULL if toast chunks
+ * are missing (instead of raising an error).
+ * ----------
+ */
+extern varlena *detoast_external_attr_extended(varlena *attr);
+
/* ----------
* detoast_attr() -
*
diff --git a/src/include/access/heaptoast.h b/src/include/access/heaptoast.h
index 631cb1836b96..1be85db6ddd2 100644
--- a/src/include/access/heaptoast.h
+++ b/src/include/access/heaptoast.h
@@ -92,10 +92,14 @@
* heap_toast_insert_or_update -
*
* Called by heap_insert() and heap_update().
+ *
+ * If missing_ok is true, returns NULL when failing to fetch external
+ * TOAST data, instead of throwing an error.
* ----------
*/
extern HeapTuple heap_toast_insert_or_update(Relation rel, HeapTuple newtup,
- HeapTuple oldtup, uint32 options);
+ HeapTuple oldtup, uint32 options,
+ bool missing_ok);
/* ----------
* heap_toast_delete -
@@ -140,10 +144,13 @@ extern HeapTuple toast_build_flattened_tuple(TupleDesc tupleDesc,
* heap_fetch_toast_slice
*
* Fetch a slice from a toast value stored in a heap table.
+ * If missing_ok is true, returns false when chunks are missing
+ * instead of raising an error. Returns true on success.
* ----------
*/
-extern void heap_fetch_toast_slice(Relation toastrel, Oid valueid,
+extern bool heap_fetch_toast_slice(Relation toastrel, Oid valueid,
int32 attrsize, int32 sliceoffset,
- int32 slicelength, varlena *result);
+ int32 slicelength, varlena *result,
+ bool missing_ok);
#endif /* HEAPTOAST_H */
diff --git a/src/include/access/rewriteheap.h b/src/include/access/rewriteheap.h
index 6ccf7b45c04e..df4fa4fde710 100644
--- a/src/include/access/rewriteheap.h
+++ b/src/include/access/rewriteheap.h
@@ -25,8 +25,8 @@ extern RewriteState begin_heap_rewrite(Relation old_heap, Relation new_heap,
TransactionId oldest_xmin, TransactionId freeze_xid,
MultiXactId cutoff_multi);
extern void end_heap_rewrite(RewriteState state);
-extern void rewrite_heap_tuple(RewriteState state, HeapTuple old_tuple,
- HeapTuple new_tuple);
+extern bool rewrite_heap_tuple(RewriteState state, HeapTuple old_tuple,
+ HeapTuple new_tuple, bool missing_ok);
extern bool rewrite_heap_dead_tuple(RewriteState state, HeapTuple old_tuple);
/*
diff --git a/src/include/access/tableam.h b/src/include/access/tableam.h
index f2c36696bcad..a90b15dd82b3 100644
--- a/src/include/access/tableam.h
+++ b/src/include/access/tableam.h
@@ -782,12 +782,16 @@ typedef struct TableAmRoutine
* This callback is invoked when detoasting a value stored in a toast
* table implemented by this AM. See table_relation_fetch_toast_slice()
* for more details.
+ *
+ * If missing_ok is true, returns false when chunks are missing instead of
+ * raising an error. Returns true on success.
*/
- void (*relation_fetch_toast_slice) (Relation toastrel, Oid valueid,
+ bool (*relation_fetch_toast_slice) (Relation toastrel, Oid valueid,
int32 attrsize,
int32 sliceoffset,
int32 slicelength,
- varlena *result);
+ varlena *result,
+ bool missing_ok);
/* ------------------------------------------------------------------------
@@ -1981,16 +1985,20 @@ table_relation_toast_am(Relation rel)
*
* result is caller-allocated space into which the fetched bytes should be
* stored.
+ *
+ * missing_ok: if true, return false when toast chunks are missing instead
+ * of raising an error. Returns true on success.
*/
-static inline void
+static inline bool
table_relation_fetch_toast_slice(Relation toastrel, Oid valueid,
int32 attrsize, int32 sliceoffset,
- int32 slicelength, varlena *result)
+ int32 slicelength, varlena *result,
+ bool missing_ok)
{
- toastrel->rd_tableam->relation_fetch_toast_slice(toastrel, valueid,
- attrsize,
- sliceoffset, slicelength,
- result);
+ return toastrel->rd_tableam->relation_fetch_toast_slice(toastrel, valueid,
+ attrsize,
+ sliceoffset, slicelength,
+ result, missing_ok);
}
diff --git a/src/include/access/toast_helper.h b/src/include/access/toast_helper.h
index 2ec92397f267..e548ba5596b4 100644
--- a/src/include/access/toast_helper.h
+++ b/src/include/access/toast_helper.h
@@ -101,7 +101,7 @@ typedef struct
#define TOASTCOL_IGNORE 0x0010
#define TOASTCOL_INCOMPRESSIBLE 0x0020
-extern void toast_tuple_init(ToastTupleContext *ttc);
+extern bool toast_tuple_init(ToastTupleContext *ttc, bool missing_ok);
extern int toast_tuple_find_biggest_attribute(ToastTupleContext *ttc,
bool for_compression,
bool check_main);
diff --git a/src/backend/access/common/detoast.c b/src/backend/access/common/detoast.c
index a6c1f3a734b2..c16b61a1cb1c 100644
--- a/src/backend/access/common/detoast.c
+++ b/src/backend/access/common/detoast.c
@@ -22,7 +22,7 @@
#include "utils/expandeddatum.h"
#include "utils/rel.h"
-static varlena *toast_fetch_datum(varlena *attr);
+static varlena *toast_fetch_datum(varlena *attr, bool missing_ok);
static varlena *toast_fetch_datum_slice(varlena *attr,
int32 sliceoffset,
int32 slicelength);
@@ -51,7 +51,7 @@ detoast_external_attr(varlena *attr)
/*
* This is an external stored plain value
*/
- result = toast_fetch_datum(attr);
+ result = toast_fetch_datum(attr, false);
}
else if (VARATT_IS_EXTERNAL_INDIRECT(attr))
{
@@ -102,6 +102,23 @@ detoast_external_attr(varlena *attr)
}
+/* ----------
+ * detoast_external_attr_extended -
+ *
+ * Like detoast_external_attr, but returns NULL if toast chunks are
+ * missing for external pointers.
+ * ----------
+ */
+varlena *
+detoast_external_attr_extended(varlena *attr)
+{
+ if (VARATT_IS_EXTERNAL_ONDISK(attr))
+ return toast_fetch_datum(attr, true);
+ else
+ return detoast_external_attr(attr);
+}
+
+
/* ----------
* detoast_attr -
*
@@ -120,7 +137,7 @@ detoast_attr(varlena *attr)
/*
* This is an externally stored datum --- fetch it back from there
*/
- attr = toast_fetch_datum(attr);
+ attr = toast_fetch_datum(attr, false);
/* If it's compressed, decompress it */
if (VARATT_IS_COMPRESSED(attr))
{
@@ -262,7 +279,7 @@ detoast_attr_slice(varlena *attr,
preslice = toast_fetch_datum_slice(attr, 0, max_size);
}
else
- preslice = toast_fetch_datum(attr);
+ preslice = toast_fetch_datum(attr, false);
}
else if (VARATT_IS_EXTERNAL_INDIRECT(attr))
{
@@ -337,10 +354,12 @@ detoast_attr_slice(varlena *attr,
*
* Reconstruct an in memory Datum from the chunks saved
* in the toast relation
+ *
+ * If missing_ok is true, returns NULL when chunks are missing.
* ----------
*/
static varlena *
-toast_fetch_datum(varlena *attr)
+toast_fetch_datum(varlena *attr, bool missing_ok)
{
Relation toastrel;
varlena *result;
@@ -372,8 +391,14 @@ toast_fetch_datum(varlena *attr)
toastrel = table_open(toast_pointer.va_toastrelid, AccessShareLock);
/* Fetch all chunks */
- table_relation_fetch_toast_slice(toastrel, toast_pointer.va_valueid,
- attrsize, 0, attrsize, result);
+ if (!table_relation_fetch_toast_slice(toastrel, toast_pointer.va_valueid,
+ attrsize, 0, attrsize, result,
+ missing_ok))
+ {
+ pfree(result);
+ table_close(toastrel, AccessShareLock);
+ return NULL;
+ }
/* Close toast table */
table_close(toastrel, AccessShareLock);
@@ -454,7 +479,7 @@ toast_fetch_datum_slice(varlena *attr, int32 sliceoffset,
/* Fetch all chunks */
table_relation_fetch_toast_slice(toastrel, toast_pointer.va_valueid,
attrsize, sliceoffset, slicelength,
- result);
+ result, false);
/* Close toast table */
table_close(toastrel, AccessShareLock);
diff --git a/src/backend/access/heap/heapam.c b/src/backend/access/heap/heapam.c
index abfd8e8970a6..1d4018931200 100644
--- a/src/backend/access/heap/heapam.c
+++ b/src/backend/access/heap/heapam.c
@@ -2236,7 +2236,7 @@ heap_prepare_insert(Relation relation, HeapTuple tup, TransactionId xid,
return tup;
}
else if (HeapTupleHasExternal(tup) || tup->t_len > TOAST_TUPLE_THRESHOLD)
- return heap_toast_insert_or_update(relation, tup, NULL, options);
+ return heap_toast_insert_or_update(relation, tup, NULL, options, false);
else
return tup;
}
@@ -3871,7 +3871,7 @@ l2:
if (need_toast)
{
/* Note we always use WAL and FSM during updates */
- heaptup = heap_toast_insert_or_update(relation, newtup, &oldtup, 0);
+ heaptup = heap_toast_insert_or_update(relation, newtup, &oldtup, 0, false);
newtupsize = MAXALIGN(heaptup->t_len);
}
else
diff --git a/src/backend/access/heap/heapam_handler.c b/src/backend/access/heap/heapam_handler.c
index 2268cc277bce..2cd9d0f4aeb9 100644
--- a/src/backend/access/heap/heapam_handler.c
+++ b/src/backend/access/heap/heapam_handler.c
@@ -19,6 +19,7 @@
*/
#include "postgres.h"
+#include "access/detoast.h"
#include "access/genam.h"
#include "access/heapam.h"
#include "access/heaptoast.h"
@@ -48,9 +49,10 @@
#include "utils/rel.h"
#include "utils/tuplesort.h"
-static void reform_and_rewrite_tuple(HeapTuple tuple,
+static bool reform_and_rewrite_tuple(HeapTuple tuple,
Relation OldHeap, Relation NewHeap,
- Datum *values, bool *isnull, RewriteState rwstate);
+ Datum *values, bool *isnull, RewriteState rwstate,
+ bool missing_ok);
static void heap_insert_for_repack(HeapTuple tuple, Relation OldHeap,
Relation NewHeap, Datum *values, bool *isnull,
BulkInsertState bistate);
@@ -717,6 +719,7 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,
HeapTuple tuple;
Buffer buf;
bool isdead;
+ bool recently_dead = false;
CHECK_FOR_INTERRUPTS();
@@ -802,6 +805,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 */
@@ -835,6 +839,7 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,
RelationGetRelationName(OldHeap));
/* treat as recently dead */
*tups_recently_dead += 1;
+ recently_dead = true;
isdead = false;
break;
default:
@@ -881,8 +886,22 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,
int64 ct_val[2];
if (!concurrent)
- reform_and_rewrite_tuple(tuple, OldHeap, NewHeap,
- values, isnull, rwstate);
+ {
+ if (!reform_and_rewrite_tuple(tuple, OldHeap, NewHeap,
+ values, isnull, rwstate,
+ recently_dead))
+ {
+ /*
+ * Missing TOAST chunks for a recently-dead tuple. Treat
+ * it as dead.
+ */
+ *tups_vacuumed += 1;
+ *num_tuples -= 1;
+ if (recently_dead)
+ *tups_recently_dead -= 1;
+ continue;
+ }
+ }
else
heap_insert_for_repack(tuple, OldHeap, NewHeap,
values, isnull, bistate);
@@ -934,10 +953,17 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,
n_tuples += 1;
if (!concurrent)
- reform_and_rewrite_tuple(tuple,
- OldHeap, NewHeap,
- values, isnull,
- rwstate);
+ {
+ if (!reform_and_rewrite_tuple(tuple,
+ OldHeap, NewHeap,
+ values, isnull,
+ rwstate, true))
+ {
+ /* TOAST gone for a recently dead tuple */
+ n_tuples -= 1;
+ continue;
+ }
+ }
else
heap_insert_for_repack(tuple, OldHeap, NewHeap,
values, isnull, bistate);
@@ -1613,6 +1639,43 @@ heapam_index_build_range_scan(Relation heapRelation,
continue;
}
+ /*
+ * For RECENTLY_DEAD tuples, pre-detoast external TOAST values. We do
+ * this to detect for missing chunks at later stages, feeding inline
+ * data to the downstream access method code.
+ */
+ if (!tupleIsAlive)
+ {
+ TupleDesc tdesc = RelationGetDescr(heapRelation);
+ bool skip = false;
+
+ slot_getallattrs(slot);
+ for (int i = 0; i < tdesc->natts; i++)
+ {
+ Form_pg_attribute att = TupleDescAttr(tdesc, i);
+
+ if (att->attlen != -1 || att->attisdropped)
+ continue;
+ if (slot->tts_isnull[i])
+ continue;
+ if (VARATT_IS_EXTERNAL_ONDISK(DatumGetPointer(slot->tts_values[i])))
+ {
+ varlena *detoasted;
+
+ detoasted = detoast_external_attr_extended(
+ (varlena *) DatumGetPointer(slot->tts_values[i]));
+ if (detoasted == NULL)
+ {
+ skip = true;
+ break;
+ }
+ slot->tts_values[i] = PointerGetDatum(detoasted);
+ }
+ }
+ if (skip)
+ continue;
+ }
+
/*
* For the current heap tuple, extract all the attributes we use in
* this index, and note which are null. This also performs evaluation
@@ -2347,20 +2410,29 @@ heapam_scan_sample_next_tuple(TableScanDesc scan, SampleScanState *scanstate,
* SET WITHOUT OIDS.
*
* So, we must reconstruct the tuple from component Datums.
+ *
+ * Returns true on success, and false on failure if missing_ok is
+ * true.
*/
-static void
+static bool
reform_and_rewrite_tuple(HeapTuple tuple,
Relation OldHeap, Relation NewHeap,
- Datum *values, bool *isnull, RewriteState rwstate)
+ Datum *values, bool *isnull, RewriteState rwstate,
+ bool missing_ok)
{
HeapTuple newtuple;
newtuple = reform_tuple(tuple, OldHeap, NewHeap, values, isnull);
/* The heap rewrite module does the rest */
- rewrite_heap_tuple(rwstate, tuple, newtuple);
+ if (!rewrite_heap_tuple(rwstate, tuple, newtuple, missing_ok))
+ {
+ heap_freetuple(newtuple);
+ return false;
+ }
heap_freetuple(newtuple);
+ return true;
}
/*
diff --git a/src/backend/access/heap/heaptoast.c b/src/backend/access/heap/heaptoast.c
index 03f885a25b07..38896a0c7492 100644
--- a/src/backend/access/heap/heaptoast.c
+++ b/src/backend/access/heap/heaptoast.c
@@ -94,7 +94,7 @@ heap_toast_delete(Relation rel, HeapTuple oldtup, bool is_speculative)
*/
HeapTuple
heap_toast_insert_or_update(Relation rel, HeapTuple newtup, HeapTuple oldtup,
- uint32 options)
+ uint32 options, bool missing_ok)
{
HeapTuple result_tuple;
TupleDesc tupleDesc;
@@ -154,7 +154,8 @@ heap_toast_insert_or_update(Relation rel, HeapTuple newtup, HeapTuple oldtup,
ttc.ttc_oldisnull = toast_oldisnull;
}
ttc.ttc_attr = toast_attr;
- toast_tuple_init(&ttc);
+ if (!toast_tuple_init(&ttc, missing_ok))
+ return NULL;
/* ----------
* Compress and/or save external until data fits into target length
@@ -621,11 +622,14 @@ toast_build_flattened_tuple(TupleDesc tupleDesc,
* sliceoffset is the byte offset within the TOAST value from which to fetch.
* slicelength is the number of bytes to be fetched from the TOAST value.
* result is the varlena into which the results should be written.
+ * missing_ok if true, return false on missing chunks instead of error.
+ *
+ * Returns true on success, false if missing_ok and chunks are missing.
*/
-void
+bool
heap_fetch_toast_slice(Relation toastrel, Oid valueid, int32 attrsize,
int32 sliceoffset, int32 slicelength,
- varlena *result)
+ varlena *result, bool missing_ok)
{
Relation *toastidxs;
ScanKeyData toastkey[3];
@@ -779,13 +783,23 @@ heap_fetch_toast_slice(Relation toastrel, Oid valueid, int32 attrsize,
* Final checks that we successfully fetched the datum
*/
if (expectedchunk != (endchunk + 1))
+ {
+ if (missing_ok)
+ {
+ systable_endscan_ordered(toastscan);
+ toast_close_indexes(toastidxs, num_indexes, AccessShareLock);
+ return false;
+ }
ereport(ERROR,
(errcode(ERRCODE_DATA_CORRUPTED),
errmsg_internal("missing chunk number %d for toast value %u in %s",
expectedchunk, valueid,
RelationGetRelationName(toastrel))));
+ }
/* End scan and close indexes. */
systable_endscan_ordered(toastscan);
toast_close_indexes(toastidxs, num_indexes, AccessShareLock);
+
+ return true;
}
diff --git a/src/backend/access/heap/rewriteheap.c b/src/backend/access/heap/rewriteheap.c
index 5a5398a76ae7..fbb6e6ca1f94 100644
--- a/src/backend/access/heap/rewriteheap.c
+++ b/src/backend/access/heap/rewriteheap.c
@@ -211,7 +211,8 @@ typedef struct RewriteMappingDataEntry
/* prototypes for internal functions */
-static void raw_heap_insert(RewriteState state, HeapTuple tup);
+static bool raw_heap_insert(RewriteState state, HeapTuple tup,
+ bool missing_ok);
/* internal logical remapping prototypes */
static void logical_begin_heap_rewrite(RewriteState state);
@@ -309,7 +310,7 @@ end_heap_rewrite(RewriteState state)
while ((unresolved = hash_seq_search(&seq_status)) != NULL)
{
ItemPointerSetInvalid(&unresolved->tuple->t_data->t_ctid);
- raw_heap_insert(state, unresolved->tuple);
+ raw_heap_insert(state, unresolved->tuple, false);
}
/* Write the last page, if any */
@@ -338,9 +339,10 @@ end_heap_rewrite(RewriteState state)
* old_tuple original tuple in the old heap
* new_tuple new, rewritten tuple to be inserted to new heap
*/
-void
+bool
rewrite_heap_tuple(RewriteState state,
- HeapTuple old_tuple, HeapTuple new_tuple)
+ HeapTuple old_tuple, HeapTuple new_tuple,
+ bool missing_ok)
{
MemoryContext old_cxt;
ItemPointerData old_tid;
@@ -437,7 +439,7 @@ rewrite_heap_tuple(RewriteState state,
* tuple will be written.
*/
MemoryContextSwitchTo(old_cxt);
- return;
+ return true;
}
}
@@ -455,7 +457,13 @@ rewrite_heap_tuple(RewriteState state,
ItemPointerData new_tid;
/* Insert the tuple and find out where it's put in new_heap */
- raw_heap_insert(state, new_tuple);
+ if (!raw_heap_insert(state, new_tuple, missing_ok))
+ {
+ if (free_new)
+ heap_freetuple(new_tuple);
+ MemoryContextSwitchTo(old_cxt);
+ return false;
+ }
new_tid = new_tuple->t_self;
logical_rewrite_heap_tuple(state, old_tid, new_tuple);
@@ -532,6 +540,7 @@ rewrite_heap_tuple(RewriteState state,
}
MemoryContextSwitchTo(old_cxt);
+ return true;
}
/*
@@ -593,8 +602,8 @@ rewrite_heap_dead_tuple(RewriteState state, HeapTuple old_tuple)
* tuple is invalid on entry, it's replaced with the new TID as well (in
* the inserted data only, not in the caller's copy).
*/
-static void
-raw_heap_insert(RewriteState state, HeapTuple tup)
+static bool
+raw_heap_insert(RewriteState state, HeapTuple tup, bool missing_ok)
{
Page page;
Size pageFreeSpace,
@@ -628,7 +637,9 @@ raw_heap_insert(RewriteState state, HeapTuple tup)
options |= HEAP_INSERT_NO_LOGICAL;
heaptup = heap_toast_insert_or_update(state->rs_new_rel, tup, NULL,
- options);
+ options, missing_ok);
+ if (heaptup == NULL)
+ return false;
}
else
heaptup = tup;
@@ -702,6 +713,8 @@ raw_heap_insert(RewriteState state, HeapTuple tup)
/* If heaptup is a private copy, release it. */
if (heaptup != tup)
heap_freetuple(heaptup);
+
+ return true;
}
/* ------------------------------------------------------------------------
diff --git a/src/backend/access/table/toast_helper.c b/src/backend/access/table/toast_helper.c
index 2f2022d99510..7e98c01a5eee 100644
--- a/src/backend/access/table/toast_helper.c
+++ b/src/backend/access/table/toast_helper.c
@@ -36,9 +36,12 @@
* toast_flags is just a single uint8, but toast_attr is a caller-provided
* array with a length equal to tupleDesc->natts. The caller need not
* perform any initialization of the array before calling this function.
+ *
+ * If missing_ok is true and an external TOAST value cannot be fetched,
+ * returns false. Returns true on success.
*/
-void
-toast_tuple_init(ToastTupleContext *ttc)
+bool
+toast_tuple_init(ToastTupleContext *ttc, bool missing_ok)
{
TupleDesc tupleDesc = ttc->ttc_rel->rd_att;
int numAttrs = tupleDesc->natts;
@@ -137,7 +140,13 @@ toast_tuple_init(ToastTupleContext *ttc)
if (VARATT_IS_EXTERNAL(new_value))
{
ttc->ttc_attr[i].tai_oldexternal = new_value;
- if (att->attstorage == TYPSTORAGE_PLAIN)
+ if (missing_ok && VARATT_IS_EXTERNAL_ONDISK(new_value))
+ {
+ new_value = detoast_external_attr_extended(new_value);
+ if (new_value == NULL)
+ return false;
+ }
+ else if (att->attstorage == TYPSTORAGE_PLAIN)
new_value = detoast_attr(new_value);
else
new_value = detoast_external_attr(new_value);
@@ -159,6 +168,8 @@ toast_tuple_init(ToastTupleContext *ttc)
ttc->ttc_attr[i].tai_colflags |= TOASTCOL_IGNORE;
}
}
+
+ return true;
}
/*
diff --git a/src/test/recovery/meson.build b/src/test/recovery/meson.build
index ad0d85f41897..7e583ee39a10 100644
--- a/src/test/recovery/meson.build
+++ b/src/test/recovery/meson.build
@@ -63,6 +63,7 @@ tests += {
't/052_checkpoint_segment_missing.pl',
't/053_standby_login_event_trigger.pl',
't/054_unlogged_sequence_promotion.pl',
+ 't/055_rewrite_stale_xmin.pl',
],
},
}
diff --git a/src/test/recovery/t/055_rewrite_stale_xmin.pl b/src/test/recovery/t/055_rewrite_stale_xmin.pl
new file mode 100644
index 000000000000..dad95c0cf967
--- /dev/null
+++ b/src/test/recovery/t/055_rewrite_stale_xmin.pl
@@ -0,0 +1,124 @@
+# Copyright (c) 2025-2026, PostgreSQL Global Development Group
+#
+# Test that heap rewrites (CLUSTER, VACUUM FULL, REPACK) and index builds
+# work in the case when the backend's own xmin is held back by a transaction
+# in another database.
+
+use strict;
+use warnings;
+use PostgreSQL::Test::Cluster;
+use Test::More;
+
+my $node = PostgreSQL::Test::Cluster->new('primary');
+$node->init;
+# No Autovacuum, no random interferences.
+$node->append_conf(
+ 'postgresql.conf', qq[
+autovacuum = off
+]);
+$node->start;
+
+# Create two databases.
+$node->safe_psql('postgres', 'CREATE DATABASE db_holder');
+$node->safe_psql('postgres', 'CREATE DATABASE db_target');
+
+# Set up a table with TOAST data. Returns the toast table name.
+sub setup_table
+{
+ my ($tblname, $extra_ddl) = @_;
+ $extra_ddl //= '';
+
+ $node->safe_psql(
+ 'db_target', qq{
+ DROP TABLE IF EXISTS $tblname;
+ CREATE TABLE $tblname (id int PRIMARY KEY, data text)
+ WITH (autovacuum_enabled = off);
+ ALTER TABLE $tblname ALTER COLUMN data SET STORAGE EXTERNAL;
+ INSERT INTO $tblname VALUES (1, repeat('x', 2500));
+ INSERT INTO $tblname VALUES (2, repeat('z', 2500));
+ $extra_ddl
+ });
+
+ my $toast = $node->safe_psql(
+ 'db_target', qq{
+ SELECT 'pg_toast.' || relname FROM pg_class
+ WHERE oid = (SELECT reltoastrelid FROM pg_class
+ WHERE relname = '$tblname');
+ });
+ chomp $toast;
+ return $toast;
+}
+
+# Create precondition state. Requires that $holder is already running with
+# a write XID.
+sub create_missing_toast_state
+{
+ my ($tblname, $toast_table) = @_;
+
+ # Hold xmin in same DB to prevent main tuple removal.
+ my $xmin_holder = $node->background_psql('db_target', on_error_stop => 1);
+ $xmin_holder->query_safe("BEGIN ISOLATION LEVEL REPEATABLE READ");
+ $xmin_holder->query_safe("SELECT 1");
+
+ # Delete the row with TOAST data.
+ $node->safe_psql('db_target', "DELETE FROM $tblname WHERE id = 1");
+
+ # VACUUM main table only. The xmin_holder keeps the dead tuple.
+ $node->safe_psql('db_target', "VACUUM (PROCESS_TOAST false) $tblname");
+
+ # Release same-DB xmin.
+ $xmin_holder->query_safe("COMMIT");
+ $xmin_holder->quit;
+
+ # Vacuum toast table: toast chunks now DEAD and removed.
+ $node->safe_psql('db_target', "VACUUM $toast_table");
+}
+
+# Open a transaction holding an XID before any deletes. This XID will hold
+# back GetSnapshotData() globally, on a different database than the one
+# running the various rewrite operations.
+my $holder = $node->background_psql('db_holder', on_error_stop => 1);
+$holder->query_safe("BEGIN");
+$holder->query_safe("CREATE TEMP TABLE xid_holder(x int)");
+
+# Test 1: CLUSTER
+my $toast = setup_table('rewrite_test');
+create_missing_toast_state('rewrite_test', $toast);
+
+my ($ret, $stdout, $stderr) =
+ $node->psql('db_target', 'CLUSTER rewrite_test USING rewrite_test_pkey');
+is($ret, 0, "CLUSTER succeeds without missing-chunk error");
+unlike($stderr, qr/missing chunk/, "CLUSTER: no missing-chunk error");
+
+# Test 2: VACUUM FULL
+$toast = setup_table('rewrite_test');
+create_missing_toast_state('rewrite_test', $toast);
+
+($ret, $stdout, $stderr) =
+ $node->psql('db_target', 'VACUUM FULL rewrite_test');
+is($ret, 0, "VACUUM FULL succeeds without missing-chunk error");
+unlike($stderr, qr/missing chunk/, "VACUUM FULL: no missing-chunk error");
+
+# Test 3: REPACK
+$toast = setup_table('rewrite_test');
+create_missing_toast_state('rewrite_test', $toast);
+
+($ret, $stdout, $stderr) = $node->psql('db_target', 'REPACK rewrite_test');
+is($ret, 0, "REPACK succeeds without missing-chunk error");
+unlike($stderr, qr/missing chunk/, "REPACK: no missing-chunk error");
+
+# Test 4: CREATE INDEX on toasted column
+$toast = setup_table('rewrite_test');
+create_missing_toast_state('rewrite_test', $toast);
+
+($ret, $stdout, $stderr) = $node->psql('db_target',
+ 'CREATE INDEX rewrite_test_data_idx ON rewrite_test (data)');
+is($ret, 0, "CREATE INDEX succeeds without missing-chunk error");
+unlike($stderr, qr/missing chunk/, "CREATE INDEX: no missing-chunk error");
+
+# Cleanup.
+$holder->query_safe("COMMIT");
+$holder->quit;
+
+$node->stop;
+done_testing();
diff --git a/contrib/dblink/.gitignore b/contrib/dblink/.gitignore
index 5dcb3ff97235..33bc8d8ffeb3 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 fde0b49ddbbd..a0ba41280813 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 000000000000..2e5a7940ea26
--- /dev/null
+++ b/contrib/dblink/expected/rewrite_stale_xmin.out
@@ -0,0 +1,237 @@
+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_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)
+
diff --git a/contrib/dblink/meson.build b/contrib/dblink/meson.build
index e2489f41229f..86fbd372b880 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 000000000000..fe88e789f854
--- /dev/null
+++ b/contrib/dblink/specs/rewrite_stale_xmin.spec
@@ -0,0 +1,137 @@
+# Test that heap rewrites work when the rewriting backend's own xmin is
+# held back by a transaction in another database.
+
+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_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;
+}
+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);
+}
+
+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
+
+# 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
--
2.55.0
signature.asc (application/pgp-signature, 832B) download
^ permalink raw reply [nested|flat] 33+ messages in thread
* Re: BUG #19519: REPACK can fail due to missing chunk for toast value
@ 2026-07-07 17:10 Srinath Reddy Sadipiralla <srinath2133@gmail.com>
parent: Michael Paquier <michael@paquier.xyz>
0 siblings, 1 reply; 33+ messages in thread
From: Srinath Reddy Sadipiralla @ 2026-07-07 17:10 UTC (permalink / raw)
To: Michael Paquier <michael@paquier.xyz>; +Cc: Matthias van de Meent <boekewurm+postgres@gmail.com>; Imran Zaheer <imran.zhir@gmail.com>; Alexander Lakhin <exclusion@gmail.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>; Konstantin Knizhnik <knizhnik@garret.ru>
Hi,
On Tue, Jul 7, 2026 at 10:52 AM Michael Paquier <michael@paquier.xyz> wrote:
>
> Option 2 leads to a much nicer result overall, with the attached
> passing my regression tests and Alexander's case as well (highly
> concurrent thing sent yesterday). The rest of the patch is kind of
> boring, where I have been trying to get a missing_ok state across the
> stack to let the toast slice fetch bypass the case of missing chunks
> when we are OK with it due to the rewrites. That still feels crude,
> but the simplicity is appealing here, as much as the rather low
> invasiveness.
>
> Thoughts or comments?
With the initial reproducer, I originally thought this bug was driven
entirely
by a long-running query in another database causing a self-inflicted horizon
drag on the rewrite operation. My theory was that the cross-database sleeper
drags down the global xmin, which infects the snapshot held by VACUUM FULL.
During ComputeXidHorizons, VACUUM FULL ends up dragging its own garbage
collection horizon backward. Lazy vacuum avoids this trap because it
utilizes the
PROC_IN_VACUUM flag to ignore its own snapshot.Since we cannot simply apply
PROC_IN_VACUUM to VACUUM FULL (it needs standard MVCC snapshots to
safely evaluate index expressions), and we can't remove it from lazy vacuum
(which would cause bloat), patching the rewrite operation to explicitly
ignore its
own snapshot during GC calculation (excludeMyself) seemed like the correct
fix.
The script proved that OldestXmin can be dragged backward by other
processes,
bypassing the patch entirely.If a completely separate process in the same
database
(such as a simple \d catalog lookup) requests a global snapshot, it gets
"infected" by
the long-running query in the other database. This new query now sits in
the local ProcArray.
Lazy Vacuum runs, ignores the cross-database sleeper, calculates an
aggressive horizon,
and physically removes the TOAST chunks.VACUUM FULL runs, sees the local
carrier
query, and is forced to respect its older snapshot. Its horizon is dragged
backward, it
assumes the main tuples are RECENTLY_DEAD, attempts to copy them, and
crashes
because the TOAST chunks are gone.
so my initial thoughts are that until there's dependency of
OldestXmin calculation on
global snapshot , the rewrite horizon getting dragged back seems
inevitable, so i think
compared to other approaches in the thread ,your approach of ignoring the
fact of
missing chunks seems good. I quickly reviewed the core logic of treating
the missing
chunks as dead and LGTM will further look into this and test.
--
Thanks :)
Srinath Reddy Sadipiralla
EDB: https://www.enterprisedb.com/
^ permalink raw reply [nested|flat] 33+ messages in thread
* Re: BUG #19519: REPACK can fail due to missing chunk for toast value
@ 2026-07-07 22:15 Michael Paquier <michael@paquier.xyz>
parent: Srinath Reddy Sadipiralla <srinath2133@gmail.com>
0 siblings, 1 reply; 33+ messages in thread
From: Michael Paquier @ 2026-07-07 22:15 UTC (permalink / raw)
To: Srinath Reddy Sadipiralla <srinath2133@gmail.com>; +Cc: Matthias van de Meent <boekewurm+postgres@gmail.com>; Imran Zaheer <imran.zhir@gmail.com>; Alexander Lakhin <exclusion@gmail.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>; Konstantin Knizhnik <knizhnik@garret.ru>
On Tue, Jul 07, 2026 at 10:40:12PM +0530, Srinath Reddy Sadipiralla wrote:
> I quickly reviewed the core logic of treating the missing
> chunks as dead and LGTM will further look into this and test.
Thanks for that. This is tricky and invasive enough that this
warrants more eyes.
One thing that I still don't like much in the patch as written is my
use of a missing_ok argument, which feels super confusing as it
applies only to the underlying external TOAST, if the relation has
any. I'd be tempted to rewrite this portion of the patch with a
uint32 flags. Even if we assign one value for now (say MISSING_TOAST,
MISSING_TOAST_OK or whatever), it would allow more flexibility on ABI
grounds if we want more like states in the future across this portion
of the stack. Again, I strongly doubt that we will be able to
backpatch any of that.
--
Michael
Attachments:
signature.asc (application/pgp-signature, 832B) download
^ permalink raw reply [nested|flat] 33+ messages in thread
* Re: BUG #19519: REPACK can fail due to missing chunk for toast value
@ 2026-07-08 01:10 Michael Paquier <michael@paquier.xyz>
parent: Michael Paquier <michael@paquier.xyz>
0 siblings, 1 reply; 33+ messages in thread
From: Michael Paquier @ 2026-07-08 01:10 UTC (permalink / raw)
To: Srinath Reddy Sadipiralla <srinath2133@gmail.com>; +Cc: Matthias van de Meent <boekewurm+postgres@gmail.com>; Imran Zaheer <imran.zhir@gmail.com>; Alexander Lakhin <exclusion@gmail.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>; Konstantin Knizhnik <knizhnik@garret.ru>
On Wed, Jul 08, 2026 at 07:15:16AM +0900, Michael Paquier wrote:
> One thing that I still don't like much in the patch as written is my
> use of a missing_ok argument, which feels super confusing as it
> applies only to the underlying external TOAST, if the relation has
> any. I'd be tempted to rewrite this portion of the patch with a
> uint32 flags. Even if we assign one value for now (say MISSING_TOAST,
> MISSING_TOAST_OK or whatever), it would allow more flexibility on ABI
> grounds if we want more like states in the future across this portion
> of the stack. Again, I strongly doubt that we will be able to
> backpatch any of that.
A couple of extra notes while I do not forget about that stuff.. The
patch may be better split into two if we go with this approach, as the
index build and rewrite paths require different solutions:
- One for the rewrite path. It makes little sense to do any kind of
aggressive early detoasting because it may be wasteful due to the
tuple rewrites that update their data with only copies by reference
(main relation tuple is rewritten, reuses the same external TOAST
tuple). For workloads where UPDATEs do not touch the TOASTed
attributes, that would be a waste.
- One for the index build path, which is actually too aggressive with
its early detoasting, now that I think about it. There should be no
need to perform a detoast for anything else than the attributes that
are used in the index definition or the attributes that are used in
index expressions. So as written this patch would lead to a
regression.
--
Michael
Attachments:
signature.asc (application/pgp-signature, 832B) download
^ permalink raw reply [nested|flat] 33+ messages in thread
* Re: BUG #19519: REPACK can fail due to missing chunk for toast value
@ 2026-07-08 12:00 Heikki Linnakangas <hlinnaka@iki.fi>
parent: Michael Paquier <michael@paquier.xyz>
0 siblings, 3 replies; 33+ messages in thread
From: Heikki Linnakangas @ 2026-07-08 12:00 UTC (permalink / raw)
To: Michael Paquier <michael@paquier.xyz>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; +Cc: Matthias van de Meent <boekewurm+postgres@gmail.com>; Imran Zaheer <imran.zhir@gmail.com>; Alexander Lakhin <exclusion@gmail.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>; Konstantin Knizhnik <knizhnik@garret.ru>
On 08/07/2026 04:10, Michael Paquier wrote:
> On Wed, Jul 08, 2026 at 07:15:16AM +0900, Michael Paquier wrote:
>> One thing that I still don't like much in the patch as written is my
>> use of a missing_ok argument, which feels super confusing as it
>> applies only to the underlying external TOAST, if the relation has
>> any. I'd be tempted to rewrite this portion of the patch with a
>> uint32 flags. Even if we assign one value for now (say MISSING_TOAST,
>> MISSING_TOAST_OK or whatever), it would allow more flexibility on ABI
>> grounds if we want more like states in the future across this portion
>> of the stack. Again, I strongly doubt that we will be able to
>> backpatch any of that.
Yeah, boolean arguments in general can be confusing. Especially
arguments like "missing_ok" where it's hard to remember which behavior
is true and which is false. An IDE that shows the name of the argument
helps, but having the caller say "MISSING_TOAST_OK" rather than "true"
is much clearer.
For backpatching, I think we could smuggle the flag in a global
variable, to avoid changing the signature of the
relation_fetch_toast_slice() callback. See attached patch 0002 on top of
your 0001 patch (which is also attached for completeness). It doesn't
fix the problem for hypothetical 3rd party tableam implementations that
implement their own relation_fetch_toast_slice() callback. But do such
extensions even exist? If yes, they could be fixed too by also checking
the global variable.
I thought about adding an extra "extended" callback next to
relation_fetch_toast_slice(), but I don't see a way to add functions to
TableAmRoutine in an ABI-compatible way. For the future, we might want
to store sizeof(TableAmRoutine) in the struct itself, so that we could
add fields to it in minor versions without breaking the API, in case we
need something like this again.
> A couple of extra notes while I do not forget about that stuff.. The
> patch may be better split into two if we go with this approach, as the
> index build and rewrite paths require different solutions:
> - One for the rewrite path. It makes little sense to do any kind of
> aggressive early detoasting because it may be wasteful due to the
> tuple rewrites that update their data with only copies by reference
> (main relation tuple is rewritten, reuses the same external TOAST
> tuple). For workloads where UPDATEs do not touch the TOASTed
> attributes, that would be a waste.
I didn't understand this part. Do you mean when rebuilding the indexes
after rewriting the heap? I didn't think we support storing toasted
external datums in an index at all.
> - One for the index build path, which is actually too aggressive with
> its early detoasting, now that I think about it. There should be no
> need to perform a detoast for anything else than the attributes that
> are used in the index definition or the attributes that are used in
> index expressions. So as written this patch would lead to a
> regression.
Yeah, although I wouldn't be too worried about the performance here. The
penalty would be when building an index on values that are large enough
to be toasted, with lots of RECENTLY_DEAD tuples. That doesn't seem like
a very common case.
- Heikki
Attachments: download all (2 files, .tar.gz)
v3-0001-Fix-missing-chunk-errors-during-heap-rewrites-and.patch (text/x-patch, 36.6K) download
From 2e9cc62deda3de859ee389772471734a2f4f9e5d Mon Sep 17 00:00:00 2001
From: Michael Paquier <michael@paquier.xyz>
Date: Tue, 7 Jul 2026 14:20:30 +0900
Subject: [PATCH v3] Fix "missing chunk" errors during heap rewrites and index
builds
Blah, blah.
This problem has been reported recently by Alexander for REPACK, but it
is a much older issue (tested down to 9.5 for curiosity's sake, but I
suspect that it is much older than that).
XXX: This patch includes both TAP and isolation tests. We should remove
one pattern at the end.
Reported-by: Alexander Lakhin <exclusion@gmail.com>
Discussion: https://postgr.es/m/18351-f6e06364b3a2e669@postgresql.org
Discussion: https://postgr.es/m/19519-fe02d8ff679d834d@postgresql.org
---
src/include/access/detoast.h | 9 +
src/include/access/heaptoast.h | 13 +-
src/include/access/rewriteheap.h | 4 +-
src/include/access/tableam.h | 24 +-
src/include/access/toast_helper.h | 2 +-
src/backend/access/common/detoast.c | 41 ++-
src/backend/access/heap/heapam.c | 4 +-
src/backend/access/heap/heapam_handler.c | 94 ++++++-
src/backend/access/heap/heaptoast.c | 22 +-
src/backend/access/heap/rewriteheap.c | 31 ++-
src/backend/access/table/toast_helper.c | 17 +-
src/test/recovery/meson.build | 1 +
src/test/recovery/t/055_rewrite_stale_xmin.pl | 124 +++++++++
contrib/dblink/.gitignore | 2 +
contrib/dblink/Makefile | 2 +
.../dblink/expected/rewrite_stale_xmin.out | 237 ++++++++++++++++++
contrib/dblink/meson.build | 5 +
contrib/dblink/specs/rewrite_stale_xmin.spec | 137 ++++++++++
18 files changed, 718 insertions(+), 51 deletions(-)
create mode 100644 src/test/recovery/t/055_rewrite_stale_xmin.pl
create mode 100644 contrib/dblink/expected/rewrite_stale_xmin.out
create mode 100644 contrib/dblink/specs/rewrite_stale_xmin.spec
diff --git a/src/include/access/detoast.h b/src/include/access/detoast.h
index fbd98181a3a1..c5eeed04b011 100644
--- a/src/include/access/detoast.h
+++ b/src/include/access/detoast.h
@@ -43,6 +43,15 @@ do { \
*/
extern varlena *detoast_external_attr(varlena *attr);
+/* ----------
+ * detoast_external_attr_extended() -
+ *
+ * Like detoast_external_attr, but returns NULL if toast chunks
+ * are missing (instead of raising an error).
+ * ----------
+ */
+extern varlena *detoast_external_attr_extended(varlena *attr);
+
/* ----------
* detoast_attr() -
*
diff --git a/src/include/access/heaptoast.h b/src/include/access/heaptoast.h
index 631cb1836b96..1be85db6ddd2 100644
--- a/src/include/access/heaptoast.h
+++ b/src/include/access/heaptoast.h
@@ -92,10 +92,14 @@
* heap_toast_insert_or_update -
*
* Called by heap_insert() and heap_update().
+ *
+ * If missing_ok is true, returns NULL when failing to fetch external
+ * TOAST data, instead of throwing an error.
* ----------
*/
extern HeapTuple heap_toast_insert_or_update(Relation rel, HeapTuple newtup,
- HeapTuple oldtup, uint32 options);
+ HeapTuple oldtup, uint32 options,
+ bool missing_ok);
/* ----------
* heap_toast_delete -
@@ -140,10 +144,13 @@ extern HeapTuple toast_build_flattened_tuple(TupleDesc tupleDesc,
* heap_fetch_toast_slice
*
* Fetch a slice from a toast value stored in a heap table.
+ * If missing_ok is true, returns false when chunks are missing
+ * instead of raising an error. Returns true on success.
* ----------
*/
-extern void heap_fetch_toast_slice(Relation toastrel, Oid valueid,
+extern bool heap_fetch_toast_slice(Relation toastrel, Oid valueid,
int32 attrsize, int32 sliceoffset,
- int32 slicelength, varlena *result);
+ int32 slicelength, varlena *result,
+ bool missing_ok);
#endif /* HEAPTOAST_H */
diff --git a/src/include/access/rewriteheap.h b/src/include/access/rewriteheap.h
index 6ccf7b45c04e..df4fa4fde710 100644
--- a/src/include/access/rewriteheap.h
+++ b/src/include/access/rewriteheap.h
@@ -25,8 +25,8 @@ extern RewriteState begin_heap_rewrite(Relation old_heap, Relation new_heap,
TransactionId oldest_xmin, TransactionId freeze_xid,
MultiXactId cutoff_multi);
extern void end_heap_rewrite(RewriteState state);
-extern void rewrite_heap_tuple(RewriteState state, HeapTuple old_tuple,
- HeapTuple new_tuple);
+extern bool rewrite_heap_tuple(RewriteState state, HeapTuple old_tuple,
+ HeapTuple new_tuple, bool missing_ok);
extern bool rewrite_heap_dead_tuple(RewriteState state, HeapTuple old_tuple);
/*
diff --git a/src/include/access/tableam.h b/src/include/access/tableam.h
index f2c36696bcad..a90b15dd82b3 100644
--- a/src/include/access/tableam.h
+++ b/src/include/access/tableam.h
@@ -782,12 +782,16 @@ typedef struct TableAmRoutine
* This callback is invoked when detoasting a value stored in a toast
* table implemented by this AM. See table_relation_fetch_toast_slice()
* for more details.
+ *
+ * If missing_ok is true, returns false when chunks are missing instead of
+ * raising an error. Returns true on success.
*/
- void (*relation_fetch_toast_slice) (Relation toastrel, Oid valueid,
+ bool (*relation_fetch_toast_slice) (Relation toastrel, Oid valueid,
int32 attrsize,
int32 sliceoffset,
int32 slicelength,
- varlena *result);
+ varlena *result,
+ bool missing_ok);
/* ------------------------------------------------------------------------
@@ -1981,16 +1985,20 @@ table_relation_toast_am(Relation rel)
*
* result is caller-allocated space into which the fetched bytes should be
* stored.
+ *
+ * missing_ok: if true, return false when toast chunks are missing instead
+ * of raising an error. Returns true on success.
*/
-static inline void
+static inline bool
table_relation_fetch_toast_slice(Relation toastrel, Oid valueid,
int32 attrsize, int32 sliceoffset,
- int32 slicelength, varlena *result)
+ int32 slicelength, varlena *result,
+ bool missing_ok)
{
- toastrel->rd_tableam->relation_fetch_toast_slice(toastrel, valueid,
- attrsize,
- sliceoffset, slicelength,
- result);
+ return toastrel->rd_tableam->relation_fetch_toast_slice(toastrel, valueid,
+ attrsize,
+ sliceoffset, slicelength,
+ result, missing_ok);
}
diff --git a/src/include/access/toast_helper.h b/src/include/access/toast_helper.h
index 2ec92397f267..e548ba5596b4 100644
--- a/src/include/access/toast_helper.h
+++ b/src/include/access/toast_helper.h
@@ -101,7 +101,7 @@ typedef struct
#define TOASTCOL_IGNORE 0x0010
#define TOASTCOL_INCOMPRESSIBLE 0x0020
-extern void toast_tuple_init(ToastTupleContext *ttc);
+extern bool toast_tuple_init(ToastTupleContext *ttc, bool missing_ok);
extern int toast_tuple_find_biggest_attribute(ToastTupleContext *ttc,
bool for_compression,
bool check_main);
diff --git a/src/backend/access/common/detoast.c b/src/backend/access/common/detoast.c
index a6c1f3a734b2..c16b61a1cb1c 100644
--- a/src/backend/access/common/detoast.c
+++ b/src/backend/access/common/detoast.c
@@ -22,7 +22,7 @@
#include "utils/expandeddatum.h"
#include "utils/rel.h"
-static varlena *toast_fetch_datum(varlena *attr);
+static varlena *toast_fetch_datum(varlena *attr, bool missing_ok);
static varlena *toast_fetch_datum_slice(varlena *attr,
int32 sliceoffset,
int32 slicelength);
@@ -51,7 +51,7 @@ detoast_external_attr(varlena *attr)
/*
* This is an external stored plain value
*/
- result = toast_fetch_datum(attr);
+ result = toast_fetch_datum(attr, false);
}
else if (VARATT_IS_EXTERNAL_INDIRECT(attr))
{
@@ -102,6 +102,23 @@ detoast_external_attr(varlena *attr)
}
+/* ----------
+ * detoast_external_attr_extended -
+ *
+ * Like detoast_external_attr, but returns NULL if toast chunks are
+ * missing for external pointers.
+ * ----------
+ */
+varlena *
+detoast_external_attr_extended(varlena *attr)
+{
+ if (VARATT_IS_EXTERNAL_ONDISK(attr))
+ return toast_fetch_datum(attr, true);
+ else
+ return detoast_external_attr(attr);
+}
+
+
/* ----------
* detoast_attr -
*
@@ -120,7 +137,7 @@ detoast_attr(varlena *attr)
/*
* This is an externally stored datum --- fetch it back from there
*/
- attr = toast_fetch_datum(attr);
+ attr = toast_fetch_datum(attr, false);
/* If it's compressed, decompress it */
if (VARATT_IS_COMPRESSED(attr))
{
@@ -262,7 +279,7 @@ detoast_attr_slice(varlena *attr,
preslice = toast_fetch_datum_slice(attr, 0, max_size);
}
else
- preslice = toast_fetch_datum(attr);
+ preslice = toast_fetch_datum(attr, false);
}
else if (VARATT_IS_EXTERNAL_INDIRECT(attr))
{
@@ -337,10 +354,12 @@ detoast_attr_slice(varlena *attr,
*
* Reconstruct an in memory Datum from the chunks saved
* in the toast relation
+ *
+ * If missing_ok is true, returns NULL when chunks are missing.
* ----------
*/
static varlena *
-toast_fetch_datum(varlena *attr)
+toast_fetch_datum(varlena *attr, bool missing_ok)
{
Relation toastrel;
varlena *result;
@@ -372,8 +391,14 @@ toast_fetch_datum(varlena *attr)
toastrel = table_open(toast_pointer.va_toastrelid, AccessShareLock);
/* Fetch all chunks */
- table_relation_fetch_toast_slice(toastrel, toast_pointer.va_valueid,
- attrsize, 0, attrsize, result);
+ if (!table_relation_fetch_toast_slice(toastrel, toast_pointer.va_valueid,
+ attrsize, 0, attrsize, result,
+ missing_ok))
+ {
+ pfree(result);
+ table_close(toastrel, AccessShareLock);
+ return NULL;
+ }
/* Close toast table */
table_close(toastrel, AccessShareLock);
@@ -454,7 +479,7 @@ toast_fetch_datum_slice(varlena *attr, int32 sliceoffset,
/* Fetch all chunks */
table_relation_fetch_toast_slice(toastrel, toast_pointer.va_valueid,
attrsize, sliceoffset, slicelength,
- result);
+ result, false);
/* Close toast table */
table_close(toastrel, AccessShareLock);
diff --git a/src/backend/access/heap/heapam.c b/src/backend/access/heap/heapam.c
index abfd8e8970a6..1d4018931200 100644
--- a/src/backend/access/heap/heapam.c
+++ b/src/backend/access/heap/heapam.c
@@ -2236,7 +2236,7 @@ heap_prepare_insert(Relation relation, HeapTuple tup, TransactionId xid,
return tup;
}
else if (HeapTupleHasExternal(tup) || tup->t_len > TOAST_TUPLE_THRESHOLD)
- return heap_toast_insert_or_update(relation, tup, NULL, options);
+ return heap_toast_insert_or_update(relation, tup, NULL, options, false);
else
return tup;
}
@@ -3871,7 +3871,7 @@ l2:
if (need_toast)
{
/* Note we always use WAL and FSM during updates */
- heaptup = heap_toast_insert_or_update(relation, newtup, &oldtup, 0);
+ heaptup = heap_toast_insert_or_update(relation, newtup, &oldtup, 0, false);
newtupsize = MAXALIGN(heaptup->t_len);
}
else
diff --git a/src/backend/access/heap/heapam_handler.c b/src/backend/access/heap/heapam_handler.c
index 2268cc277bce..2cd9d0f4aeb9 100644
--- a/src/backend/access/heap/heapam_handler.c
+++ b/src/backend/access/heap/heapam_handler.c
@@ -19,6 +19,7 @@
*/
#include "postgres.h"
+#include "access/detoast.h"
#include "access/genam.h"
#include "access/heapam.h"
#include "access/heaptoast.h"
@@ -48,9 +49,10 @@
#include "utils/rel.h"
#include "utils/tuplesort.h"
-static void reform_and_rewrite_tuple(HeapTuple tuple,
+static bool reform_and_rewrite_tuple(HeapTuple tuple,
Relation OldHeap, Relation NewHeap,
- Datum *values, bool *isnull, RewriteState rwstate);
+ Datum *values, bool *isnull, RewriteState rwstate,
+ bool missing_ok);
static void heap_insert_for_repack(HeapTuple tuple, Relation OldHeap,
Relation NewHeap, Datum *values, bool *isnull,
BulkInsertState bistate);
@@ -717,6 +719,7 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,
HeapTuple tuple;
Buffer buf;
bool isdead;
+ bool recently_dead = false;
CHECK_FOR_INTERRUPTS();
@@ -802,6 +805,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 */
@@ -835,6 +839,7 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,
RelationGetRelationName(OldHeap));
/* treat as recently dead */
*tups_recently_dead += 1;
+ recently_dead = true;
isdead = false;
break;
default:
@@ -881,8 +886,22 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,
int64 ct_val[2];
if (!concurrent)
- reform_and_rewrite_tuple(tuple, OldHeap, NewHeap,
- values, isnull, rwstate);
+ {
+ if (!reform_and_rewrite_tuple(tuple, OldHeap, NewHeap,
+ values, isnull, rwstate,
+ recently_dead))
+ {
+ /*
+ * Missing TOAST chunks for a recently-dead tuple. Treat
+ * it as dead.
+ */
+ *tups_vacuumed += 1;
+ *num_tuples -= 1;
+ if (recently_dead)
+ *tups_recently_dead -= 1;
+ continue;
+ }
+ }
else
heap_insert_for_repack(tuple, OldHeap, NewHeap,
values, isnull, bistate);
@@ -934,10 +953,17 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,
n_tuples += 1;
if (!concurrent)
- reform_and_rewrite_tuple(tuple,
- OldHeap, NewHeap,
- values, isnull,
- rwstate);
+ {
+ if (!reform_and_rewrite_tuple(tuple,
+ OldHeap, NewHeap,
+ values, isnull,
+ rwstate, true))
+ {
+ /* TOAST gone for a recently dead tuple */
+ n_tuples -= 1;
+ continue;
+ }
+ }
else
heap_insert_for_repack(tuple, OldHeap, NewHeap,
values, isnull, bistate);
@@ -1613,6 +1639,43 @@ heapam_index_build_range_scan(Relation heapRelation,
continue;
}
+ /*
+ * For RECENTLY_DEAD tuples, pre-detoast external TOAST values. We do
+ * this to detect for missing chunks at later stages, feeding inline
+ * data to the downstream access method code.
+ */
+ if (!tupleIsAlive)
+ {
+ TupleDesc tdesc = RelationGetDescr(heapRelation);
+ bool skip = false;
+
+ slot_getallattrs(slot);
+ for (int i = 0; i < tdesc->natts; i++)
+ {
+ Form_pg_attribute att = TupleDescAttr(tdesc, i);
+
+ if (att->attlen != -1 || att->attisdropped)
+ continue;
+ if (slot->tts_isnull[i])
+ continue;
+ if (VARATT_IS_EXTERNAL_ONDISK(DatumGetPointer(slot->tts_values[i])))
+ {
+ varlena *detoasted;
+
+ detoasted = detoast_external_attr_extended(
+ (varlena *) DatumGetPointer(slot->tts_values[i]));
+ if (detoasted == NULL)
+ {
+ skip = true;
+ break;
+ }
+ slot->tts_values[i] = PointerGetDatum(detoasted);
+ }
+ }
+ if (skip)
+ continue;
+ }
+
/*
* For the current heap tuple, extract all the attributes we use in
* this index, and note which are null. This also performs evaluation
@@ -2347,20 +2410,29 @@ heapam_scan_sample_next_tuple(TableScanDesc scan, SampleScanState *scanstate,
* SET WITHOUT OIDS.
*
* So, we must reconstruct the tuple from component Datums.
+ *
+ * Returns true on success, and false on failure if missing_ok is
+ * true.
*/
-static void
+static bool
reform_and_rewrite_tuple(HeapTuple tuple,
Relation OldHeap, Relation NewHeap,
- Datum *values, bool *isnull, RewriteState rwstate)
+ Datum *values, bool *isnull, RewriteState rwstate,
+ bool missing_ok)
{
HeapTuple newtuple;
newtuple = reform_tuple(tuple, OldHeap, NewHeap, values, isnull);
/* The heap rewrite module does the rest */
- rewrite_heap_tuple(rwstate, tuple, newtuple);
+ if (!rewrite_heap_tuple(rwstate, tuple, newtuple, missing_ok))
+ {
+ heap_freetuple(newtuple);
+ return false;
+ }
heap_freetuple(newtuple);
+ return true;
}
/*
diff --git a/src/backend/access/heap/heaptoast.c b/src/backend/access/heap/heaptoast.c
index 03f885a25b07..38896a0c7492 100644
--- a/src/backend/access/heap/heaptoast.c
+++ b/src/backend/access/heap/heaptoast.c
@@ -94,7 +94,7 @@ heap_toast_delete(Relation rel, HeapTuple oldtup, bool is_speculative)
*/
HeapTuple
heap_toast_insert_or_update(Relation rel, HeapTuple newtup, HeapTuple oldtup,
- uint32 options)
+ uint32 options, bool missing_ok)
{
HeapTuple result_tuple;
TupleDesc tupleDesc;
@@ -154,7 +154,8 @@ heap_toast_insert_or_update(Relation rel, HeapTuple newtup, HeapTuple oldtup,
ttc.ttc_oldisnull = toast_oldisnull;
}
ttc.ttc_attr = toast_attr;
- toast_tuple_init(&ttc);
+ if (!toast_tuple_init(&ttc, missing_ok))
+ return NULL;
/* ----------
* Compress and/or save external until data fits into target length
@@ -621,11 +622,14 @@ toast_build_flattened_tuple(TupleDesc tupleDesc,
* sliceoffset is the byte offset within the TOAST value from which to fetch.
* slicelength is the number of bytes to be fetched from the TOAST value.
* result is the varlena into which the results should be written.
+ * missing_ok if true, return false on missing chunks instead of error.
+ *
+ * Returns true on success, false if missing_ok and chunks are missing.
*/
-void
+bool
heap_fetch_toast_slice(Relation toastrel, Oid valueid, int32 attrsize,
int32 sliceoffset, int32 slicelength,
- varlena *result)
+ varlena *result, bool missing_ok)
{
Relation *toastidxs;
ScanKeyData toastkey[3];
@@ -779,13 +783,23 @@ heap_fetch_toast_slice(Relation toastrel, Oid valueid, int32 attrsize,
* Final checks that we successfully fetched the datum
*/
if (expectedchunk != (endchunk + 1))
+ {
+ if (missing_ok)
+ {
+ systable_endscan_ordered(toastscan);
+ toast_close_indexes(toastidxs, num_indexes, AccessShareLock);
+ return false;
+ }
ereport(ERROR,
(errcode(ERRCODE_DATA_CORRUPTED),
errmsg_internal("missing chunk number %d for toast value %u in %s",
expectedchunk, valueid,
RelationGetRelationName(toastrel))));
+ }
/* End scan and close indexes. */
systable_endscan_ordered(toastscan);
toast_close_indexes(toastidxs, num_indexes, AccessShareLock);
+
+ return true;
}
diff --git a/src/backend/access/heap/rewriteheap.c b/src/backend/access/heap/rewriteheap.c
index 5a5398a76ae7..fbb6e6ca1f94 100644
--- a/src/backend/access/heap/rewriteheap.c
+++ b/src/backend/access/heap/rewriteheap.c
@@ -211,7 +211,8 @@ typedef struct RewriteMappingDataEntry
/* prototypes for internal functions */
-static void raw_heap_insert(RewriteState state, HeapTuple tup);
+static bool raw_heap_insert(RewriteState state, HeapTuple tup,
+ bool missing_ok);
/* internal logical remapping prototypes */
static void logical_begin_heap_rewrite(RewriteState state);
@@ -309,7 +310,7 @@ end_heap_rewrite(RewriteState state)
while ((unresolved = hash_seq_search(&seq_status)) != NULL)
{
ItemPointerSetInvalid(&unresolved->tuple->t_data->t_ctid);
- raw_heap_insert(state, unresolved->tuple);
+ raw_heap_insert(state, unresolved->tuple, false);
}
/* Write the last page, if any */
@@ -338,9 +339,10 @@ end_heap_rewrite(RewriteState state)
* old_tuple original tuple in the old heap
* new_tuple new, rewritten tuple to be inserted to new heap
*/
-void
+bool
rewrite_heap_tuple(RewriteState state,
- HeapTuple old_tuple, HeapTuple new_tuple)
+ HeapTuple old_tuple, HeapTuple new_tuple,
+ bool missing_ok)
{
MemoryContext old_cxt;
ItemPointerData old_tid;
@@ -437,7 +439,7 @@ rewrite_heap_tuple(RewriteState state,
* tuple will be written.
*/
MemoryContextSwitchTo(old_cxt);
- return;
+ return true;
}
}
@@ -455,7 +457,13 @@ rewrite_heap_tuple(RewriteState state,
ItemPointerData new_tid;
/* Insert the tuple and find out where it's put in new_heap */
- raw_heap_insert(state, new_tuple);
+ if (!raw_heap_insert(state, new_tuple, missing_ok))
+ {
+ if (free_new)
+ heap_freetuple(new_tuple);
+ MemoryContextSwitchTo(old_cxt);
+ return false;
+ }
new_tid = new_tuple->t_self;
logical_rewrite_heap_tuple(state, old_tid, new_tuple);
@@ -532,6 +540,7 @@ rewrite_heap_tuple(RewriteState state,
}
MemoryContextSwitchTo(old_cxt);
+ return true;
}
/*
@@ -593,8 +602,8 @@ rewrite_heap_dead_tuple(RewriteState state, HeapTuple old_tuple)
* tuple is invalid on entry, it's replaced with the new TID as well (in
* the inserted data only, not in the caller's copy).
*/
-static void
-raw_heap_insert(RewriteState state, HeapTuple tup)
+static bool
+raw_heap_insert(RewriteState state, HeapTuple tup, bool missing_ok)
{
Page page;
Size pageFreeSpace,
@@ -628,7 +637,9 @@ raw_heap_insert(RewriteState state, HeapTuple tup)
options |= HEAP_INSERT_NO_LOGICAL;
heaptup = heap_toast_insert_or_update(state->rs_new_rel, tup, NULL,
- options);
+ options, missing_ok);
+ if (heaptup == NULL)
+ return false;
}
else
heaptup = tup;
@@ -702,6 +713,8 @@ raw_heap_insert(RewriteState state, HeapTuple tup)
/* If heaptup is a private copy, release it. */
if (heaptup != tup)
heap_freetuple(heaptup);
+
+ return true;
}
/* ------------------------------------------------------------------------
diff --git a/src/backend/access/table/toast_helper.c b/src/backend/access/table/toast_helper.c
index 2f2022d99510..7e98c01a5eee 100644
--- a/src/backend/access/table/toast_helper.c
+++ b/src/backend/access/table/toast_helper.c
@@ -36,9 +36,12 @@
* toast_flags is just a single uint8, but toast_attr is a caller-provided
* array with a length equal to tupleDesc->natts. The caller need not
* perform any initialization of the array before calling this function.
+ *
+ * If missing_ok is true and an external TOAST value cannot be fetched,
+ * returns false. Returns true on success.
*/
-void
-toast_tuple_init(ToastTupleContext *ttc)
+bool
+toast_tuple_init(ToastTupleContext *ttc, bool missing_ok)
{
TupleDesc tupleDesc = ttc->ttc_rel->rd_att;
int numAttrs = tupleDesc->natts;
@@ -137,7 +140,13 @@ toast_tuple_init(ToastTupleContext *ttc)
if (VARATT_IS_EXTERNAL(new_value))
{
ttc->ttc_attr[i].tai_oldexternal = new_value;
- if (att->attstorage == TYPSTORAGE_PLAIN)
+ if (missing_ok && VARATT_IS_EXTERNAL_ONDISK(new_value))
+ {
+ new_value = detoast_external_attr_extended(new_value);
+ if (new_value == NULL)
+ return false;
+ }
+ else if (att->attstorage == TYPSTORAGE_PLAIN)
new_value = detoast_attr(new_value);
else
new_value = detoast_external_attr(new_value);
@@ -159,6 +168,8 @@ toast_tuple_init(ToastTupleContext *ttc)
ttc->ttc_attr[i].tai_colflags |= TOASTCOL_IGNORE;
}
}
+
+ return true;
}
/*
diff --git a/src/test/recovery/meson.build b/src/test/recovery/meson.build
index ad0d85f41897..7e583ee39a10 100644
--- a/src/test/recovery/meson.build
+++ b/src/test/recovery/meson.build
@@ -63,6 +63,7 @@ tests += {
't/052_checkpoint_segment_missing.pl',
't/053_standby_login_event_trigger.pl',
't/054_unlogged_sequence_promotion.pl',
+ 't/055_rewrite_stale_xmin.pl',
],
},
}
diff --git a/src/test/recovery/t/055_rewrite_stale_xmin.pl b/src/test/recovery/t/055_rewrite_stale_xmin.pl
new file mode 100644
index 000000000000..dad95c0cf967
--- /dev/null
+++ b/src/test/recovery/t/055_rewrite_stale_xmin.pl
@@ -0,0 +1,124 @@
+# Copyright (c) 2025-2026, PostgreSQL Global Development Group
+#
+# Test that heap rewrites (CLUSTER, VACUUM FULL, REPACK) and index builds
+# work in the case when the backend's own xmin is held back by a transaction
+# in another database.
+
+use strict;
+use warnings;
+use PostgreSQL::Test::Cluster;
+use Test::More;
+
+my $node = PostgreSQL::Test::Cluster->new('primary');
+$node->init;
+# No Autovacuum, no random interferences.
+$node->append_conf(
+ 'postgresql.conf', qq[
+autovacuum = off
+]);
+$node->start;
+
+# Create two databases.
+$node->safe_psql('postgres', 'CREATE DATABASE db_holder');
+$node->safe_psql('postgres', 'CREATE DATABASE db_target');
+
+# Set up a table with TOAST data. Returns the toast table name.
+sub setup_table
+{
+ my ($tblname, $extra_ddl) = @_;
+ $extra_ddl //= '';
+
+ $node->safe_psql(
+ 'db_target', qq{
+ DROP TABLE IF EXISTS $tblname;
+ CREATE TABLE $tblname (id int PRIMARY KEY, data text)
+ WITH (autovacuum_enabled = off);
+ ALTER TABLE $tblname ALTER COLUMN data SET STORAGE EXTERNAL;
+ INSERT INTO $tblname VALUES (1, repeat('x', 2500));
+ INSERT INTO $tblname VALUES (2, repeat('z', 2500));
+ $extra_ddl
+ });
+
+ my $toast = $node->safe_psql(
+ 'db_target', qq{
+ SELECT 'pg_toast.' || relname FROM pg_class
+ WHERE oid = (SELECT reltoastrelid FROM pg_class
+ WHERE relname = '$tblname');
+ });
+ chomp $toast;
+ return $toast;
+}
+
+# Create precondition state. Requires that $holder is already running with
+# a write XID.
+sub create_missing_toast_state
+{
+ my ($tblname, $toast_table) = @_;
+
+ # Hold xmin in same DB to prevent main tuple removal.
+ my $xmin_holder = $node->background_psql('db_target', on_error_stop => 1);
+ $xmin_holder->query_safe("BEGIN ISOLATION LEVEL REPEATABLE READ");
+ $xmin_holder->query_safe("SELECT 1");
+
+ # Delete the row with TOAST data.
+ $node->safe_psql('db_target', "DELETE FROM $tblname WHERE id = 1");
+
+ # VACUUM main table only. The xmin_holder keeps the dead tuple.
+ $node->safe_psql('db_target', "VACUUM (PROCESS_TOAST false) $tblname");
+
+ # Release same-DB xmin.
+ $xmin_holder->query_safe("COMMIT");
+ $xmin_holder->quit;
+
+ # Vacuum toast table: toast chunks now DEAD and removed.
+ $node->safe_psql('db_target', "VACUUM $toast_table");
+}
+
+# Open a transaction holding an XID before any deletes. This XID will hold
+# back GetSnapshotData() globally, on a different database than the one
+# running the various rewrite operations.
+my $holder = $node->background_psql('db_holder', on_error_stop => 1);
+$holder->query_safe("BEGIN");
+$holder->query_safe("CREATE TEMP TABLE xid_holder(x int)");
+
+# Test 1: CLUSTER
+my $toast = setup_table('rewrite_test');
+create_missing_toast_state('rewrite_test', $toast);
+
+my ($ret, $stdout, $stderr) =
+ $node->psql('db_target', 'CLUSTER rewrite_test USING rewrite_test_pkey');
+is($ret, 0, "CLUSTER succeeds without missing-chunk error");
+unlike($stderr, qr/missing chunk/, "CLUSTER: no missing-chunk error");
+
+# Test 2: VACUUM FULL
+$toast = setup_table('rewrite_test');
+create_missing_toast_state('rewrite_test', $toast);
+
+($ret, $stdout, $stderr) =
+ $node->psql('db_target', 'VACUUM FULL rewrite_test');
+is($ret, 0, "VACUUM FULL succeeds without missing-chunk error");
+unlike($stderr, qr/missing chunk/, "VACUUM FULL: no missing-chunk error");
+
+# Test 3: REPACK
+$toast = setup_table('rewrite_test');
+create_missing_toast_state('rewrite_test', $toast);
+
+($ret, $stdout, $stderr) = $node->psql('db_target', 'REPACK rewrite_test');
+is($ret, 0, "REPACK succeeds without missing-chunk error");
+unlike($stderr, qr/missing chunk/, "REPACK: no missing-chunk error");
+
+# Test 4: CREATE INDEX on toasted column
+$toast = setup_table('rewrite_test');
+create_missing_toast_state('rewrite_test', $toast);
+
+($ret, $stdout, $stderr) = $node->psql('db_target',
+ 'CREATE INDEX rewrite_test_data_idx ON rewrite_test (data)');
+is($ret, 0, "CREATE INDEX succeeds without missing-chunk error");
+unlike($stderr, qr/missing chunk/, "CREATE INDEX: no missing-chunk error");
+
+# Cleanup.
+$holder->query_safe("COMMIT");
+$holder->quit;
+
+$node->stop;
+done_testing();
diff --git a/contrib/dblink/.gitignore b/contrib/dblink/.gitignore
index 5dcb3ff97235..33bc8d8ffeb3 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 fde0b49ddbbd..a0ba41280813 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 000000000000..2e5a7940ea26
--- /dev/null
+++ b/contrib/dblink/expected/rewrite_stale_xmin.out
@@ -0,0 +1,237 @@
+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_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)
+
diff --git a/contrib/dblink/meson.build b/contrib/dblink/meson.build
index e2489f41229f..86fbd372b880 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 000000000000..fe88e789f854
--- /dev/null
+++ b/contrib/dblink/specs/rewrite_stale_xmin.spec
@@ -0,0 +1,137 @@
+# Test that heap rewrites work when the rewriting backend's own xmin is
+# held back by a transaction in another database.
+
+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_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;
+}
+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);
+}
+
+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
+
+# 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
--
2.55.0
v3-0002-Smuggle-the-missing_ok-arg-in-a-global-var-for-ba.patch (text/x-patch, 5.7K) download
From ae8419d0a166372789cd94acc0b9c8a8d9c864cf Mon Sep 17 00:00:00 2001
From: Heikki Linnakangas <heikki.linnakangas@iki.fi>
Date: Wed, 8 Jul 2026 12:36:48 +0300
Subject: [PATCH v3 2/2] Smuggle the 'missing_ok' arg in a global var, for
backpatching
---
src/backend/access/heap/heaptoast.c | 21 ++++++++++++++++---
src/backend/access/table/tableam.c | 4 ++++
src/include/access/heaptoast.h | 15 +++++++++++---
src/include/access/tableam.h | 31 ++++++++++++++++++++---------
4 files changed, 56 insertions(+), 15 deletions(-)
diff --git a/src/backend/access/heap/heaptoast.c b/src/backend/access/heap/heaptoast.c
index 38896a0c749..7ab54225059 100644
--- a/src/backend/access/heap/heaptoast.c
+++ b/src/backend/access/heap/heaptoast.c
@@ -613,6 +613,21 @@ toast_build_flattened_tuple(TupleDesc tupleDesc,
return new_tuple;
}
+/*
+ * Adapter for the old API in backbranches, where the 'missing_ok' flag is
+ * passed in a global variable.
+ */
+void
+heap_fetch_toast_slice(Relation toastrel, Oid valueid, int32 attrsize,
+ int32 sliceoffset, int32 slicelength,
+ varlena *result)
+{
+ fetch_toast_slice_was_missing =
+ heap_fetch_toast_slice_ext(toastrel, valueid, attrsize,
+ sliceoffset, slicelength,
+ result, fetch_toast_slice_missing_ok);
+}
+
/*
* Fetch a TOAST slice from a heap table.
*
@@ -627,9 +642,9 @@ toast_build_flattened_tuple(TupleDesc tupleDesc,
* Returns true on success, false if missing_ok and chunks are missing.
*/
bool
-heap_fetch_toast_slice(Relation toastrel, Oid valueid, int32 attrsize,
- int32 sliceoffset, int32 slicelength,
- varlena *result, bool missing_ok)
+heap_fetch_toast_slice_ext(Relation toastrel, Oid valueid, int32 attrsize,
+ int32 sliceoffset, int32 slicelength,
+ varlena *result, bool missing_ok)
{
Relation *toastidxs;
ScanKeyData toastkey[3];
diff --git a/src/backend/access/table/tableam.c b/src/backend/access/table/tableam.c
index 68ff0966f1c..f3164c3d627 100644
--- a/src/backend/access/table/tableam.c
+++ b/src/backend/access/table/tableam.c
@@ -49,6 +49,10 @@
char *default_table_access_method = DEFAULT_TABLE_ACCESS_METHOD;
bool synchronize_seqscans = true;
+/* hack to pass extra argument and return value to/from relation_fetch_toast_slice */
+bool fetch_toast_slice_missing_ok = false;
+bool fetch_toast_slice_was_missing = false;
+
/* ----------------------------------------------------------------------------
* Slot functions.
diff --git a/src/include/access/heaptoast.h b/src/include/access/heaptoast.h
index 1be85db6ddd..4c763447d2b 100644
--- a/src/include/access/heaptoast.h
+++ b/src/include/access/heaptoast.h
@@ -148,9 +148,18 @@ extern HeapTuple toast_build_flattened_tuple(TupleDesc tupleDesc,
* instead of raising an error. Returns true on success.
* ----------
*/
-extern bool heap_fetch_toast_slice(Relation toastrel, Oid valueid,
+extern bool heap_fetch_toast_slice_ext(Relation toastrel, Oid valueid,
+ int32 attrsize, int32 sliceoffset,
+ int32 slicelength, varlena *result,
+ bool missing_ok);
+
+/*
+ * Legacy API used in the tableam. Instead of a 'missing_ok' arg, looks
+ * at the 'fetch_toast_slice_missing_ok' variable, and returns the return
+ * value 'fetch_toast_slice_was_missing'.
+ */
+extern void heap_fetch_toast_slice(Relation toastrel, Oid valueid,
int32 attrsize, int32 sliceoffset,
- int32 slicelength, varlena *result,
- bool missing_ok);
+ int32 slicelength, varlena *result);
#endif /* HEAPTOAST_H */
diff --git a/src/include/access/tableam.h b/src/include/access/tableam.h
index a90b15dd82b..979b3f63fb2 100644
--- a/src/include/access/tableam.h
+++ b/src/include/access/tableam.h
@@ -307,6 +307,9 @@ typedef void (*IndexBuildCallback) (Relation index,
bool tupleIsAlive,
void *state);
+extern bool fetch_toast_slice_missing_ok;
+extern bool fetch_toast_slice_was_missing;
+
/*
* API struct for a table AM. Note this must be allocated in a
* server-lifetime manner, typically as a static const struct, which then gets
@@ -783,15 +786,15 @@ typedef struct TableAmRoutine
* table implemented by this AM. See table_relation_fetch_toast_slice()
* for more details.
*
- * If missing_ok is true, returns false when chunks are missing instead of
- * raising an error. Returns true on success.
+ * If the 'fetch_toast_slice_missing_ok' global variable is true and some
+ * chunks are missing, the callback should set the
+ * 'fetch_toast_slice_was_missing' flag instead of raising an error
*/
- bool (*relation_fetch_toast_slice) (Relation toastrel, Oid valueid,
+ void (*relation_fetch_toast_slice) (Relation toastrel, Oid valueid,
int32 attrsize,
int32 sliceoffset,
int32 slicelength,
- varlena *result,
- bool missing_ok);
+ varlena *result);
/* ------------------------------------------------------------------------
@@ -1995,10 +1998,20 @@ table_relation_fetch_toast_slice(Relation toastrel, Oid valueid,
int32 slicelength, varlena *result,
bool missing_ok)
{
- return toastrel->rd_tableam->relation_fetch_toast_slice(toastrel, valueid,
- attrsize,
- sliceoffset, slicelength,
- result, missing_ok);
+ fetch_toast_slice_missing_ok = missing_ok;
+ fetch_toast_slice_was_missing = false;
+ toastrel->rd_tableam->relation_fetch_toast_slice(toastrel, valueid,
+ attrsize,
+ sliceoffset, slicelength,
+ result);
+ if (missing_ok)
+ {
+ /* reset the flag just in case there are other direct callers */
+ fetch_toast_slice_missing_ok = false;
+ return fetch_toast_slice_was_missing;
+ }
+ else
+ return true;
}
--
2.47.3
^ permalink raw reply [nested|flat] 33+ messages in thread
* Re: BUG #19519: REPACK can fail due to missing chunk for toast value
@ 2026-07-08 15:00 Imran Zaheer <imran.zhir@gmail.com>
parent: Heikki Linnakangas <hlinnaka@iki.fi>
2 siblings, 1 reply; 33+ messages in thread
From: Imran Zaheer @ 2026-07-08 15:00 UTC (permalink / raw)
To: Heikki Linnakangas <hlinnaka@iki.fi>; +Cc: Michael Paquier <michael@paquier.xyz>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; Matthias van de Meent <boekewurm+postgres@gmail.com>; Alexander Lakhin <exclusion@gmail.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>; Konstantin Knizhnik <knizhnik@garret.ru>
Hi.
@@ -934,10 +953,17 @@ heapam_relation_copy_for_cluster(Relation
OldHeap, Relation NewHeap,
- reform_and_rewrite_tuple(tuple,
- OldHeap, NewHeap,
- values, isnull,
- rwstate);
+ {
+ if (!reform_and_rewrite_tuple(tuple,
+ OldHeap, NewHeap,
+ values, isnull,
+ rwstate, true))
+ {
+ /* TOAST gone for a recently dead tuple */
+ n_tuples -= 1;
+ continue;
+ }
+ }
The tuplesort_getheaptuple() will contain both live and recently
deleted tuples. However, the proposed fix passes missing_ok=true for
all tuples coming out of the sort, which means a toast fetch failure
for a LIVE tuple would be acceptable and will be silently skipped. Or
am I missing something?
Thanks
Imran Zaheer
^ permalink raw reply [nested|flat] 33+ messages in thread
* Re: BUG #19519: REPACK can fail due to missing chunk for toast value
@ 2026-07-08 22:49 Michael Paquier <michael@paquier.xyz>
parent: Imran Zaheer <imran.zhir@gmail.com>
0 siblings, 0 replies; 33+ messages in thread
From: Michael Paquier @ 2026-07-08 22:49 UTC (permalink / raw)
To: Imran Zaheer <imran.zhir@gmail.com>; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; Matthias van de Meent <boekewurm+postgres@gmail.com>; Alexander Lakhin <exclusion@gmail.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>; Konstantin Knizhnik <knizhnik@garret.ru>
On Wed, Jul 08, 2026 at 08:00:28PM +0500, Imran Zaheer wrote:
> The tuplesort_getheaptuple() will contain both live and recently
> deleted tuples. However, the proposed fix passes missing_ok=true for
> all tuples coming out of the sort, which means a toast fetch failure
> for a LIVE tuple would be acceptable and will be silently skipped. Or
> am I missing something?
Argh, thanks. Using missing_ok=true for the sort path is broken. The
flag should be false, instead. When dealing with the sort of the
tuples, we would already have made sure that the tuples with missing
toast chunks have been discarded, so a plain error with a missing
chunk would point to an invalid case.
I'm taking some time today to rework the patch set. Will add this
adjustment in it.
--
Michael
Attachments:
signature.asc (application/pgp-signature, 832B) download
^ permalink raw reply [nested|flat] 33+ messages in thread
* Re: BUG #19519: REPACK can fail due to missing chunk for toast value
@ 2026-07-09 02:47 Michael Paquier <michael@paquier.xyz>
parent: Heikki Linnakangas <hlinnaka@iki.fi>
2 siblings, 2 replies; 33+ messages in thread
From: Michael Paquier @ 2026-07-09 02:47 UTC (permalink / raw)
To: Heikki Linnakangas <hlinnaka@iki.fi>; +Cc: Srinath Reddy Sadipiralla <srinath2133@gmail.com>; Matthias van de Meent <boekewurm+postgres@gmail.com>; Imran Zaheer <imran.zhir@gmail.com>; Alexander Lakhin <exclusion@gmail.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>; Konstantin Knizhnik <knizhnik@garret.ru>
On Wed, Jul 08, 2026 at 03:00:33PM +0300, Heikki Linnakangas wrote:
> On 08/07/2026 04:10, Michael Paquier wrote:
> Yeah, boolean arguments in general can be confusing. Especially arguments
> like "missing_ok" where it's hard to remember which behavior is true and
> which is false. An IDE that shows the name of the argument helps, but having
> the caller say "MISSING_TOAST_OK" rather than "true" is much clearer.
>
> For backpatching, I think we could smuggle the flag in a global variable, to
> avoid changing the signature of the relation_fetch_toast_slice() callback.
> See attached patch 0002 on top of your 0001 patch (which is also attached
> for completeness). It doesn't fix the problem for hypothetical 3rd party
> tableam implementations that implement their own
> relation_fetch_toast_slice() callback. But do such extensions even exist? If
> yes, they could be fixed too by also checking the global variable.
One of my issues with that is that the static states can go out of
sync very easily. I'd like to think we don't have that many
extensions, but it's really hard to be sure. Silent breakages across
minor releases are never cool.
> I thought about adding an extra "extended" callback next to
> relation_fetch_toast_slice(), but I don't see a way to add functions to
> TableAmRoutine in an ABI-compatible way. For the future, we might want to
> store sizeof(TableAmRoutine) in the struct itself, so that we could add
> fields to it in minor versions without breaking the API, in case we need
> something like this again.
Right, I didn't consider this one.
>> - One for the rewrite path. It makes little sense to do any kind of
>> aggressive early detoasting because it may be wasteful due to the
>> tuple rewrites that update their data with only copies by reference
>> (main relation tuple is rewritten, reuses the same external TOAST
>> tuple). For workloads where UPDATEs do not touch the TOASTed
>> attributes, that would be a waste.
>
> I didn't understand this part. Do you mean when rebuilding the indexes after
> rewriting the heap? I didn't think we support storing toasted external
> datums in an index at all.
I was referring to toast_save_datum() (touched this area a few weeks
ago for the 8-byte TOAST thing), where we touch only the
varatt_external on the main relation in some rewrite case. Forcing a
detoast for all tuples in such cases would make the rewrite less
efficient, no?
>> - One for the index build path, which is actually too aggressive with
>> its early detoasting, now that I think about it. There should be no
>> need to perform a detoast for anything else than the attributes that
>> are used in the index definition or the attributes that are used in
>> index expressions. So as written this patch would lead to a
>> regression.
>
> Yeah, although I wouldn't be too worried about the performance here. The
> penalty would be when building an index on values that are large enough to
> be toasted, with lots of RECENTLY_DEAD tuples. That doesn't seem like a very
> common case.
Pulling the varnos from the index predicate and expressions makes that
possible, thanks to ii_NumIndexAttrs.
An updated patch is attached, with the "flags" business added, and
something for the other issue reported by Imran for the case where
reform_and_rewrite_tuple() was not handled correctly. If we have a
sort, that means going back to a more aggressive detoasting to check
if some chunks are missing if a tuple has been found as recently dead.
I was wondering about doing a split into two patches for
build_range_scan() and copy_for_cluster(), but refrained from that due
to the detoast_external_attr_extended() required in both cases.
Anyway, thoughts and reviews are welcome.
--
Michael
Attachments:
v4-0001-Fix-missing-chunk-errors-during-heap-rewrites-and.patch (text/plain, 40.7K) download
From 8d961035cdccfe9e76a859c5acd838e8f6969382 Mon Sep 17 00:00:00 2001
From: Michael Paquier <michael@paquier.xyz>
Date: Thu, 9 Jul 2026 11:46:21 +0900
Subject: [PATCH v4] Fix "missing chunk" errors during heap rewrites and index
builds
Blah, blah.
This problem has been reported recently by Alexander for REPACK, but it
is a much older issue (tested down to 9.5 for curiosity's sake, but I
suspect that it is much older than that).
XXX: This patch includes both TAP and isolation tests. We should remove
one pattern at the end.
Reported-by: Alexander Lakhin <exclusion@gmail.com>
Discussion: https://postgr.es/m/18351-f6e06364b3a2e669@postgresql.org
Discussion: https://postgr.es/m/19519-fe02d8ff679d834d@postgresql.org
---
src/include/access/detoast.h | 9 +
src/include/access/heaptoast.h | 18 +-
src/include/access/rewriteheap.h | 6 +-
src/include/access/tableam.h | 26 +-
src/include/access/toast_helper.h | 10 +-
src/backend/access/common/detoast.c | 42 +++-
src/backend/access/heap/heapam.c | 4 +-
src/backend/access/heap/heapam_handler.c | 148 ++++++++++-
src/backend/access/heap/heaptoast.c | 28 ++-
src/backend/access/heap/rewriteheap.c | 31 ++-
src/backend/access/table/toast_helper.c | 19 +-
src/test/recovery/meson.build | 1 +
src/test/recovery/t/055_rewrite_stale_xmin.pl | 124 +++++++++
contrib/dblink/.gitignore | 2 +
contrib/dblink/Makefile | 2 +
.../dblink/expected/rewrite_stale_xmin.out | 237 ++++++++++++++++++
contrib/dblink/meson.build | 5 +
contrib/dblink/specs/rewrite_stale_xmin.spec | 137 ++++++++++
18 files changed, 794 insertions(+), 55 deletions(-)
create mode 100644 src/test/recovery/t/055_rewrite_stale_xmin.pl
create mode 100644 contrib/dblink/expected/rewrite_stale_xmin.out
create mode 100644 contrib/dblink/specs/rewrite_stale_xmin.spec
diff --git a/src/include/access/detoast.h b/src/include/access/detoast.h
index fbd98181a3a1..c5eeed04b011 100644
--- a/src/include/access/detoast.h
+++ b/src/include/access/detoast.h
@@ -43,6 +43,15 @@ do { \
*/
extern varlena *detoast_external_attr(varlena *attr);
+/* ----------
+ * detoast_external_attr_extended() -
+ *
+ * Like detoast_external_attr, but returns NULL if toast chunks
+ * are missing (instead of raising an error).
+ * ----------
+ */
+extern varlena *detoast_external_attr_extended(varlena *attr);
+
/* ----------
* detoast_attr() -
*
diff --git a/src/include/access/heaptoast.h b/src/include/access/heaptoast.h
index 631cb1836b96..bc4087b3c95c 100644
--- a/src/include/access/heaptoast.h
+++ b/src/include/access/heaptoast.h
@@ -91,11 +91,15 @@
/* ----------
* heap_toast_insert_or_update -
*
- * Called by heap_insert() and heap_update().
+ * Called by heap_insert() and heap_update(). Returns NULL if the
+ * insert/update could not be completed.
+ *
+ * See toast_helper.h for the values of "flags".
* ----------
*/
extern HeapTuple heap_toast_insert_or_update(Relation rel, HeapTuple newtup,
- HeapTuple oldtup, uint32 options);
+ HeapTuple oldtup, uint32 options,
+ uint32 flags);
/* ----------
* heap_toast_delete -
@@ -139,11 +143,15 @@ extern HeapTuple toast_build_flattened_tuple(TupleDesc tupleDesc,
/* ----------
* heap_fetch_toast_slice
*
- * Fetch a slice from a toast value stored in a heap table.
+ * Fetch a slice from a toast value stored in a heap table. Returns
+ * false if the slice could not be fetched, otherwise true on success.
+ *
+ * See toast_helper.h for the values of "flags".
* ----------
*/
-extern void heap_fetch_toast_slice(Relation toastrel, Oid valueid,
+extern bool heap_fetch_toast_slice(Relation toastrel, Oid valueid,
int32 attrsize, int32 sliceoffset,
- int32 slicelength, varlena *result);
+ int32 slicelength, varlena *result,
+ uint32 flags);
#endif /* HEAPTOAST_H */
diff --git a/src/include/access/rewriteheap.h b/src/include/access/rewriteheap.h
index 6ccf7b45c04e..09110f6337a5 100644
--- a/src/include/access/rewriteheap.h
+++ b/src/include/access/rewriteheap.h
@@ -25,8 +25,10 @@ extern RewriteState begin_heap_rewrite(Relation old_heap, Relation new_heap,
TransactionId oldest_xmin, TransactionId freeze_xid,
MultiXactId cutoff_multi);
extern void end_heap_rewrite(RewriteState state);
-extern void rewrite_heap_tuple(RewriteState state, HeapTuple old_tuple,
- HeapTuple new_tuple);
+
+/* See toast_helper.h for the values of "flags" */
+extern bool rewrite_heap_tuple(RewriteState state, HeapTuple old_tuple,
+ HeapTuple new_tuple, uint32 flags);
extern bool rewrite_heap_dead_tuple(RewriteState state, HeapTuple old_tuple);
/*
diff --git a/src/include/access/tableam.h b/src/include/access/tableam.h
index f2c36696bcad..707baf804e3a 100644
--- a/src/include/access/tableam.h
+++ b/src/include/access/tableam.h
@@ -782,12 +782,17 @@ typedef struct TableAmRoutine
* This callback is invoked when detoasting a value stored in a toast
* table implemented by this AM. See table_relation_fetch_toast_slice()
* for more details.
+ *
+ * If TOAST_MISSING_OK is set in flags, returns false when chunks are
+ * missing instead of raising an error. Returns true on success. See
+ * toast_helper.h for possible values of "flags".
*/
- void (*relation_fetch_toast_slice) (Relation toastrel, Oid valueid,
+ bool (*relation_fetch_toast_slice) (Relation toastrel, Oid valueid,
int32 attrsize,
int32 sliceoffset,
int32 slicelength,
- varlena *result);
+ varlena *result,
+ uint32 flags);
/* ------------------------------------------------------------------------
@@ -1981,16 +1986,21 @@ table_relation_toast_am(Relation rel)
*
* result is caller-allocated space into which the fetched bytes should be
* stored.
+ *
+ * flags: if TOAST_MISSING_OK is set, return false when toast chunks are
+ * missing instead of raising an error. Returns true on success. See
+ * also toast_helper.h.
*/
-static inline void
+static inline bool
table_relation_fetch_toast_slice(Relation toastrel, Oid valueid,
int32 attrsize, int32 sliceoffset,
- int32 slicelength, varlena *result)
+ int32 slicelength, varlena *result,
+ uint32 flags)
{
- toastrel->rd_tableam->relation_fetch_toast_slice(toastrel, valueid,
- attrsize,
- sliceoffset, slicelength,
- result);
+ return toastrel->rd_tableam->relation_fetch_toast_slice(toastrel, valueid,
+ attrsize,
+ sliceoffset, slicelength,
+ result, flags);
}
diff --git a/src/include/access/toast_helper.h b/src/include/access/toast_helper.h
index 2ec92397f267..4abebe82798f 100644
--- a/src/include/access/toast_helper.h
+++ b/src/include/access/toast_helper.h
@@ -101,7 +101,15 @@ typedef struct
#define TOASTCOL_IGNORE 0x0010
#define TOASTCOL_INCOMPRESSIBLE 0x0020
-extern void toast_tuple_init(ToastTupleContext *ttc);
+/*
+ * Flags for TOAST fetch operations.
+ *
+ * TOAST_MISSING_OK, when set, means that a TOAST fetch tolerates missing
+ * chunks and returns a failure state instead of raising an error.
+ */
+#define TOAST_MISSING_OK (1 << 1)
+
+extern bool toast_tuple_init(ToastTupleContext *ttc, uint32 flags);
extern int toast_tuple_find_biggest_attribute(ToastTupleContext *ttc,
bool for_compression,
bool check_main);
diff --git a/src/backend/access/common/detoast.c b/src/backend/access/common/detoast.c
index a6c1f3a734b2..3195d77db4b0 100644
--- a/src/backend/access/common/detoast.c
+++ b/src/backend/access/common/detoast.c
@@ -16,13 +16,14 @@
#include "access/detoast.h"
#include "access/table.h"
#include "access/tableam.h"
+#include "access/toast_helper.h"
#include "access/toast_internals.h"
#include "common/int.h"
#include "common/pg_lzcompress.h"
#include "utils/expandeddatum.h"
#include "utils/rel.h"
-static varlena *toast_fetch_datum(varlena *attr);
+static varlena *toast_fetch_datum(varlena *attr, uint32 flags);
static varlena *toast_fetch_datum_slice(varlena *attr,
int32 sliceoffset,
int32 slicelength);
@@ -51,7 +52,7 @@ detoast_external_attr(varlena *attr)
/*
* This is an external stored plain value
*/
- result = toast_fetch_datum(attr);
+ result = toast_fetch_datum(attr, 0);
}
else if (VARATT_IS_EXTERNAL_INDIRECT(attr))
{
@@ -102,6 +103,23 @@ detoast_external_attr(varlena *attr)
}
+/* ----------
+ * detoast_external_attr_extended -
+ *
+ * Like detoast_external_attr, but returns NULL if toast chunks are
+ * missing for external pointers.
+ * ----------
+ */
+varlena *
+detoast_external_attr_extended(varlena *attr)
+{
+ if (VARATT_IS_EXTERNAL_ONDISK(attr))
+ return toast_fetch_datum(attr, TOAST_MISSING_OK);
+ else
+ return detoast_external_attr(attr);
+}
+
+
/* ----------
* detoast_attr -
*
@@ -120,7 +138,7 @@ detoast_attr(varlena *attr)
/*
* This is an externally stored datum --- fetch it back from there
*/
- attr = toast_fetch_datum(attr);
+ attr = toast_fetch_datum(attr, 0);
/* If it's compressed, decompress it */
if (VARATT_IS_COMPRESSED(attr))
{
@@ -262,7 +280,7 @@ detoast_attr_slice(varlena *attr,
preslice = toast_fetch_datum_slice(attr, 0, max_size);
}
else
- preslice = toast_fetch_datum(attr);
+ preslice = toast_fetch_datum(attr, 0);
}
else if (VARATT_IS_EXTERNAL_INDIRECT(attr))
{
@@ -337,10 +355,12 @@ detoast_attr_slice(varlena *attr,
*
* Reconstruct an in memory Datum from the chunks saved
* in the toast relation
+ *
+ * If flags uses TOAST_MISSING_OK, returns NULL when chunks are missing.
* ----------
*/
static varlena *
-toast_fetch_datum(varlena *attr)
+toast_fetch_datum(varlena *attr, uint32 flags)
{
Relation toastrel;
varlena *result;
@@ -372,8 +392,14 @@ toast_fetch_datum(varlena *attr)
toastrel = table_open(toast_pointer.va_toastrelid, AccessShareLock);
/* Fetch all chunks */
- table_relation_fetch_toast_slice(toastrel, toast_pointer.va_valueid,
- attrsize, 0, attrsize, result);
+ if (!table_relation_fetch_toast_slice(toastrel, toast_pointer.va_valueid,
+ attrsize, 0, attrsize, result,
+ flags))
+ {
+ pfree(result);
+ table_close(toastrel, AccessShareLock);
+ return NULL;
+ }
/* Close toast table */
table_close(toastrel, AccessShareLock);
@@ -454,7 +480,7 @@ toast_fetch_datum_slice(varlena *attr, int32 sliceoffset,
/* Fetch all chunks */
table_relation_fetch_toast_slice(toastrel, toast_pointer.va_valueid,
attrsize, sliceoffset, slicelength,
- result);
+ result, 0);
/* Close toast table */
table_close(toastrel, AccessShareLock);
diff --git a/src/backend/access/heap/heapam.c b/src/backend/access/heap/heapam.c
index abfd8e8970a6..c962393aab22 100644
--- a/src/backend/access/heap/heapam.c
+++ b/src/backend/access/heap/heapam.c
@@ -2236,7 +2236,7 @@ heap_prepare_insert(Relation relation, HeapTuple tup, TransactionId xid,
return tup;
}
else if (HeapTupleHasExternal(tup) || tup->t_len > TOAST_TUPLE_THRESHOLD)
- return heap_toast_insert_or_update(relation, tup, NULL, options);
+ return heap_toast_insert_or_update(relation, tup, NULL, options, 0);
else
return tup;
}
@@ -3871,7 +3871,7 @@ l2:
if (need_toast)
{
/* Note we always use WAL and FSM during updates */
- heaptup = heap_toast_insert_or_update(relation, newtup, &oldtup, 0);
+ heaptup = heap_toast_insert_or_update(relation, newtup, &oldtup, 0, 0);
newtupsize = MAXALIGN(heaptup->t_len);
}
else
diff --git a/src/backend/access/heap/heapam_handler.c b/src/backend/access/heap/heapam_handler.c
index bf87430cf017..e900ea0c0673 100644
--- a/src/backend/access/heap/heapam_handler.c
+++ b/src/backend/access/heap/heapam_handler.c
@@ -19,6 +19,7 @@
*/
#include "postgres.h"
+#include "access/detoast.h"
#include "access/genam.h"
#include "access/heapam.h"
#include "access/heaptoast.h"
@@ -26,6 +27,7 @@
#include "access/rewriteheap.h"
#include "access/syncscan.h"
#include "access/tableam.h"
+#include "access/toast_helper.h"
#include "access/tsmapi.h"
#include "access/visibilitymap.h"
#include "access/xact.h"
@@ -36,6 +38,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"
@@ -48,9 +51,11 @@
#include "utils/rel.h"
#include "utils/tuplesort.h"
-static void reform_and_rewrite_tuple(HeapTuple tuple,
+/* See toast_helper.h for values of "flags" */
+static bool reform_and_rewrite_tuple(HeapTuple tuple,
Relation OldHeap, Relation NewHeap,
- Datum *values, bool *isnull, RewriteState rwstate);
+ Datum *values, bool *isnull, RewriteState rwstate,
+ uint32 flags);
static void heap_insert_for_repack(HeapTuple tuple, Relation OldHeap,
Relation NewHeap, Datum *values, bool *isnull,
BulkInsertState bistate);
@@ -711,6 +716,7 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,
HeapTuple tuple;
Buffer buf;
bool isdead;
+ bool recently_dead = false;
CHECK_FOR_INTERRUPTS();
@@ -796,6 +802,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 */
@@ -829,6 +836,7 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,
RelationGetRelationName(OldHeap));
/* treat as recently dead */
*tups_recently_dead += 1;
+ recently_dead = true;
isdead = false;
break;
default:
@@ -857,6 +865,45 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,
*num_tuples += 1;
if (tuplesort != NULL)
{
+ /*
+ * For RECENTLY_DEAD tuples, verify TOAST data is still available
+ * before putting the tuple in the sort. If a concurrent VACUUM
+ * already reclaimed it, skip the tuple.
+ */
+ if (recently_dead)
+ {
+ bool skip = false;
+
+ heap_deform_tuple(tuple, oldTupDesc, values, isnull);
+ for (int i = 0; i < oldTupDesc->natts; i++)
+ {
+ Form_pg_attribute att = TupleDescAttr(oldTupDesc, i);
+ varlena *d;
+
+ if (att->attlen != -1 || att->attisdropped)
+ continue;
+ if (isnull[i])
+ continue;
+ if (!VARATT_IS_EXTERNAL_ONDISK(DatumGetPointer(values[i])))
+ continue;
+ d = detoast_external_attr_extended(
+ (varlena *) DatumGetPointer(values[i]));
+ if (d == NULL)
+ {
+ skip = true;
+ break;
+ }
+ pfree(d);
+ }
+ if (skip)
+ {
+ *num_tuples -= 1;
+ *tups_vacuumed += 1;
+ *tups_recently_dead -= 1;
+ continue;
+ }
+ }
+
tuplesort_putheaptuple(tuplesort, tuple);
/*
@@ -875,8 +922,22 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,
int64 ct_val[2];
if (!concurrent)
- reform_and_rewrite_tuple(tuple, OldHeap, NewHeap,
- values, isnull, rwstate);
+ {
+ if (!reform_and_rewrite_tuple(tuple, OldHeap, NewHeap,
+ values, isnull, rwstate,
+ recently_dead ? TOAST_MISSING_OK : 0))
+ {
+ /*
+ * Missing TOAST chunks for a recently-dead tuple. Treat
+ * it as dead.
+ */
+ *tups_vacuumed += 1;
+ *num_tuples -= 1;
+ if (recently_dead)
+ *tups_recently_dead -= 1;
+ continue;
+ }
+ }
else
heap_insert_for_repack(tuple, OldHeap, NewHeap,
values, isnull, bistate);
@@ -928,10 +989,12 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,
n_tuples += 1;
if (!concurrent)
- reform_and_rewrite_tuple(tuple,
- OldHeap, NewHeap,
- values, isnull,
- rwstate);
+ {
+ (void) reform_and_rewrite_tuple(tuple,
+ OldHeap, NewHeap,
+ values, isnull,
+ rwstate, 0);
+ }
else
heap_insert_for_repack(tuple, OldHeap, NewHeap,
values, isnull, bistate);
@@ -1163,6 +1226,7 @@ heapam_index_build_range_scan(Relation heapRelation,
BlockNumber previous_blkno = InvalidBlockNumber;
BlockNumber root_blkno = InvalidBlockNumber;
OffsetNumber root_offsets[MaxHeapTuplesPerPage];
+ Bitmapset *index_attrs = NULL;
/*
* sanity checks
@@ -1259,6 +1323,21 @@ heapam_index_build_range_scan(Relation heapRelation,
!TransactionIdIsValid(OldestXmin));
Assert(snapshot == SnapshotAny || !anyvisible);
+ /*
+ * Extract the set of attributes an index may need to detoast, including
+ * expressions and predicates.
+ */
+ for (int i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
+ {
+ int attnum = indexInfo->ii_IndexAttrNumbers[i];
+
+ if (attnum != 0)
+ index_attrs = bms_add_member(index_attrs,
+ attnum - FirstLowInvalidHeapAttributeNumber);
+ }
+ pull_varattnos((Node *) indexInfo->ii_Expressions, 1, &index_attrs);
+ pull_varattnos((Node *) indexInfo->ii_Predicate, 1, &index_attrs);
+
/* Publish number of blocks to scan */
if (progress)
{
@@ -1607,6 +1686,44 @@ heapam_index_build_range_scan(Relation heapRelation,
continue;
}
+ /* For RECENTLY_DEAD tuples, pre-detoast external TOAST values. */
+ if (!tupleIsAlive)
+ {
+ bool skip = false;
+ int attno;
+
+ slot_getallattrs(slot);
+ attno = -1;
+ while ((attno = bms_next_member(index_attrs, attno)) >= 0)
+ {
+ int attnum = attno + FirstLowInvalidHeapAttributeNumber;
+ Form_pg_attribute att;
+
+ if (attnum <= 0)
+ continue; /* system column */
+ att = TupleDescAttr(RelationGetDescr(heapRelation), attnum - 1);
+ if (att->attlen != -1 || att->attisdropped)
+ continue;
+ if (slot->tts_isnull[attnum - 1])
+ continue;
+ if (VARATT_IS_EXTERNAL_ONDISK(DatumGetPointer(slot->tts_values[attnum - 1])))
+ {
+ varlena *detoasted;
+
+ detoasted = detoast_external_attr_extended(
+ (varlena *) DatumGetPointer(slot->tts_values[attnum - 1]));
+ if (detoasted == NULL)
+ {
+ skip = true;
+ break;
+ }
+ slot->tts_values[attnum - 1] = PointerGetDatum(detoasted);
+ }
+ }
+ if (skip)
+ continue;
+ }
+
/*
* For the current heap tuple, extract all the attributes we use in
* this index, and note which are null. This also performs evaluation
@@ -2341,20 +2458,29 @@ heapam_scan_sample_next_tuple(TableScanDesc scan, SampleScanState *scanstate,
* SET WITHOUT OIDS.
*
* So, we must reconstruct the tuple from component Datums.
+ *
+ * Returns true on success, and false on failure if flags uses
+ * TOAST_MISSING_OK. See toast_helper.h.
*/
-static void
+static bool
reform_and_rewrite_tuple(HeapTuple tuple,
Relation OldHeap, Relation NewHeap,
- Datum *values, bool *isnull, RewriteState rwstate)
+ Datum *values, bool *isnull, RewriteState rwstate,
+ uint32 flags)
{
HeapTuple newtuple;
newtuple = reform_tuple(tuple, OldHeap, NewHeap, values, isnull);
/* The heap rewrite module does the rest */
- rewrite_heap_tuple(rwstate, tuple, newtuple);
+ if (!rewrite_heap_tuple(rwstate, tuple, newtuple, flags))
+ {
+ heap_freetuple(newtuple);
+ return false;
+ }
heap_freetuple(newtuple);
+ return true;
}
/*
diff --git a/src/backend/access/heap/heaptoast.c b/src/backend/access/heap/heaptoast.c
index 03f885a25b07..ba5942a94953 100644
--- a/src/backend/access/heap/heaptoast.c
+++ b/src/backend/access/heap/heaptoast.c
@@ -84,9 +84,10 @@ heap_toast_delete(Relation rel, HeapTuple oldtup, bool is_speculative)
* newtup: the candidate new tuple to be inserted
* oldtup: the old row version for UPDATE, or NULL for INSERT
* options: options to be passed to heap_insert() for toast rows
+ * flags: additional control flags, see heaptoast.h.
* Result:
- * either newtup if no toasting is needed, or a palloc'd modified tuple
- * that is what should actually get stored
+ * either newtup if no toasting is needed, a palloc'd modified tuple
+ * that is what should actually get stored, or NULL.
*
* NOTE: neither newtup nor oldtup will be modified. This is a change
* from the pre-8.1 API of this routine.
@@ -94,7 +95,7 @@ heap_toast_delete(Relation rel, HeapTuple oldtup, bool is_speculative)
*/
HeapTuple
heap_toast_insert_or_update(Relation rel, HeapTuple newtup, HeapTuple oldtup,
- uint32 options)
+ uint32 options, uint32 flags)
{
HeapTuple result_tuple;
TupleDesc tupleDesc;
@@ -154,7 +155,8 @@ heap_toast_insert_or_update(Relation rel, HeapTuple newtup, HeapTuple oldtup,
ttc.ttc_oldisnull = toast_oldisnull;
}
ttc.ttc_attr = toast_attr;
- toast_tuple_init(&ttc);
+ if (!toast_tuple_init(&ttc, flags))
+ return NULL;
/* ----------
* Compress and/or save external until data fits into target length
@@ -621,11 +623,15 @@ toast_build_flattened_tuple(TupleDesc tupleDesc,
* sliceoffset is the byte offset within the TOAST value from which to fetch.
* slicelength is the number of bytes to be fetched from the TOAST value.
* result is the varlena into which the results should be written.
+ * flags records more options, see toast_helper.h.
+ *
+ * Returns true on success, or false if flags uses TOAST_MISSING_OK and
+ * chunks are missing rather than raising an error.
*/
-void
+bool
heap_fetch_toast_slice(Relation toastrel, Oid valueid, int32 attrsize,
int32 sliceoffset, int32 slicelength,
- varlena *result)
+ varlena *result, uint32 flags)
{
Relation *toastidxs;
ScanKeyData toastkey[3];
@@ -779,13 +785,23 @@ heap_fetch_toast_slice(Relation toastrel, Oid valueid, int32 attrsize,
* Final checks that we successfully fetched the datum
*/
if (expectedchunk != (endchunk + 1))
+ {
+ if (flags & TOAST_MISSING_OK)
+ {
+ systable_endscan_ordered(toastscan);
+ toast_close_indexes(toastidxs, num_indexes, AccessShareLock);
+ return false;
+ }
ereport(ERROR,
(errcode(ERRCODE_DATA_CORRUPTED),
errmsg_internal("missing chunk number %d for toast value %u in %s",
expectedchunk, valueid,
RelationGetRelationName(toastrel))));
+ }
/* End scan and close indexes. */
systable_endscan_ordered(toastscan);
toast_close_indexes(toastidxs, num_indexes, AccessShareLock);
+
+ return true;
}
diff --git a/src/backend/access/heap/rewriteheap.c b/src/backend/access/heap/rewriteheap.c
index 0ccd392c3dc0..811f1934db34 100644
--- a/src/backend/access/heap/rewriteheap.c
+++ b/src/backend/access/heap/rewriteheap.c
@@ -211,7 +211,8 @@ typedef struct RewriteMappingDataEntry
/* prototypes for internal functions */
-static void raw_heap_insert(RewriteState state, HeapTuple tup);
+static bool raw_heap_insert(RewriteState state, HeapTuple tup,
+ uint32 flags);
/* internal logical remapping prototypes */
static void logical_begin_heap_rewrite(RewriteState state);
@@ -309,7 +310,7 @@ end_heap_rewrite(RewriteState state)
while ((unresolved = hash_seq_search(&seq_status)) != NULL)
{
ItemPointerSetInvalid(&unresolved->tuple->t_data->t_ctid);
- raw_heap_insert(state, unresolved->tuple);
+ raw_heap_insert(state, unresolved->tuple, 0);
}
/* Write the last page, if any */
@@ -338,9 +339,10 @@ end_heap_rewrite(RewriteState state)
* old_tuple original tuple in the old heap
* new_tuple new, rewritten tuple to be inserted to new heap
*/
-void
+bool
rewrite_heap_tuple(RewriteState state,
- HeapTuple old_tuple, HeapTuple new_tuple)
+ HeapTuple old_tuple, HeapTuple new_tuple,
+ uint32 flags)
{
MemoryContext old_cxt;
ItemPointerData old_tid;
@@ -437,7 +439,7 @@ rewrite_heap_tuple(RewriteState state,
* tuple will be written.
*/
MemoryContextSwitchTo(old_cxt);
- return;
+ return true;
}
}
@@ -455,7 +457,13 @@ rewrite_heap_tuple(RewriteState state,
ItemPointerData new_tid;
/* Insert the tuple and find out where it's put in new_heap */
- raw_heap_insert(state, new_tuple);
+ if (!raw_heap_insert(state, new_tuple, flags))
+ {
+ if (free_new)
+ heap_freetuple(new_tuple);
+ MemoryContextSwitchTo(old_cxt);
+ return false;
+ }
new_tid = new_tuple->t_self;
logical_rewrite_heap_tuple(state, old_tid, new_tuple);
@@ -532,6 +540,7 @@ rewrite_heap_tuple(RewriteState state,
}
MemoryContextSwitchTo(old_cxt);
+ return true;
}
/*
@@ -593,8 +602,8 @@ rewrite_heap_dead_tuple(RewriteState state, HeapTuple old_tuple)
* tuple is invalid on entry, it's replaced with the new TID as well (in
* the inserted data only, not in the caller's copy).
*/
-static void
-raw_heap_insert(RewriteState state, HeapTuple tup)
+static bool
+raw_heap_insert(RewriteState state, HeapTuple tup, uint32 flags)
{
Page page;
Size pageFreeSpace,
@@ -628,7 +637,9 @@ raw_heap_insert(RewriteState state, HeapTuple tup)
options |= HEAP_INSERT_NO_LOGICAL;
heaptup = heap_toast_insert_or_update(state->rs_new_rel, tup, NULL,
- options);
+ options, flags);
+ if (heaptup == NULL)
+ return false;
}
else
heaptup = tup;
@@ -702,6 +713,8 @@ raw_heap_insert(RewriteState state, HeapTuple tup)
/* If heaptup is a private copy, release it. */
if (heaptup != tup)
heap_freetuple(heaptup);
+
+ return true;
}
/* ------------------------------------------------------------------------
diff --git a/src/backend/access/table/toast_helper.c b/src/backend/access/table/toast_helper.c
index 2f2022d99510..50ce051a6876 100644
--- a/src/backend/access/table/toast_helper.c
+++ b/src/backend/access/table/toast_helper.c
@@ -36,9 +36,13 @@
* toast_flags is just a single uint8, but toast_attr is a caller-provided
* array with a length equal to tupleDesc->natts. The caller need not
* perform any initialization of the array before calling this function.
+ *
+ * If flags uses TOAST_MISSING_OK and an external TOAST value cannot be
+ * fetched, returns false instead of raising an error. Returns true on
+ * success. See toast_helper.h.
*/
-void
-toast_tuple_init(ToastTupleContext *ttc)
+bool
+toast_tuple_init(ToastTupleContext *ttc, uint32 flags)
{
TupleDesc tupleDesc = ttc->ttc_rel->rd_att;
int numAttrs = tupleDesc->natts;
@@ -137,7 +141,14 @@ toast_tuple_init(ToastTupleContext *ttc)
if (VARATT_IS_EXTERNAL(new_value))
{
ttc->ttc_attr[i].tai_oldexternal = new_value;
- if (att->attstorage == TYPSTORAGE_PLAIN)
+ if ((flags & TOAST_MISSING_OK) != 0 &&
+ VARATT_IS_EXTERNAL_ONDISK(new_value))
+ {
+ new_value = detoast_external_attr_extended(new_value);
+ if (new_value == NULL)
+ return false;
+ }
+ else if (att->attstorage == TYPSTORAGE_PLAIN)
new_value = detoast_attr(new_value);
else
new_value = detoast_external_attr(new_value);
@@ -159,6 +170,8 @@ toast_tuple_init(ToastTupleContext *ttc)
ttc->ttc_attr[i].tai_colflags |= TOASTCOL_IGNORE;
}
}
+
+ return true;
}
/*
diff --git a/src/test/recovery/meson.build b/src/test/recovery/meson.build
index ad0d85f41897..7e583ee39a10 100644
--- a/src/test/recovery/meson.build
+++ b/src/test/recovery/meson.build
@@ -63,6 +63,7 @@ tests += {
't/052_checkpoint_segment_missing.pl',
't/053_standby_login_event_trigger.pl',
't/054_unlogged_sequence_promotion.pl',
+ 't/055_rewrite_stale_xmin.pl',
],
},
}
diff --git a/src/test/recovery/t/055_rewrite_stale_xmin.pl b/src/test/recovery/t/055_rewrite_stale_xmin.pl
new file mode 100644
index 000000000000..dad95c0cf967
--- /dev/null
+++ b/src/test/recovery/t/055_rewrite_stale_xmin.pl
@@ -0,0 +1,124 @@
+# Copyright (c) 2025-2026, PostgreSQL Global Development Group
+#
+# Test that heap rewrites (CLUSTER, VACUUM FULL, REPACK) and index builds
+# work in the case when the backend's own xmin is held back by a transaction
+# in another database.
+
+use strict;
+use warnings;
+use PostgreSQL::Test::Cluster;
+use Test::More;
+
+my $node = PostgreSQL::Test::Cluster->new('primary');
+$node->init;
+# No Autovacuum, no random interferences.
+$node->append_conf(
+ 'postgresql.conf', qq[
+autovacuum = off
+]);
+$node->start;
+
+# Create two databases.
+$node->safe_psql('postgres', 'CREATE DATABASE db_holder');
+$node->safe_psql('postgres', 'CREATE DATABASE db_target');
+
+# Set up a table with TOAST data. Returns the toast table name.
+sub setup_table
+{
+ my ($tblname, $extra_ddl) = @_;
+ $extra_ddl //= '';
+
+ $node->safe_psql(
+ 'db_target', qq{
+ DROP TABLE IF EXISTS $tblname;
+ CREATE TABLE $tblname (id int PRIMARY KEY, data text)
+ WITH (autovacuum_enabled = off);
+ ALTER TABLE $tblname ALTER COLUMN data SET STORAGE EXTERNAL;
+ INSERT INTO $tblname VALUES (1, repeat('x', 2500));
+ INSERT INTO $tblname VALUES (2, repeat('z', 2500));
+ $extra_ddl
+ });
+
+ my $toast = $node->safe_psql(
+ 'db_target', qq{
+ SELECT 'pg_toast.' || relname FROM pg_class
+ WHERE oid = (SELECT reltoastrelid FROM pg_class
+ WHERE relname = '$tblname');
+ });
+ chomp $toast;
+ return $toast;
+}
+
+# Create precondition state. Requires that $holder is already running with
+# a write XID.
+sub create_missing_toast_state
+{
+ my ($tblname, $toast_table) = @_;
+
+ # Hold xmin in same DB to prevent main tuple removal.
+ my $xmin_holder = $node->background_psql('db_target', on_error_stop => 1);
+ $xmin_holder->query_safe("BEGIN ISOLATION LEVEL REPEATABLE READ");
+ $xmin_holder->query_safe("SELECT 1");
+
+ # Delete the row with TOAST data.
+ $node->safe_psql('db_target', "DELETE FROM $tblname WHERE id = 1");
+
+ # VACUUM main table only. The xmin_holder keeps the dead tuple.
+ $node->safe_psql('db_target', "VACUUM (PROCESS_TOAST false) $tblname");
+
+ # Release same-DB xmin.
+ $xmin_holder->query_safe("COMMIT");
+ $xmin_holder->quit;
+
+ # Vacuum toast table: toast chunks now DEAD and removed.
+ $node->safe_psql('db_target', "VACUUM $toast_table");
+}
+
+# Open a transaction holding an XID before any deletes. This XID will hold
+# back GetSnapshotData() globally, on a different database than the one
+# running the various rewrite operations.
+my $holder = $node->background_psql('db_holder', on_error_stop => 1);
+$holder->query_safe("BEGIN");
+$holder->query_safe("CREATE TEMP TABLE xid_holder(x int)");
+
+# Test 1: CLUSTER
+my $toast = setup_table('rewrite_test');
+create_missing_toast_state('rewrite_test', $toast);
+
+my ($ret, $stdout, $stderr) =
+ $node->psql('db_target', 'CLUSTER rewrite_test USING rewrite_test_pkey');
+is($ret, 0, "CLUSTER succeeds without missing-chunk error");
+unlike($stderr, qr/missing chunk/, "CLUSTER: no missing-chunk error");
+
+# Test 2: VACUUM FULL
+$toast = setup_table('rewrite_test');
+create_missing_toast_state('rewrite_test', $toast);
+
+($ret, $stdout, $stderr) =
+ $node->psql('db_target', 'VACUUM FULL rewrite_test');
+is($ret, 0, "VACUUM FULL succeeds without missing-chunk error");
+unlike($stderr, qr/missing chunk/, "VACUUM FULL: no missing-chunk error");
+
+# Test 3: REPACK
+$toast = setup_table('rewrite_test');
+create_missing_toast_state('rewrite_test', $toast);
+
+($ret, $stdout, $stderr) = $node->psql('db_target', 'REPACK rewrite_test');
+is($ret, 0, "REPACK succeeds without missing-chunk error");
+unlike($stderr, qr/missing chunk/, "REPACK: no missing-chunk error");
+
+# Test 4: CREATE INDEX on toasted column
+$toast = setup_table('rewrite_test');
+create_missing_toast_state('rewrite_test', $toast);
+
+($ret, $stdout, $stderr) = $node->psql('db_target',
+ 'CREATE INDEX rewrite_test_data_idx ON rewrite_test (data)');
+is($ret, 0, "CREATE INDEX succeeds without missing-chunk error");
+unlike($stderr, qr/missing chunk/, "CREATE INDEX: no missing-chunk error");
+
+# Cleanup.
+$holder->query_safe("COMMIT");
+$holder->quit;
+
+$node->stop;
+done_testing();
diff --git a/contrib/dblink/.gitignore b/contrib/dblink/.gitignore
index 5dcb3ff97235..33bc8d8ffeb3 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 fde0b49ddbbd..a0ba41280813 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 000000000000..2e5a7940ea26
--- /dev/null
+++ b/contrib/dblink/expected/rewrite_stale_xmin.out
@@ -0,0 +1,237 @@
+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_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)
+
diff --git a/contrib/dblink/meson.build b/contrib/dblink/meson.build
index e2489f41229f..86fbd372b880 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 000000000000..fe88e789f854
--- /dev/null
+++ b/contrib/dblink/specs/rewrite_stale_xmin.spec
@@ -0,0 +1,137 @@
+# Test that heap rewrites work when the rewriting backend's own xmin is
+# held back by a transaction in another database.
+
+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_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;
+}
+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);
+}
+
+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
+
+# 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
--
2.55.0
signature.asc (application/pgp-signature, 832B) download
^ permalink raw reply [nested|flat] 33+ messages in thread
* Re: BUG #19519: REPACK can fail due to missing chunk for toast value
@ 2026-07-09 05:17 Konstantin Knizhnik <knizhnik@garret.ru>
parent: Heikki Linnakangas <hlinnaka@iki.fi>
2 siblings, 1 reply; 33+ messages in thread
From: Konstantin Knizhnik @ 2026-07-09 05:17 UTC (permalink / raw)
To: Heikki Linnakangas <hlinnaka@iki.fi>; Michael Paquier <michael@paquier.xyz>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; +Cc: Matthias van de Meent <boekewurm+postgres@gmail.com>; Imran Zaheer <imran.zhir@gmail.com>; Alexander Lakhin <exclusion@gmail.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>
On 08/07/2026 3:00 PM, Heikki Linnakangas wrote:
> On 08/07/2026 04:10, Michael Paquier wrote:
>> On Wed, Jul 08, 2026 at 07:15:16AM +0900, Michael Paquier wrote:
>>> One thing that I still don't like much in the patch as written is my
>>> use of a missing_ok argument, which feels super confusing as it
>>> applies only to the underlying external TOAST, if the relation has
>>> any. I'd be tempted to rewrite this portion of the patch with a
>>> uint32 flags. Even if we assign one value for now (say MISSING_TOAST,
>>> MISSING_TOAST_OK or whatever), it would allow more flexibility on ABI
>>> grounds if we want more like states in the future across this portion
>>> of the stack. Again, I strongly doubt that we will be able to
>>> backpatch any of that.
>
> Yeah, boolean arguments in general can be confusing. Especially
> arguments like "missing_ok" where it's hard to remember which behavior
> is true and which is false. An IDE that shows the name of the argument
> helps, but having the caller say "MISSING_TOAST_OK" rather than "true"
> is much clearer.
>
> For backpatching, I think we could smuggle the flag in a global
> variable, to avoid changing the signature of the
> relation_fetch_toast_slice() callback. See attached patch 0002 on top
> of your 0001 patch (which is also attached for completeness). It
> doesn't fix the problem for hypothetical 3rd party tableam
> implementations that implement their own relation_fetch_toast_slice()
> callback. But do such extensions even exist? If yes, they could be
> fixed too by also checking the global variable.
>
> I thought about adding an extra "extended" callback next to
> relation_fetch_toast_slice(), but I don't see a way to add functions
> to TableAmRoutine in an ABI-compatible way. For the future, we might
> want to store sizeof(TableAmRoutine) in the struct itself, so that we
> could add fields to it in minor versions without breaking the API, in
> case we need something like this again.
Changing `table_relation_fetch_toast_slice` signature breaks
compatibility with some extensions, for example duckdb.
I wonder if we can change only `bool (*relation_fetch_toast_slice)(...,
bool missing_ok)` callback signature, but preserve signature of
`table_relation_fetch_toast_slice`, adding one more function
`table_relation_try_fetch_toast_slice`:
static inline void
table_relation_fetch_toast_slice(Relation toastrel, Oid valueid,
int32 attrsize,
int32 sliceoffset,
int32
slicelength, varlena *result,
bool missing_ok)
{
(void)toastrel->rd_tableam->relation_fetch_toast_slice(toastrel,
valueid,
attrsize,
sliceoffset, slicelength,
result, false);
}
static inline bool
table_relation_try_fetch_toast_slice(Relation toastrel, Oid valueid,
int32 attrsize,
int32 sliceoffset,
int32
slicelength, varlena *result,
bool missing_ok)
{
return toastrel->rd_tableam->relation_fetch_toast_slice(toastrel,
valueid,
attrsize,
sliceoffset, slicelength,
result, missing_ok);
}
>
>> A couple of extra notes while I do not forget about that stuff.. The
>> patch may be better split into two if we go with this approach, as the
>> index build and rewrite paths require different solutions:
>> - One for the rewrite path. It makes little sense to do any kind of
>> aggressive early detoasting because it may be wasteful due to the
>> tuple rewrites that update their data with only copies by reference
>> (main relation tuple is rewritten, reuses the same external TOAST
>> tuple). For workloads where UPDATEs do not touch the TOASTed
>> attributes, that would be a waste.
>
> I didn't understand this part. Do you mean when rebuilding the indexes
> after rewriting the heap? I didn't think we support storing toasted
> external datums in an index at all.
>
>> - One for the index build path, which is actually too aggressive with
>> its early detoasting, now that I think about it. There should be no
>> need to perform a detoast for anything else than the attributes that
>> are used in the index definition or the attributes that are used in
>> index expressions. So as written this patch would lead to a
>> regression.
> Yeah, although I wouldn't be too worried about the performance here.
> The penalty would be when building an index on values that are large
> enough to be toasted, with lots of RECENTLY_DEAD tuples. That doesn't
> seem like a very common case.
>
> - Heikki
^ permalink raw reply [nested|flat] 33+ messages in thread
* Re: BUG #19519: REPACK can fail due to missing chunk for toast value
@ 2026-07-09 05:43 Michael Paquier <michael@paquier.xyz>
parent: Konstantin Knizhnik <knizhnik@garret.ru>
0 siblings, 2 replies; 33+ messages in thread
From: Michael Paquier @ 2026-07-09 05:43 UTC (permalink / raw)
To: Konstantin Knizhnik <knizhnik@garret.ru>; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; Matthias van de Meent <boekewurm+postgres@gmail.com>; Imran Zaheer <imran.zhir@gmail.com>; Alexander Lakhin <exclusion@gmail.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>
On Thu, Jul 09, 2026 at 08:17:06AM +0300, Konstantin Knizhnik wrote:
> Changing `table_relation_fetch_toast_slice` signature breaks compatibility
> with some extensions, for example duckdb.
> I wonder if we can change only `bool (*relation_fetch_toast_slice)(...,
> bool missing_ok)` callback signature, but preserve signature of
> `table_relation_fetch_toast_slice`, adding one more function
> `table_relation_try_fetch_toast_slice`:
Thanks for the input.
Adding more functions implies to change the size of TableAmRoutine,
which may be bad. For now I'd be tempted to just focus on how to fix
the problem on HEAD in a way we are happy with. We could sort out an
optional back-branch version as a second step.
--
Michael
Attachments:
signature.asc (application/pgp-signature, 832B) download
^ permalink raw reply [nested|flat] 33+ messages in thread
* Re: BUG #19519: REPACK can fail due to missing chunk for toast value
@ 2026-07-09 10:08 Konstantin Knizhnik <knizhnik@garret.ru>
parent: Michael Paquier <michael@paquier.xyz>
1 sibling, 0 replies; 33+ messages in thread
From: Konstantin Knizhnik @ 2026-07-09 10:08 UTC (permalink / raw)
To: Michael Paquier <michael@paquier.xyz>; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; Matthias van de Meent <boekewurm+postgres@gmail.com>; Imran Zaheer <imran.zhir@gmail.com>; Alexander Lakhin <exclusion@gmail.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>
On 09/07/2026 8:43 AM, Michael Paquier wrote:
> On Thu, Jul 09, 2026 at 08:17:06AM +0300, Konstantin Knizhnik wrote:
>> Changing `table_relation_fetch_toast_slice` signature breaks compatibility
>> with some extensions, for example duckdb.
>> I wonder if we can change only `bool (*relation_fetch_toast_slice)(...,
>> bool missing_ok)` callback signature, but preserve signature of
>> `table_relation_fetch_toast_slice`, adding one more function
>> `table_relation_try_fetch_toast_slice`:
> Thanks for the input.
>
> Adding more functions implies to change the size of TableAmRoutine,
> which may be bad. For now I'd be tempted to just focus on how to fix
> the problem on HEAD in a way we are happy with. We could sort out an
> optional back-branch version as a second step.
> --
> Michael
Sorry, I do not suggest to extend TableAmRoutine - it will contain
single `relation_fetch_toast_slice` entry with new signature.
I suggest to add only new wrapper function
`table_relation_try_fetch_toast_slice`, preserving original
`table_relation_fetch_toast_slice`. It will preserve compatibility with
extensions (there are not using TableAmRoutine directly) and do not
extend TableAmRoutine.
^ permalink raw reply [nested|flat] 33+ messages in thread
* Re: BUG #19519: REPACK can fail due to missing chunk for toast value
@ 2026-07-17 10:22 Matthias van de Meent <boekewurm+postgres@gmail.com>
parent: Michael Paquier <michael@paquier.xyz>
1 sibling, 0 replies; 33+ messages in thread
From: Matthias van de Meent @ 2026-07-17 10:22 UTC (permalink / raw)
To: Michael Paquier <michael@paquier.xyz>; +Cc: Imran Zaheer <imran.zhir@gmail.com>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; Alexander Lakhin <exclusion@gmail.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>; Konstantin Knizhnik <knizhnik@garret.ru>
On Tue, 7 Jul 2026 at 03:42, Michael Paquier <michael@paquier.xyz> wrote:
>
> On Tue, Jul 07, 2026 at 01:51:32AM +0200, Matthias van de Meent wrote:
> >
> > Either way, if we can register a snapshot in the REPACK/INDEX backend whose
> > xmin is (*correctly*) registered with the OldestNonRemovableTransactionId()
> > of the relation, then concurrent cleanup won't happen for toast, and we'd
> > also avoid dereferencing those dangling toast pointers. We won't need to
> > actually use that snapshot for any scans; it'll avoid the issue as long as
> > our backend advertises an xmin <= the OldestXmin used in maintenance to
> > hold back pruning/vacuum on the relation.
> >
> > (we can adjust that xmin every once in a while with a newer
> > OldestNonRemovableTransactionId (excl. our own backend) as long as we also
> > adjust the OldestXmin cutoff for the SnapshotAny visibility tests, but I
> > don't suggest to backpatch that even newer system, it'd add significant
> > complications to an already complicated system)
>
> I doubt that anything would be backpatchable, based on how the
> discussion is going. I'm OK to be proven wrong.
I've tried my hand at implementing this, but finally realized it's not
possible to build a safe non-vacuumable AnySnapshot that is certain to
be protected against concurrent cleanup. That needs a guarantee that
the vacuum horizon calculations we're using (and other backends are
going to use) never go backwards, and we can't give that guarantee.
This has to do with the way hot standby feedback is implemented, plus
various other components that allow(ed) xmin to be set from snapshots
which were already dropped from PGPROC's data.
Kind regards,
Matthias van de Meent
^ permalink raw reply [nested|flat] 33+ messages in thread
* Re: BUG #19519: REPACK can fail due to missing chunk for toast value
@ 2026-07-21 15:44 Dilip Kumar <dilipbalaut@gmail.com>
parent: Michael Paquier <michael@paquier.xyz>
1 sibling, 0 replies; 33+ messages in thread
From: Dilip Kumar @ 2026-07-21 15:44 UTC (permalink / raw)
To: Michael Paquier <michael@paquier.xyz>; +Cc: Konstantin Knizhnik <knizhnik@garret.ru>; Heikki Linnakangas <hlinnaka@iki.fi>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; Matthias van de Meent <boekewurm+postgres@gmail.com>; Imran Zaheer <imran.zhir@gmail.com>; Alexander Lakhin <exclusion@gmail.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>
On Thu, Jul 9, 2026 at 11:13 AM Michael Paquier <michael@paquier.xyz> wrote:
>
> On Thu, Jul 09, 2026 at 08:17:06AM +0300, Konstantin Knizhnik wrote:
> > Changing `table_relation_fetch_toast_slice` signature breaks compatibility
> > with some extensions, for example duckdb.
> > I wonder if we can change only `bool (*relation_fetch_toast_slice)(...,
> > bool missing_ok)` callback signature, but preserve signature of
> > `table_relation_fetch_toast_slice`, adding one more function
> > `table_relation_try_fetch_toast_slice`:
>
> Thanks for the input.
>
> Adding more functions implies to change the size of TableAmRoutine,
> which may be bad. For now I'd be tempted to just focus on how to fix
> the problem on HEAD in a way we are happy with. We could sort out an
> optional back-branch version as a second step.
I was reviewing this patch, haven't yet completed the review but
noticed one discrepancy with the patch
Prior to this patch, if att->attstorage == TYPSTORAGE_PLAIN,
toast_tuple_init() called detoast_attr(), which fetches and
decompresses if VARATT_IS_EXTERNAL_ONDISK and VARATT_IS_COMPRESSED.
Now with patch when (flags & TOAST_MISSING_OK) is set,
detoast_external_attr_extended() fetches raw bytes from pg_toast if
(VARATT_IS_EXTERNAL_ONDISK(attr)), leaving compressed external datums
compressed. So this seems to be a change in behavior for external
compressed attributes when the attribute storage is set to PLAIN. Am
I missing something?
--
Regards,
Dilip Kumar
Google
^ permalink raw reply [nested|flat] 33+ messages in thread
* RE: BUG #19519: REPACK can fail due to missing chunk for toast value
@ 2026-07-24 11:39 Zhijie Hou (Fujitsu) <houzj.fnst@fujitsu.com>
parent: Michael Paquier <michael@paquier.xyz>
1 sibling, 0 replies; 33+ messages in thread
From: Zhijie Hou (Fujitsu) @ 2026-07-24 11:39 UTC (permalink / raw)
To: Michael Paquier <michael@paquier.xyz>; Heikki Linnakangas <hlinnaka@iki.fi>; +Cc: Srinath Reddy Sadipiralla <srinath2133@gmail.com>; Matthias van de Meent <boekewurm+postgres@gmail.com>; Imran Zaheer <imran.zhir@gmail.com>; Alexander Lakhin <exclusion@gmail.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>; Konstantin Knizhnik <knizhnik@garret.ru>
On Thursday, July 9, 2026 10:47 AM Michael Paquier <michael@paquier.xyz> wrote:
>
> An updated patch is attached, with the "flags" business added, and something
> for the other issue reported by Imran for the case where
> reform_and_rewrite_tuple() was not handled correctly. If we have a sort,
> that means going back to a more aggressive detoasting to check if some
> chunks are missing if a tuple has been found as recently dead.
> I was wondering about doing a split into two patches for
> build_range_scan() and copy_for_cluster(), but refrained from that due to the
> detoast_external_attr_extended() required in both cases.
>
> Anyway, thoughts and reviews are welcome.
Thank you for updating the patch. I've reviewed it and have a few comments
below.
1.
I think there could be a memory leak in the early return path of
heap_toast_insert_or_update() when failing to retrieve a toast value.
In toast_tuple_init, each attribute is detoasted one by one. This means that if
there are multiple toasted columns, it's possible that some columns have already
been detoasted while the remaining ones cannot be accessed (e.g., they were
removed by vacuum). This can happen because we have a "HOT" mechanism that
avoids updating unchanged toast columns, so if a user only updates one toast
column value, the other toast columns in the table can still point to old chunks
that may no longer be available.
In such cases, the code continues rewriting without freeing the already
detoasted values, unlike what we do in toast_tuple_cleanup.
2.
This patch does not add TOAST_MISSING_OK to the
end_heap_rewrite->raw_heap_insert call path, but it does seem possible to
trigger the similar bug there.
In rewrite_heap_tuple(), the tuple being updated is added to the
rs_unresolved_tups hash. If that tuple has an unavailable toast value, then when
end_heap_rewrite() is reached, it will attempt to read that toast value and
report a "missing chunk" error.
Please see the attachment which contains a script that I had AI generate to
reproduce both issues.
Best Regards,
Zhijie Hou
Attachments:
repro_sh (application/octet-stream, 4.2K) download
^ permalink raw reply [nested|flat] 33+ messages in thread
* Re: BUG #19519: REPACK can fail due to missing chunk for toast value
@ 2026-07-30 19:54 Matthias van de Meent <boekewurm+postgres@gmail.com>
parent: Michael Paquier <michael@paquier.xyz>
1 sibling, 2 replies; 33+ messages in thread
From: Matthias van de Meent @ 2026-07-30 19:54 UTC (permalink / raw)
To: Michael Paquier <michael@paquier.xyz>; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; Imran Zaheer <imran.zhir@gmail.com>; Alexander Lakhin <exclusion@gmail.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>; Konstantin Knizhnik <knizhnik@garret.ru>
On Thu, 9 Jul 2026 at 04:47, Michael Paquier <michael@paquier.xyz> wrote:
>
> An updated patch is attached, with the "flags" business added, and
> something for the other issue reported by Imran for the case where
> reform_and_rewrite_tuple() was not handled correctly. If we have a
> sort, that means going back to a more aggressive detoasting to check
> if some chunks are missing if a tuple has been found as recently dead.
> I was wondering about doing a split into two patches for
> build_range_scan() and copy_for_cluster(), but refrained from that due
> to the detoast_external_attr_extended() required in both cases.
>
> Anyway, thoughts and reviews are welcome.
I've gone through the patch, see below. I've attached some of the
suggested changes in 0002, with your v4-0001 as v5-0001. Some are more
involved.
> +++ b/src/backend/access/heap/heaptoast.c
> heap_toast_insert_or_update(Relation rel, HeapTuple newtup, HeapTuple oldtup,
> - uint32 options)
> + uint32 options, uint32 flags)
Is there a good reason why the options argument couldn't be reused
with one or a few more new flag bits? The TABLE_INSERT options itself
defines only 3 bits right now, and HEAP_INSERT adds only one more,
leaving more than enough space for any other shenanigans we may have
to pull with non-MVCC-backed TOAST operations.
> +++ b/src/backend/access/heap/heapam_handler.c
> @@ -857,6 +865,45 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,
> {
> + /*
> + * For RECENTLY_DEAD tuples, verify TOAST data is still available
> + * before putting the tuple in the sort. If a concurrent VACUUM
> + * already reclaimed it, skip the tuple.
> + */
> + if (recently_dead)
[...]
This code only skips tuples whose toasted data is not deleted ahead of
putting the tuple referencing the toasted data into the sort. It
doesn't save the detoasted values, and so doesn't really protect
against concurrent removal of the tuple's toasted data _after_ putting
the tuple into the sort, which could cause issues if the same tuple
needs to detoast now-deleted toast data as part of (e.g.) the
tuplesort.
> + *tups_vacuumed += 1;
> + *num_tuples -= 1;
> + if (recently_dead)
> + *tups_recently_dead -= 1;
I think this `if (recently_dead)` should be an Assert(recently_dead).
Of all possible tuple visibility states only RECENTLY_DEAD tuples are
allowed to get their TOAST data reclaimed while we're processing the
scan. Adjusted accordingly in 0002
> + /*
> + * Extract the set of attributes an index may need to detoast, including
> + * expressions and predicates.
> + */
I think this code will need to be adjusted to handle whole-row expressions.
Right now, it fails when an index/order by of `(tablename.*)` is
defined; this gives a Var with attno=0, which can't be detoasted as
such, but should cause every attribute to be detoasted.
Example: Use this in the 055 test instead of the current index, and
you'll probably hit a detoasting error:
'CREATE INDEX rewrite_test_data_idx ON rewrite_test ((rewrite_test
IS NOT NULL))');
Fix in 0002.
> @@ -1607,6 +1686,44 @@ heapam_index_build_range_scan(Relation heapRelation,
> continue;
> }
>
> + /* For RECENTLY_DEAD tuples, pre-detoast external TOAST values. */
This path can leak memory if multiple attributes need to be detoasted
in this path. We need to keep track of which attributes we need to
manually pfree(), so that we don't leak memory in this path.
Additionally, this pre-detoasting section needs to happen before we
execute the predicate, because right now we only detect missing toast
and reject the tuples after the predicate was executed; and this
predicate can have detoasting with ERRORs if the attributes weren't
yet pre-detoasted.
These both are fixed in 0002.
I've also included a fix for issue 1 of Zhijie's reply of July 24 in patch 0002.
Kind regards,
Matthias van de Meent
Databricks (https://www.databricks.com)
Attachments: download all (2 files, .tar.gz)
v5-0002-Various-fixes-and-adjustments.patch (application/octet-stream, 11.4K) download
From 2ac1755494b7c54c83b2c5300779005616c55d2b Mon Sep 17 00:00:00 2001
From: Matthias van de Meent <boekewurm+postgres@gmail.com>
Date: Thu, 30 Jul 2026 21:22:46 +0200
Subject: [PATCH v5 2/2] Various fixes and adjustments:
- Detoasting/unpacking of heap attrs is limited to only relevant
attrs, including whole-row attrs
- Manage detoasting memory of heapam_index_build_range_scan
- Return NULL on *any* expected situations from concurrent toast
tuple removal in detoasting when TOAST_MISSING_OK is defined.
- Test whole-row Var in tests
- Avoid leaking memory in toast_tuple_init
---
src/backend/access/heap/heapam_handler.c | 137 +++++++++++++++---
src/backend/access/heap/heaptoast.c | 32 +++-
src/backend/access/table/toast_helper.c | 13 +-
src/test/recovery/t/055_rewrite_stale_xmin.pl | 2 +-
4 files changed, 154 insertions(+), 30 deletions(-)
diff --git a/src/backend/access/heap/heapam_handler.c b/src/backend/access/heap/heapam_handler.c
index e900ea0c067..8c7a67ec3e1 100644
--- a/src/backend/access/heap/heapam_handler.c
+++ b/src/backend/access/heap/heapam_handler.c
@@ -927,14 +927,14 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,
values, isnull, rwstate,
recently_dead ? TOAST_MISSING_OK : 0))
{
+ Assert(recently_dead);
/*
* Missing TOAST chunks for a recently-dead tuple. Treat
* it as dead.
*/
*tups_vacuumed += 1;
*num_tuples -= 1;
- if (recently_dead)
- *tups_recently_dead -= 1;
+ *tups_recently_dead -= 1;
continue;
}
}
@@ -1226,7 +1226,7 @@ heapam_index_build_range_scan(Relation heapRelation,
BlockNumber previous_blkno = InvalidBlockNumber;
BlockNumber root_blkno = InvalidBlockNumber;
OffsetNumber root_offsets[MaxHeapTuplesPerPage];
- Bitmapset *index_attrs = NULL;
+ Bitmapset *detoast_index_attrs = NULL;
/*
* sanity checks
@@ -1332,11 +1332,60 @@ heapam_index_build_range_scan(Relation heapRelation,
int attnum = indexInfo->ii_IndexAttrNumbers[i];
if (attnum != 0)
- index_attrs = bms_add_member(index_attrs,
+ detoast_index_attrs = bms_add_member(detoast_index_attrs,
attnum - FirstLowInvalidHeapAttributeNumber);
}
- pull_varattnos((Node *) indexInfo->ii_Expressions, 1, &index_attrs);
- pull_varattnos((Node *) indexInfo->ii_Predicate, 1, &index_attrs);
+ pull_varattnos((Node *) indexInfo->ii_Expressions, 1, &detoast_index_attrs);
+ pull_varattnos((Node *) indexInfo->ii_Predicate, 1, &detoast_index_attrs);
+
+ /*
+ * Post-process the attribute bitmap.
+ *
+ * We remove all non-varlena attributes (we don't need to check them
+ * during detoasting), and add all varlena attributes if the index
+ * contains a whole-row expression.
+ */
+ if (bms_is_member(-FirstLowInvalidHeapAttributeNumber, detoast_index_attrs))
+ {
+ TupleDesc desc = RelationGetDescr(heapRelation);
+
+ for (AttrNumber i = RelationGetNumberOfAttributes(heapRelation); i > 0; i--)
+ {
+ AttrNumber offset = i - FirstLowInvalidHeapAttributeNumber;
+ CompactAttribute *att = TupleDescCompactAttr(desc, i - 1);
+
+ /*
+ * If the attribute is varlena, add it to the map, else remove
+ * the attribute.
+ * We work backwards to avoid reallocations.
+ */
+ if (att->attlen == -1)
+ detoast_index_attrs = bms_add_member(detoast_index_attrs, offset);
+ else
+ detoast_index_attrs = bms_del_member(detoast_index_attrs, offset);
+ }
+
+ detoast_index_attrs = bms_del_member(detoast_index_attrs, -FirstLowInvalidHeapAttributeNumber);
+ }
+ else
+ {
+ TupleDesc desc = RelationGetDescr(heapRelation);
+
+ for (AttrNumber i = RelationGetNumberOfAttributes(heapRelation); i > 0; i--)
+ {
+ AttrNumber offset = i - FirstLowInvalidHeapAttributeNumber;
+ CompactAttribute *att = TupleDescCompactAttr(desc, i - 1);
+
+ /*
+ * If the attribute is not varlena, remove the attribute from
+ * tracking.
+ *
+ * We work backwards to avoid reallocations.
+ */
+ if (att->attlen != -1)
+ detoast_index_attrs = bms_del_member(detoast_index_attrs, offset);
+ }
+ }
/* Publish number of blocks to scan */
if (progress)
@@ -1375,6 +1424,7 @@ heapam_index_build_range_scan(Relation heapRelation,
while ((heapTuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
{
bool tupleIsAlive;
+ Bitmapset *detoasted_attrs = NULL;
CHECK_FOR_INTERRUPTS();
@@ -1676,36 +1726,36 @@ heapam_index_build_range_scan(Relation heapRelation,
/* Set up for predicate or expression evaluation */
ExecStoreBufferHeapTuple(heapTuple, slot, hscan->rs_cbuf);
- /*
- * In a partial index, discard tuples that don't satisfy the
- * predicate.
- */
- if (predicate != NULL)
- {
- if (!ExecQual(predicate, econtext))
- continue;
- }
-
/* For RECENTLY_DEAD tuples, pre-detoast external TOAST values. */
- if (!tupleIsAlive)
+ if (!tupleIsAlive && !bms_is_empty(detoast_index_attrs))
{
bool skip = false;
int attno;
- slot_getallattrs(slot);
+ /*
+ * Only get the attributes up to the last attribute we want to
+ * detoast.
+ */
+ attno = bms_prev_member(detoast_index_attrs, -1);
+ slot_getsomeattrs(slot, attno + FirstLowInvalidHeapAttributeNumber);
+
+ /*
+ * Iterate over the attributes which are now in tts_isnull/
+ * tts_values slots, and detoast them where needed.
+ */
attno = -1;
- while ((attno = bms_next_member(index_attrs, attno)) >= 0)
+ while ((attno = bms_next_member(detoast_index_attrs, attno)) >= 0)
{
int attnum = attno + FirstLowInvalidHeapAttributeNumber;
- Form_pg_attribute att;
if (attnum <= 0)
continue; /* system column */
- att = TupleDescAttr(RelationGetDescr(heapRelation), attnum - 1);
- if (att->attlen != -1 || att->attisdropped)
- continue;
+
+ Assert(TupleDescCompactAttr(RelationGetDescr(heapRelation), attnum - 1)->attlen == -1);
+
if (slot->tts_isnull[attnum - 1])
continue;
+
if (VARATT_IS_EXTERNAL_ONDISK(DatumGetPointer(slot->tts_values[attnum - 1])))
{
varlena *detoasted;
@@ -1717,10 +1767,37 @@ heapam_index_build_range_scan(Relation heapRelation,
skip = true;
break;
}
+
slot->tts_values[attnum - 1] = PointerGetDatum(detoasted);
+
+ detoasted_attrs = bms_add_member(detoasted_attrs, attnum);
}
}
+
if (skip)
+ {
+ attno = -1;
+
+ /* cleanup any pre-detoasted values */
+ while ((attno = bms_next_member(detoasted_attrs, attno)) != -2)
+ {
+ Assert(attno > 0);
+ pfree(DatumGetPointer(slot->tts_values[attno - 1]));
+ }
+
+ /* final cleanup of this iteration's memory */
+ bms_free(detoasted_attrs);
+ continue;
+ }
+ }
+
+ /*
+ * In a partial index, discard tuples that don't satisfy the
+ * predicate.
+ */
+ if (predicate != NULL)
+ {
+ if (!ExecQual(predicate, econtext))
continue;
}
@@ -1787,6 +1864,20 @@ heapam_index_build_range_scan(Relation heapRelation,
callback(indexRelation, &heapTuple->t_self, values, isnull,
tupleIsAlive, callback_state);
}
+
+ if (!bms_is_empty(detoasted_attrs))
+ {
+ int attno = -1;
+
+ while ((attno = bms_next_member(detoasted_attrs, attno)) != -2)
+ {
+ Assert(attno > 0);
+ pfree(DatumGetPointer(slot->tts_values[attno - 1]));
+ }
+
+ bms_free(detoasted_attrs);
+ detoasted_attrs = NULL;
+ }
}
/* Report scan progress one last time. */
diff --git a/src/backend/access/heap/heaptoast.c b/src/backend/access/heap/heaptoast.c
index ba5942a9495..ba50929b62c 100644
--- a/src/backend/access/heap/heaptoast.c
+++ b/src/backend/access/heap/heaptoast.c
@@ -740,28 +740,47 @@ heap_fetch_toast_slice(Relation toastrel, Oid valueid, int32 attrsize,
/*
* Some checks on the data we've found
*/
+
if (curchunk != expectedchunk)
+ {
+ if (flags & TOAST_MISSING_OK)
+ goto toast_broken_missing_ok;
+
ereport(ERROR,
(errcode(ERRCODE_DATA_CORRUPTED),
errmsg_internal("unexpected chunk number %d (expected %d) for toast value %u in %s",
curchunk, expectedchunk, valueid,
RelationGetRelationName(toastrel))));
+ }
+
if (curchunk > endchunk)
+ {
+ if (flags & TOAST_MISSING_OK)
+ goto toast_broken_missing_ok;
+
ereport(ERROR,
(errcode(ERRCODE_DATA_CORRUPTED),
errmsg_internal("unexpected chunk number %d (out of range %d..%d) for toast value %u in %s",
curchunk,
startchunk, endchunk, valueid,
RelationGetRelationName(toastrel))));
+ }
+
expected_size = curchunk < totalchunks - 1 ? TOAST_MAX_CHUNK_SIZE
: attrsize - ((totalchunks - 1) * TOAST_MAX_CHUNK_SIZE);
+
if (chunksize != expected_size)
+ {
+ if (flags & TOAST_MISSING_OK)
+ goto toast_broken_missing_ok;
+
ereport(ERROR,
(errcode(ERRCODE_DATA_CORRUPTED),
errmsg_internal("unexpected chunk size %d (expected %d) in chunk %d of %d for toast value %u in %s",
chunksize, expected_size,
curchunk, totalchunks, valueid,
RelationGetRelationName(toastrel))));
+ }
/*
* Copy the data into proper place in our result
@@ -787,11 +806,8 @@ heap_fetch_toast_slice(Relation toastrel, Oid valueid, int32 attrsize,
if (expectedchunk != (endchunk + 1))
{
if (flags & TOAST_MISSING_OK)
- {
- systable_endscan_ordered(toastscan);
- toast_close_indexes(toastidxs, num_indexes, AccessShareLock);
- return false;
- }
+ goto toast_broken_missing_ok;
+
ereport(ERROR,
(errcode(ERRCODE_DATA_CORRUPTED),
errmsg_internal("missing chunk number %d for toast value %u in %s",
@@ -804,4 +820,10 @@ heap_fetch_toast_slice(Relation toastrel, Oid valueid, int32 attrsize,
toast_close_indexes(toastidxs, num_indexes, AccessShareLock);
return true;
+
+toast_broken_missing_ok:
+ /* End scan and close indexes. */
+ systable_endscan_ordered(toastscan);
+ toast_close_indexes(toastidxs, num_indexes, AccessShareLock);
+ return false;
}
diff --git a/src/backend/access/table/toast_helper.c b/src/backend/access/table/toast_helper.c
index 50ce051a687..cdb0f1a2628 100644
--- a/src/backend/access/table/toast_helper.c
+++ b/src/backend/access/table/toast_helper.c
@@ -146,7 +146,7 @@ toast_tuple_init(ToastTupleContext *ttc, uint32 flags)
{
new_value = detoast_external_attr_extended(new_value);
if (new_value == NULL)
- return false;
+ goto broken_toast_missing_ok;
}
else if (att->attstorage == TYPSTORAGE_PLAIN)
new_value = detoast_attr(new_value);
@@ -172,6 +172,17 @@ toast_tuple_init(ToastTupleContext *ttc, uint32 flags)
}
return true;
+
+broken_toast_missing_ok:
+ for (; i > 0; i--)
+ {
+ if (ttc->ttc_attr[i].tai_colflags & TOASTCOL_NEEDS_FREE)
+ {
+ pfree(DatumGetPointer(ttc->ttc_values[i]));
+ ttc->ttc_attr[i].tai_colflags &= ~TOASTCOL_NEEDS_FREE;
+ }
+ }
+ return false;
}
/*
diff --git a/src/test/recovery/t/055_rewrite_stale_xmin.pl b/src/test/recovery/t/055_rewrite_stale_xmin.pl
index dad95c0cf96..fbccb5373a8 100644
--- a/src/test/recovery/t/055_rewrite_stale_xmin.pl
+++ b/src/test/recovery/t/055_rewrite_stale_xmin.pl
@@ -112,7 +112,7 @@ $toast = setup_table('rewrite_test');
create_missing_toast_state('rewrite_test', $toast);
($ret, $stdout, $stderr) = $node->psql('db_target',
- 'CREATE INDEX rewrite_test_data_idx ON rewrite_test (data)');
+ 'CREATE INDEX rewrite_test_data_idx ON rewrite_test ((rewrite_test IS NOT NULL))');
is($ret, 0, "CREATE INDEX succeeds without missing-chunk error");
unlike($stderr, qr/missing chunk/, "CREATE INDEX: no missing-chunk error");
--
2.50.1 (Apple Git-155)
v5-0001-Fix-missing-chunk-errors-during-heap-rewrites-and.patch (application/octet-stream, 40.7K) download
From 9b20b20ae569778231e7640e05b10d28251d09ae Mon Sep 17 00:00:00 2001
From: Michael Paquier <michael@paquier.xyz>
Date: Thu, 9 Jul 2026 11:46:21 +0900
Subject: [PATCH v5 1/2] Fix "missing chunk" errors during heap rewrites and
index builds
Blah, blah.
This problem has been reported recently by Alexander for REPACK, but it
is a much older issue (tested down to 9.5 for curiosity's sake, but I
suspect that it is much older than that).
XXX: This patch includes both TAP and isolation tests. We should remove
one pattern at the end.
Reported-by: Alexander Lakhin <exclusion@gmail.com>
Discussion: https://postgr.es/m/18351-f6e06364b3a2e669@postgresql.org
Discussion: https://postgr.es/m/19519-fe02d8ff679d834d@postgresql.org
---
contrib/dblink/.gitignore | 2 +
contrib/dblink/Makefile | 2 +
.../dblink/expected/rewrite_stale_xmin.out | 237 ++++++++++++++++++
contrib/dblink/meson.build | 5 +
contrib/dblink/specs/rewrite_stale_xmin.spec | 137 ++++++++++
src/backend/access/common/detoast.c | 42 +++-
src/backend/access/heap/heapam.c | 4 +-
src/backend/access/heap/heapam_handler.c | 148 ++++++++++-
src/backend/access/heap/heaptoast.c | 28 ++-
src/backend/access/heap/rewriteheap.c | 31 ++-
src/backend/access/table/toast_helper.c | 19 +-
src/include/access/detoast.h | 9 +
src/include/access/heaptoast.h | 18 +-
src/include/access/rewriteheap.h | 6 +-
src/include/access/tableam.h | 26 +-
src/include/access/toast_helper.h | 10 +-
src/test/recovery/meson.build | 1 +
src/test/recovery/t/055_rewrite_stale_xmin.pl | 124 +++++++++
18 files changed, 794 insertions(+), 55 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/recovery/t/055_rewrite_stale_xmin.pl
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..2e5a7940ea2
--- /dev/null
+++ b/contrib/dblink/expected/rewrite_stale_xmin.out
@@ -0,0 +1,237 @@
+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_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)
+
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..fe88e789f85
--- /dev/null
+++ b/contrib/dblink/specs/rewrite_stale_xmin.spec
@@ -0,0 +1,137 @@
+# Test that heap rewrites work when the rewriting backend's own xmin is
+# held back by a transaction in another database.
+
+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_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;
+}
+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);
+}
+
+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
+
+# 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
diff --git a/src/backend/access/common/detoast.c b/src/backend/access/common/detoast.c
index a6c1f3a734b..3195d77db4b 100644
--- a/src/backend/access/common/detoast.c
+++ b/src/backend/access/common/detoast.c
@@ -16,13 +16,14 @@
#include "access/detoast.h"
#include "access/table.h"
#include "access/tableam.h"
+#include "access/toast_helper.h"
#include "access/toast_internals.h"
#include "common/int.h"
#include "common/pg_lzcompress.h"
#include "utils/expandeddatum.h"
#include "utils/rel.h"
-static varlena *toast_fetch_datum(varlena *attr);
+static varlena *toast_fetch_datum(varlena *attr, uint32 flags);
static varlena *toast_fetch_datum_slice(varlena *attr,
int32 sliceoffset,
int32 slicelength);
@@ -51,7 +52,7 @@ detoast_external_attr(varlena *attr)
/*
* This is an external stored plain value
*/
- result = toast_fetch_datum(attr);
+ result = toast_fetch_datum(attr, 0);
}
else if (VARATT_IS_EXTERNAL_INDIRECT(attr))
{
@@ -102,6 +103,23 @@ detoast_external_attr(varlena *attr)
}
+/* ----------
+ * detoast_external_attr_extended -
+ *
+ * Like detoast_external_attr, but returns NULL if toast chunks are
+ * missing for external pointers.
+ * ----------
+ */
+varlena *
+detoast_external_attr_extended(varlena *attr)
+{
+ if (VARATT_IS_EXTERNAL_ONDISK(attr))
+ return toast_fetch_datum(attr, TOAST_MISSING_OK);
+ else
+ return detoast_external_attr(attr);
+}
+
+
/* ----------
* detoast_attr -
*
@@ -120,7 +138,7 @@ detoast_attr(varlena *attr)
/*
* This is an externally stored datum --- fetch it back from there
*/
- attr = toast_fetch_datum(attr);
+ attr = toast_fetch_datum(attr, 0);
/* If it's compressed, decompress it */
if (VARATT_IS_COMPRESSED(attr))
{
@@ -262,7 +280,7 @@ detoast_attr_slice(varlena *attr,
preslice = toast_fetch_datum_slice(attr, 0, max_size);
}
else
- preslice = toast_fetch_datum(attr);
+ preslice = toast_fetch_datum(attr, 0);
}
else if (VARATT_IS_EXTERNAL_INDIRECT(attr))
{
@@ -337,10 +355,12 @@ detoast_attr_slice(varlena *attr,
*
* Reconstruct an in memory Datum from the chunks saved
* in the toast relation
+ *
+ * If flags uses TOAST_MISSING_OK, returns NULL when chunks are missing.
* ----------
*/
static varlena *
-toast_fetch_datum(varlena *attr)
+toast_fetch_datum(varlena *attr, uint32 flags)
{
Relation toastrel;
varlena *result;
@@ -372,8 +392,14 @@ toast_fetch_datum(varlena *attr)
toastrel = table_open(toast_pointer.va_toastrelid, AccessShareLock);
/* Fetch all chunks */
- table_relation_fetch_toast_slice(toastrel, toast_pointer.va_valueid,
- attrsize, 0, attrsize, result);
+ if (!table_relation_fetch_toast_slice(toastrel, toast_pointer.va_valueid,
+ attrsize, 0, attrsize, result,
+ flags))
+ {
+ pfree(result);
+ table_close(toastrel, AccessShareLock);
+ return NULL;
+ }
/* Close toast table */
table_close(toastrel, AccessShareLock);
@@ -454,7 +480,7 @@ toast_fetch_datum_slice(varlena *attr, int32 sliceoffset,
/* Fetch all chunks */
table_relation_fetch_toast_slice(toastrel, toast_pointer.va_valueid,
attrsize, sliceoffset, slicelength,
- result);
+ result, 0);
/* Close toast table */
table_close(toastrel, AccessShareLock);
diff --git a/src/backend/access/heap/heapam.c b/src/backend/access/heap/heapam.c
index 8b488cfd8f6..e58c3ea0328 100644
--- a/src/backend/access/heap/heapam.c
+++ b/src/backend/access/heap/heapam.c
@@ -2262,7 +2262,7 @@ heap_prepare_insert(Relation relation, HeapTuple tup, TransactionId xid,
return tup;
}
else if (HeapTupleHasExternal(tup) || tup->t_len > TOAST_TUPLE_THRESHOLD)
- return heap_toast_insert_or_update(relation, tup, NULL, options);
+ return heap_toast_insert_or_update(relation, tup, NULL, options, 0);
else
return tup;
}
@@ -3962,7 +3962,7 @@ l2:
if (need_toast)
{
/* Note we always use WAL and FSM during updates */
- heaptup = heap_toast_insert_or_update(relation, newtup, &oldtup, 0);
+ heaptup = heap_toast_insert_or_update(relation, newtup, &oldtup, 0, 0);
newtupsize = MAXALIGN(heaptup->t_len);
}
else
diff --git a/src/backend/access/heap/heapam_handler.c b/src/backend/access/heap/heapam_handler.c
index bf87430cf01..e900ea0c067 100644
--- a/src/backend/access/heap/heapam_handler.c
+++ b/src/backend/access/heap/heapam_handler.c
@@ -19,6 +19,7 @@
*/
#include "postgres.h"
+#include "access/detoast.h"
#include "access/genam.h"
#include "access/heapam.h"
#include "access/heaptoast.h"
@@ -26,6 +27,7 @@
#include "access/rewriteheap.h"
#include "access/syncscan.h"
#include "access/tableam.h"
+#include "access/toast_helper.h"
#include "access/tsmapi.h"
#include "access/visibilitymap.h"
#include "access/xact.h"
@@ -36,6 +38,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"
@@ -48,9 +51,11 @@
#include "utils/rel.h"
#include "utils/tuplesort.h"
-static void reform_and_rewrite_tuple(HeapTuple tuple,
+/* See toast_helper.h for values of "flags" */
+static bool reform_and_rewrite_tuple(HeapTuple tuple,
Relation OldHeap, Relation NewHeap,
- Datum *values, bool *isnull, RewriteState rwstate);
+ Datum *values, bool *isnull, RewriteState rwstate,
+ uint32 flags);
static void heap_insert_for_repack(HeapTuple tuple, Relation OldHeap,
Relation NewHeap, Datum *values, bool *isnull,
BulkInsertState bistate);
@@ -711,6 +716,7 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,
HeapTuple tuple;
Buffer buf;
bool isdead;
+ bool recently_dead = false;
CHECK_FOR_INTERRUPTS();
@@ -796,6 +802,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 */
@@ -829,6 +836,7 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,
RelationGetRelationName(OldHeap));
/* treat as recently dead */
*tups_recently_dead += 1;
+ recently_dead = true;
isdead = false;
break;
default:
@@ -857,6 +865,45 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,
*num_tuples += 1;
if (tuplesort != NULL)
{
+ /*
+ * For RECENTLY_DEAD tuples, verify TOAST data is still available
+ * before putting the tuple in the sort. If a concurrent VACUUM
+ * already reclaimed it, skip the tuple.
+ */
+ if (recently_dead)
+ {
+ bool skip = false;
+
+ heap_deform_tuple(tuple, oldTupDesc, values, isnull);
+ for (int i = 0; i < oldTupDesc->natts; i++)
+ {
+ Form_pg_attribute att = TupleDescAttr(oldTupDesc, i);
+ varlena *d;
+
+ if (att->attlen != -1 || att->attisdropped)
+ continue;
+ if (isnull[i])
+ continue;
+ if (!VARATT_IS_EXTERNAL_ONDISK(DatumGetPointer(values[i])))
+ continue;
+ d = detoast_external_attr_extended(
+ (varlena *) DatumGetPointer(values[i]));
+ if (d == NULL)
+ {
+ skip = true;
+ break;
+ }
+ pfree(d);
+ }
+ if (skip)
+ {
+ *num_tuples -= 1;
+ *tups_vacuumed += 1;
+ *tups_recently_dead -= 1;
+ continue;
+ }
+ }
+
tuplesort_putheaptuple(tuplesort, tuple);
/*
@@ -875,8 +922,22 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,
int64 ct_val[2];
if (!concurrent)
- reform_and_rewrite_tuple(tuple, OldHeap, NewHeap,
- values, isnull, rwstate);
+ {
+ if (!reform_and_rewrite_tuple(tuple, OldHeap, NewHeap,
+ values, isnull, rwstate,
+ recently_dead ? TOAST_MISSING_OK : 0))
+ {
+ /*
+ * Missing TOAST chunks for a recently-dead tuple. Treat
+ * it as dead.
+ */
+ *tups_vacuumed += 1;
+ *num_tuples -= 1;
+ if (recently_dead)
+ *tups_recently_dead -= 1;
+ continue;
+ }
+ }
else
heap_insert_for_repack(tuple, OldHeap, NewHeap,
values, isnull, bistate);
@@ -928,10 +989,12 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,
n_tuples += 1;
if (!concurrent)
- reform_and_rewrite_tuple(tuple,
- OldHeap, NewHeap,
- values, isnull,
- rwstate);
+ {
+ (void) reform_and_rewrite_tuple(tuple,
+ OldHeap, NewHeap,
+ values, isnull,
+ rwstate, 0);
+ }
else
heap_insert_for_repack(tuple, OldHeap, NewHeap,
values, isnull, bistate);
@@ -1163,6 +1226,7 @@ heapam_index_build_range_scan(Relation heapRelation,
BlockNumber previous_blkno = InvalidBlockNumber;
BlockNumber root_blkno = InvalidBlockNumber;
OffsetNumber root_offsets[MaxHeapTuplesPerPage];
+ Bitmapset *index_attrs = NULL;
/*
* sanity checks
@@ -1259,6 +1323,21 @@ heapam_index_build_range_scan(Relation heapRelation,
!TransactionIdIsValid(OldestXmin));
Assert(snapshot == SnapshotAny || !anyvisible);
+ /*
+ * Extract the set of attributes an index may need to detoast, including
+ * expressions and predicates.
+ */
+ for (int i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
+ {
+ int attnum = indexInfo->ii_IndexAttrNumbers[i];
+
+ if (attnum != 0)
+ index_attrs = bms_add_member(index_attrs,
+ attnum - FirstLowInvalidHeapAttributeNumber);
+ }
+ pull_varattnos((Node *) indexInfo->ii_Expressions, 1, &index_attrs);
+ pull_varattnos((Node *) indexInfo->ii_Predicate, 1, &index_attrs);
+
/* Publish number of blocks to scan */
if (progress)
{
@@ -1607,6 +1686,44 @@ heapam_index_build_range_scan(Relation heapRelation,
continue;
}
+ /* For RECENTLY_DEAD tuples, pre-detoast external TOAST values. */
+ if (!tupleIsAlive)
+ {
+ bool skip = false;
+ int attno;
+
+ slot_getallattrs(slot);
+ attno = -1;
+ while ((attno = bms_next_member(index_attrs, attno)) >= 0)
+ {
+ int attnum = attno + FirstLowInvalidHeapAttributeNumber;
+ Form_pg_attribute att;
+
+ if (attnum <= 0)
+ continue; /* system column */
+ att = TupleDescAttr(RelationGetDescr(heapRelation), attnum - 1);
+ if (att->attlen != -1 || att->attisdropped)
+ continue;
+ if (slot->tts_isnull[attnum - 1])
+ continue;
+ if (VARATT_IS_EXTERNAL_ONDISK(DatumGetPointer(slot->tts_values[attnum - 1])))
+ {
+ varlena *detoasted;
+
+ detoasted = detoast_external_attr_extended(
+ (varlena *) DatumGetPointer(slot->tts_values[attnum - 1]));
+ if (detoasted == NULL)
+ {
+ skip = true;
+ break;
+ }
+ slot->tts_values[attnum - 1] = PointerGetDatum(detoasted);
+ }
+ }
+ if (skip)
+ continue;
+ }
+
/*
* For the current heap tuple, extract all the attributes we use in
* this index, and note which are null. This also performs evaluation
@@ -2341,20 +2458,29 @@ heapam_scan_sample_next_tuple(TableScanDesc scan, SampleScanState *scanstate,
* SET WITHOUT OIDS.
*
* So, we must reconstruct the tuple from component Datums.
+ *
+ * Returns true on success, and false on failure if flags uses
+ * TOAST_MISSING_OK. See toast_helper.h.
*/
-static void
+static bool
reform_and_rewrite_tuple(HeapTuple tuple,
Relation OldHeap, Relation NewHeap,
- Datum *values, bool *isnull, RewriteState rwstate)
+ Datum *values, bool *isnull, RewriteState rwstate,
+ uint32 flags)
{
HeapTuple newtuple;
newtuple = reform_tuple(tuple, OldHeap, NewHeap, values, isnull);
/* The heap rewrite module does the rest */
- rewrite_heap_tuple(rwstate, tuple, newtuple);
+ if (!rewrite_heap_tuple(rwstate, tuple, newtuple, flags))
+ {
+ heap_freetuple(newtuple);
+ return false;
+ }
heap_freetuple(newtuple);
+ return true;
}
/*
diff --git a/src/backend/access/heap/heaptoast.c b/src/backend/access/heap/heaptoast.c
index 03f885a25b0..ba5942a9495 100644
--- a/src/backend/access/heap/heaptoast.c
+++ b/src/backend/access/heap/heaptoast.c
@@ -84,9 +84,10 @@ heap_toast_delete(Relation rel, HeapTuple oldtup, bool is_speculative)
* newtup: the candidate new tuple to be inserted
* oldtup: the old row version for UPDATE, or NULL for INSERT
* options: options to be passed to heap_insert() for toast rows
+ * flags: additional control flags, see heaptoast.h.
* Result:
- * either newtup if no toasting is needed, or a palloc'd modified tuple
- * that is what should actually get stored
+ * either newtup if no toasting is needed, a palloc'd modified tuple
+ * that is what should actually get stored, or NULL.
*
* NOTE: neither newtup nor oldtup will be modified. This is a change
* from the pre-8.1 API of this routine.
@@ -94,7 +95,7 @@ heap_toast_delete(Relation rel, HeapTuple oldtup, bool is_speculative)
*/
HeapTuple
heap_toast_insert_or_update(Relation rel, HeapTuple newtup, HeapTuple oldtup,
- uint32 options)
+ uint32 options, uint32 flags)
{
HeapTuple result_tuple;
TupleDesc tupleDesc;
@@ -154,7 +155,8 @@ heap_toast_insert_or_update(Relation rel, HeapTuple newtup, HeapTuple oldtup,
ttc.ttc_oldisnull = toast_oldisnull;
}
ttc.ttc_attr = toast_attr;
- toast_tuple_init(&ttc);
+ if (!toast_tuple_init(&ttc, flags))
+ return NULL;
/* ----------
* Compress and/or save external until data fits into target length
@@ -621,11 +623,15 @@ toast_build_flattened_tuple(TupleDesc tupleDesc,
* sliceoffset is the byte offset within the TOAST value from which to fetch.
* slicelength is the number of bytes to be fetched from the TOAST value.
* result is the varlena into which the results should be written.
+ * flags records more options, see toast_helper.h.
+ *
+ * Returns true on success, or false if flags uses TOAST_MISSING_OK and
+ * chunks are missing rather than raising an error.
*/
-void
+bool
heap_fetch_toast_slice(Relation toastrel, Oid valueid, int32 attrsize,
int32 sliceoffset, int32 slicelength,
- varlena *result)
+ varlena *result, uint32 flags)
{
Relation *toastidxs;
ScanKeyData toastkey[3];
@@ -779,13 +785,23 @@ heap_fetch_toast_slice(Relation toastrel, Oid valueid, int32 attrsize,
* Final checks that we successfully fetched the datum
*/
if (expectedchunk != (endchunk + 1))
+ {
+ if (flags & TOAST_MISSING_OK)
+ {
+ systable_endscan_ordered(toastscan);
+ toast_close_indexes(toastidxs, num_indexes, AccessShareLock);
+ return false;
+ }
ereport(ERROR,
(errcode(ERRCODE_DATA_CORRUPTED),
errmsg_internal("missing chunk number %d for toast value %u in %s",
expectedchunk, valueid,
RelationGetRelationName(toastrel))));
+ }
/* End scan and close indexes. */
systable_endscan_ordered(toastscan);
toast_close_indexes(toastidxs, num_indexes, AccessShareLock);
+
+ return true;
}
diff --git a/src/backend/access/heap/rewriteheap.c b/src/backend/access/heap/rewriteheap.c
index 0648e433031..c68333ed03f 100644
--- a/src/backend/access/heap/rewriteheap.c
+++ b/src/backend/access/heap/rewriteheap.c
@@ -211,7 +211,8 @@ typedef struct RewriteMappingDataEntry
/* prototypes for internal functions */
-static void raw_heap_insert(RewriteState state, HeapTuple tup);
+static bool raw_heap_insert(RewriteState state, HeapTuple tup,
+ uint32 flags);
/* internal logical remapping prototypes */
static void logical_begin_heap_rewrite(RewriteState state);
@@ -309,7 +310,7 @@ end_heap_rewrite(RewriteState state)
while ((unresolved = hash_seq_search(&seq_status)) != NULL)
{
ItemPointerSetInvalid(&unresolved->tuple->t_data->t_ctid);
- raw_heap_insert(state, unresolved->tuple);
+ raw_heap_insert(state, unresolved->tuple, 0);
}
/* Write the last page, if any */
@@ -338,9 +339,10 @@ end_heap_rewrite(RewriteState state)
* old_tuple original tuple in the old heap
* new_tuple new, rewritten tuple to be inserted to new heap
*/
-void
+bool
rewrite_heap_tuple(RewriteState state,
- HeapTuple old_tuple, HeapTuple new_tuple)
+ HeapTuple old_tuple, HeapTuple new_tuple,
+ uint32 flags)
{
MemoryContext old_cxt;
ItemPointerData old_tid;
@@ -437,7 +439,7 @@ rewrite_heap_tuple(RewriteState state,
* tuple will be written.
*/
MemoryContextSwitchTo(old_cxt);
- return;
+ return true;
}
}
@@ -455,7 +457,13 @@ rewrite_heap_tuple(RewriteState state,
ItemPointerData new_tid;
/* Insert the tuple and find out where it's put in new_heap */
- raw_heap_insert(state, new_tuple);
+ if (!raw_heap_insert(state, new_tuple, flags))
+ {
+ if (free_new)
+ heap_freetuple(new_tuple);
+ MemoryContextSwitchTo(old_cxt);
+ return false;
+ }
new_tid = new_tuple->t_self;
logical_rewrite_heap_tuple(state, old_tid, new_tuple);
@@ -532,6 +540,7 @@ rewrite_heap_tuple(RewriteState state,
}
MemoryContextSwitchTo(old_cxt);
+ return true;
}
/*
@@ -593,8 +602,8 @@ rewrite_heap_dead_tuple(RewriteState state, HeapTuple old_tuple)
* tuple is invalid on entry, it's replaced with the new TID as well (in
* the inserted data only, not in the caller's copy).
*/
-static void
-raw_heap_insert(RewriteState state, HeapTuple tup)
+static bool
+raw_heap_insert(RewriteState state, HeapTuple tup, uint32 flags)
{
Page page;
Size pageFreeSpace,
@@ -628,7 +637,9 @@ raw_heap_insert(RewriteState state, HeapTuple tup)
options |= HEAP_INSERT_NO_LOGICAL;
heaptup = heap_toast_insert_or_update(state->rs_new_rel, tup, NULL,
- options);
+ options, flags);
+ if (heaptup == NULL)
+ return false;
}
else
heaptup = tup;
@@ -702,6 +713,8 @@ raw_heap_insert(RewriteState state, HeapTuple tup)
/* If heaptup is a private copy, release it. */
if (heaptup != tup)
heap_freetuple(heaptup);
+
+ return true;
}
/* ------------------------------------------------------------------------
diff --git a/src/backend/access/table/toast_helper.c b/src/backend/access/table/toast_helper.c
index 2f2022d9951..50ce051a687 100644
--- a/src/backend/access/table/toast_helper.c
+++ b/src/backend/access/table/toast_helper.c
@@ -36,9 +36,13 @@
* toast_flags is just a single uint8, but toast_attr is a caller-provided
* array with a length equal to tupleDesc->natts. The caller need not
* perform any initialization of the array before calling this function.
+ *
+ * If flags uses TOAST_MISSING_OK and an external TOAST value cannot be
+ * fetched, returns false instead of raising an error. Returns true on
+ * success. See toast_helper.h.
*/
-void
-toast_tuple_init(ToastTupleContext *ttc)
+bool
+toast_tuple_init(ToastTupleContext *ttc, uint32 flags)
{
TupleDesc tupleDesc = ttc->ttc_rel->rd_att;
int numAttrs = tupleDesc->natts;
@@ -137,7 +141,14 @@ toast_tuple_init(ToastTupleContext *ttc)
if (VARATT_IS_EXTERNAL(new_value))
{
ttc->ttc_attr[i].tai_oldexternal = new_value;
- if (att->attstorage == TYPSTORAGE_PLAIN)
+ if ((flags & TOAST_MISSING_OK) != 0 &&
+ VARATT_IS_EXTERNAL_ONDISK(new_value))
+ {
+ new_value = detoast_external_attr_extended(new_value);
+ if (new_value == NULL)
+ return false;
+ }
+ else if (att->attstorage == TYPSTORAGE_PLAIN)
new_value = detoast_attr(new_value);
else
new_value = detoast_external_attr(new_value);
@@ -159,6 +170,8 @@ toast_tuple_init(ToastTupleContext *ttc)
ttc->ttc_attr[i].tai_colflags |= TOASTCOL_IGNORE;
}
}
+
+ return true;
}
/*
diff --git a/src/include/access/detoast.h b/src/include/access/detoast.h
index fbd98181a3a..c5eeed04b01 100644
--- a/src/include/access/detoast.h
+++ b/src/include/access/detoast.h
@@ -43,6 +43,15 @@ do { \
*/
extern varlena *detoast_external_attr(varlena *attr);
+/* ----------
+ * detoast_external_attr_extended() -
+ *
+ * Like detoast_external_attr, but returns NULL if toast chunks
+ * are missing (instead of raising an error).
+ * ----------
+ */
+extern varlena *detoast_external_attr_extended(varlena *attr);
+
/* ----------
* detoast_attr() -
*
diff --git a/src/include/access/heaptoast.h b/src/include/access/heaptoast.h
index 631cb1836b9..bc4087b3c95 100644
--- a/src/include/access/heaptoast.h
+++ b/src/include/access/heaptoast.h
@@ -91,11 +91,15 @@
/* ----------
* heap_toast_insert_or_update -
*
- * Called by heap_insert() and heap_update().
+ * Called by heap_insert() and heap_update(). Returns NULL if the
+ * insert/update could not be completed.
+ *
+ * See toast_helper.h for the values of "flags".
* ----------
*/
extern HeapTuple heap_toast_insert_or_update(Relation rel, HeapTuple newtup,
- HeapTuple oldtup, uint32 options);
+ HeapTuple oldtup, uint32 options,
+ uint32 flags);
/* ----------
* heap_toast_delete -
@@ -139,11 +143,15 @@ extern HeapTuple toast_build_flattened_tuple(TupleDesc tupleDesc,
/* ----------
* heap_fetch_toast_slice
*
- * Fetch a slice from a toast value stored in a heap table.
+ * Fetch a slice from a toast value stored in a heap table. Returns
+ * false if the slice could not be fetched, otherwise true on success.
+ *
+ * See toast_helper.h for the values of "flags".
* ----------
*/
-extern void heap_fetch_toast_slice(Relation toastrel, Oid valueid,
+extern bool heap_fetch_toast_slice(Relation toastrel, Oid valueid,
int32 attrsize, int32 sliceoffset,
- int32 slicelength, varlena *result);
+ int32 slicelength, varlena *result,
+ uint32 flags);
#endif /* HEAPTOAST_H */
diff --git a/src/include/access/rewriteheap.h b/src/include/access/rewriteheap.h
index 6ccf7b45c04..09110f6337a 100644
--- a/src/include/access/rewriteheap.h
+++ b/src/include/access/rewriteheap.h
@@ -25,8 +25,10 @@ extern RewriteState begin_heap_rewrite(Relation old_heap, Relation new_heap,
TransactionId oldest_xmin, TransactionId freeze_xid,
MultiXactId cutoff_multi);
extern void end_heap_rewrite(RewriteState state);
-extern void rewrite_heap_tuple(RewriteState state, HeapTuple old_tuple,
- HeapTuple new_tuple);
+
+/* See toast_helper.h for the values of "flags" */
+extern bool rewrite_heap_tuple(RewriteState state, HeapTuple old_tuple,
+ HeapTuple new_tuple, uint32 flags);
extern bool rewrite_heap_dead_tuple(RewriteState state, HeapTuple old_tuple);
/*
diff --git a/src/include/access/tableam.h b/src/include/access/tableam.h
index f2c36696bca..707baf804e3 100644
--- a/src/include/access/tableam.h
+++ b/src/include/access/tableam.h
@@ -782,12 +782,17 @@ typedef struct TableAmRoutine
* This callback is invoked when detoasting a value stored in a toast
* table implemented by this AM. See table_relation_fetch_toast_slice()
* for more details.
+ *
+ * If TOAST_MISSING_OK is set in flags, returns false when chunks are
+ * missing instead of raising an error. Returns true on success. See
+ * toast_helper.h for possible values of "flags".
*/
- void (*relation_fetch_toast_slice) (Relation toastrel, Oid valueid,
+ bool (*relation_fetch_toast_slice) (Relation toastrel, Oid valueid,
int32 attrsize,
int32 sliceoffset,
int32 slicelength,
- varlena *result);
+ varlena *result,
+ uint32 flags);
/* ------------------------------------------------------------------------
@@ -1981,16 +1986,21 @@ table_relation_toast_am(Relation rel)
*
* result is caller-allocated space into which the fetched bytes should be
* stored.
+ *
+ * flags: if TOAST_MISSING_OK is set, return false when toast chunks are
+ * missing instead of raising an error. Returns true on success. See
+ * also toast_helper.h.
*/
-static inline void
+static inline bool
table_relation_fetch_toast_slice(Relation toastrel, Oid valueid,
int32 attrsize, int32 sliceoffset,
- int32 slicelength, varlena *result)
+ int32 slicelength, varlena *result,
+ uint32 flags)
{
- toastrel->rd_tableam->relation_fetch_toast_slice(toastrel, valueid,
- attrsize,
- sliceoffset, slicelength,
- result);
+ return toastrel->rd_tableam->relation_fetch_toast_slice(toastrel, valueid,
+ attrsize,
+ sliceoffset, slicelength,
+ result, flags);
}
diff --git a/src/include/access/toast_helper.h b/src/include/access/toast_helper.h
index 2ec92397f26..4abebe82798 100644
--- a/src/include/access/toast_helper.h
+++ b/src/include/access/toast_helper.h
@@ -101,7 +101,15 @@ typedef struct
#define TOASTCOL_IGNORE 0x0010
#define TOASTCOL_INCOMPRESSIBLE 0x0020
-extern void toast_tuple_init(ToastTupleContext *ttc);
+/*
+ * Flags for TOAST fetch operations.
+ *
+ * TOAST_MISSING_OK, when set, means that a TOAST fetch tolerates missing
+ * chunks and returns a failure state instead of raising an error.
+ */
+#define TOAST_MISSING_OK (1 << 1)
+
+extern bool toast_tuple_init(ToastTupleContext *ttc, uint32 flags);
extern int toast_tuple_find_biggest_attribute(ToastTupleContext *ttc,
bool for_compression,
bool check_main);
diff --git a/src/test/recovery/meson.build b/src/test/recovery/meson.build
index ad0d85f4189..7e583ee39a1 100644
--- a/src/test/recovery/meson.build
+++ b/src/test/recovery/meson.build
@@ -63,6 +63,7 @@ tests += {
't/052_checkpoint_segment_missing.pl',
't/053_standby_login_event_trigger.pl',
't/054_unlogged_sequence_promotion.pl',
+ 't/055_rewrite_stale_xmin.pl',
],
},
}
diff --git a/src/test/recovery/t/055_rewrite_stale_xmin.pl b/src/test/recovery/t/055_rewrite_stale_xmin.pl
new file mode 100644
index 00000000000..dad95c0cf96
--- /dev/null
+++ b/src/test/recovery/t/055_rewrite_stale_xmin.pl
@@ -0,0 +1,124 @@
+# Copyright (c) 2025-2026, PostgreSQL Global Development Group
+#
+# Test that heap rewrites (CLUSTER, VACUUM FULL, REPACK) and index builds
+# work in the case when the backend's own xmin is held back by a transaction
+# in another database.
+
+use strict;
+use warnings;
+use PostgreSQL::Test::Cluster;
+use Test::More;
+
+my $node = PostgreSQL::Test::Cluster->new('primary');
+$node->init;
+# No Autovacuum, no random interferences.
+$node->append_conf(
+ 'postgresql.conf', qq[
+autovacuum = off
+]);
+$node->start;
+
+# Create two databases.
+$node->safe_psql('postgres', 'CREATE DATABASE db_holder');
+$node->safe_psql('postgres', 'CREATE DATABASE db_target');
+
+# Set up a table with TOAST data. Returns the toast table name.
+sub setup_table
+{
+ my ($tblname, $extra_ddl) = @_;
+ $extra_ddl //= '';
+
+ $node->safe_psql(
+ 'db_target', qq{
+ DROP TABLE IF EXISTS $tblname;
+ CREATE TABLE $tblname (id int PRIMARY KEY, data text)
+ WITH (autovacuum_enabled = off);
+ ALTER TABLE $tblname ALTER COLUMN data SET STORAGE EXTERNAL;
+ INSERT INTO $tblname VALUES (1, repeat('x', 2500));
+ INSERT INTO $tblname VALUES (2, repeat('z', 2500));
+ $extra_ddl
+ });
+
+ my $toast = $node->safe_psql(
+ 'db_target', qq{
+ SELECT 'pg_toast.' || relname FROM pg_class
+ WHERE oid = (SELECT reltoastrelid FROM pg_class
+ WHERE relname = '$tblname');
+ });
+ chomp $toast;
+ return $toast;
+}
+
+# Create precondition state. Requires that $holder is already running with
+# a write XID.
+sub create_missing_toast_state
+{
+ my ($tblname, $toast_table) = @_;
+
+ # Hold xmin in same DB to prevent main tuple removal.
+ my $xmin_holder = $node->background_psql('db_target', on_error_stop => 1);
+ $xmin_holder->query_safe("BEGIN ISOLATION LEVEL REPEATABLE READ");
+ $xmin_holder->query_safe("SELECT 1");
+
+ # Delete the row with TOAST data.
+ $node->safe_psql('db_target', "DELETE FROM $tblname WHERE id = 1");
+
+ # VACUUM main table only. The xmin_holder keeps the dead tuple.
+ $node->safe_psql('db_target', "VACUUM (PROCESS_TOAST false) $tblname");
+
+ # Release same-DB xmin.
+ $xmin_holder->query_safe("COMMIT");
+ $xmin_holder->quit;
+
+ # Vacuum toast table: toast chunks now DEAD and removed.
+ $node->safe_psql('db_target', "VACUUM $toast_table");
+}
+
+# Open a transaction holding an XID before any deletes. This XID will hold
+# back GetSnapshotData() globally, on a different database than the one
+# running the various rewrite operations.
+my $holder = $node->background_psql('db_holder', on_error_stop => 1);
+$holder->query_safe("BEGIN");
+$holder->query_safe("CREATE TEMP TABLE xid_holder(x int)");
+
+# Test 1: CLUSTER
+my $toast = setup_table('rewrite_test');
+create_missing_toast_state('rewrite_test', $toast);
+
+my ($ret, $stdout, $stderr) =
+ $node->psql('db_target', 'CLUSTER rewrite_test USING rewrite_test_pkey');
+is($ret, 0, "CLUSTER succeeds without missing-chunk error");
+unlike($stderr, qr/missing chunk/, "CLUSTER: no missing-chunk error");
+
+# Test 2: VACUUM FULL
+$toast = setup_table('rewrite_test');
+create_missing_toast_state('rewrite_test', $toast);
+
+($ret, $stdout, $stderr) =
+ $node->psql('db_target', 'VACUUM FULL rewrite_test');
+is($ret, 0, "VACUUM FULL succeeds without missing-chunk error");
+unlike($stderr, qr/missing chunk/, "VACUUM FULL: no missing-chunk error");
+
+# Test 3: REPACK
+$toast = setup_table('rewrite_test');
+create_missing_toast_state('rewrite_test', $toast);
+
+($ret, $stdout, $stderr) = $node->psql('db_target', 'REPACK rewrite_test');
+is($ret, 0, "REPACK succeeds without missing-chunk error");
+unlike($stderr, qr/missing chunk/, "REPACK: no missing-chunk error");
+
+# Test 4: CREATE INDEX on toasted column
+$toast = setup_table('rewrite_test');
+create_missing_toast_state('rewrite_test', $toast);
+
+($ret, $stdout, $stderr) = $node->psql('db_target',
+ 'CREATE INDEX rewrite_test_data_idx ON rewrite_test (data)');
+is($ret, 0, "CREATE INDEX succeeds without missing-chunk error");
+unlike($stderr, qr/missing chunk/, "CREATE INDEX: no missing-chunk error");
+
+# Cleanup.
+$holder->query_safe("COMMIT");
+$holder->quit;
+
+$node->stop;
+done_testing();
--
2.50.1 (Apple Git-155)
^ permalink raw reply [nested|flat] 33+ messages in thread
* Re: BUG #19519: REPACK can fail due to missing chunk for toast value
@ 2026-08-05 18:18 Andrey Borodin <x4mmm@yandex-team.ru>
parent: Matthias van de Meent <boekewurm+postgres@gmail.com>
1 sibling, 1 reply; 33+ messages in thread
From: Andrey Borodin @ 2026-08-05 18:18 UTC (permalink / raw)
To: Matthias van de Meent <boekewurm+postgres@gmail.com>; +Cc: Michael Paquier <michael@paquier.xyz>; Heikki Linnakangas <hlinnaka@iki.fi>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; Imran Zaheer <imran.zhir@gmail.com>; Alexander Lakhin <exclusion@gmail.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>; Konstantin Knizhnik <knizhnik@garret.ru>
> On 31 Jul 2026, at 00:54, Matthias van de Meent <boekewurm+postgres@gmail.com> wrote:
>
> <v5-0002-Various-fixes-and-adjustments.patch>
Hi hackers,
When I saw the thread referring to REPACK, I incorrectly assumed that
this was a v19 issue. I was mostly interested in fixing the older
branches, skimmed Ekaterina's thread, concluded that there was no patch
yet, and posted my test largely to bump other discussion. I now realize
that this was not useful. Sorry for the noise. I would like to review
the current patch set instead.
My main interest here is whether this can be backpatched to supported
branches. The underlying CREATE INDEX, CLUSTER, and VACUUM FULL problem
is present in 14-18, even though REPACK is new. However, changing the
return type and arguments of relation_fetch_toast_slice changes the
TableAmRoutine ABI in all those branches. So v5 cannot be backpatched as
is without breaking external table AMs. As I understand that the current
plan is to settle the fix for HEAD first and consider a separate
ABI-preserving back-branch variant afterwards.
Three issues identified in the thread remain unresolved in the posted v5
patch set:
* As Zhijie reported, TOAST_MISSING_OK is lost for tuples stored in
rs_unresolved_tups, including those inserted by end_heap_rewrite().
* As Matthias noted, the scan-and-sort path still has a check/use race
because it discards the detoasted values before putting the original
tuple into tuplesort.
* As Dilip noted, the TOAST_MISSING_OK path for a TYPSTORAGE_PLAIN
attribute uses detoast_external_attr_extended() instead of
detoast_attr(). On a successful fetch, an external compressed datum
therefore appears to remain compressed.
I think the memory-leak fix in v5-0002 misses one exit path. Detoasting
now precedes the partial index predicate, but if ExecQual() returns false,
the loop continues without freeing detoasted_attrs and the detoasted
values.
I also have a question about the concern Ekaterina raised in the related
thread regarding real corruption. With TOAST_MISSING_OK, v5-0002 also
returns false for an existing chunk with an unexpected size or a chunk
outside the requested range. Is concurrent removal expected to produce
those cases too, or could the tolerant path be limited to a missing chunk
or a gap?
The current tests do not cover TOAST being removed after a recently-dead
tuple has been checked but while it is waiting in tuplesort. Nor do they
cover a recently-dead tuple deferred in rs_unresolved_tups because its
successor in the update chain has not been rewritten yet. The latter is
covered by Zhijie's reproducer, but not by the automated test suites. I
am not sure either case needs a dedicated regression test once the code is
fixed, but both paths seem easy to break again during a future refactoring.
Thanks!
Best regards, Andrey Borodin.
^ permalink raw reply [nested|flat] 33+ messages in thread
* Re: BUG #19519: REPACK can fail due to missing chunk for toast value
@ 2026-08-23 17:12 Rui Zhao <zhaorui126@gmail.com>
parent: Matthias van de Meent <boekewurm+postgres@gmail.com>
1 sibling, 0 replies; 33+ messages in thread
From: Rui Zhao @ 2026-08-23 17:12 UTC (permalink / raw)
To: Matthias van de Meent <boekewurm+postgres@gmail.com>; +Cc: Michael Paquier <michael@paquier.xyz>; Heikki Linnakangas <hlinnaka@iki.fi>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; Imran Zaheer <imran.zhir@gmail.com>; Alexander Lakhin <exclusion@gmail.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>; Konstantin Knizhnik <knizhnik@garret.ru>
Hi,
I read the approaches this thread went through: Srinath's ForRewrite()
recomputation of the rewrite's OldestXmin, the registered non-vacuumable xmin,
and the tolerant detoast v5 implements. The last one looks right to me:
Alexander's stress runs showed the first still races, Matthias found the
second cannot be guaranteed, and a recently-dead tuple whose chunks a vacuum
already removed is dead to every snapshot, so dropping it at detoast time
loses nothing. But one shape still fails on v5: an ordinary UPDATE, followed
by VACUUM FULL or REPACK, hits "missing chunk" as before. Details and a fix
below.
The mechanics first: v5 needs one rebase step -- master took
t/055_cascade_reconnect.pl in b614de4876b, so the new TAP test has to move to
056, in the file name and in src/test/recovery/meson.build. With that, both
patches apply cleanly to master as of 9716f88ddf6; I built and tested on
db0c984b1d1. No warnings; make check, the rewrite_stale_xmin spec and the 056
TAP test pass. On the reported shape all four rewrite paths -- CREATE INDEX,
CLUSTER, VACUUM FULL, REPACK -- fail on master and pass with v5.
1) The failing shape. In rewrite_stale_xmin.spec:
- DELETE FROM rewrite_test WHERE id = 1;
+ UPDATE rewrite_test SET data = repeat('z', 2500) WHERE id = 1;
and two of its four permutations then error out:
step s3_vacuum_full:
VACUUM FULL rewrite_test;
ERROR: missing chunk number 0 for toast value 16463 in rewrite_test_toast
REPACK fails the same way; CLUSTER and CREATE INDEX pass.
The UPDATE leaves an update pair in rewrite_test: A, the old version, recently
dead, its chunks reclaimed by s3_vacuum_toast; B, the new version, live. The
scan meets A first:
/* the caller asks for tolerance: A is recently dead */
reform_and_rewrite_tuple(tuple, ...,
recently_dead ? TOAST_MISSING_OK : 0)
/* but rewrite_heap_tuple() stashes A without the flags */
unresolved->old_tid = old_tuple->t_self;
unresolved->tuple = heap_copytuple(new_tuple);
Then the scan meets B, and one rewrite_heap_tuple(..., flags = 0) call writes
both tuples:
for (;;)
{
/*
* Pass 1 writes B: flags = 0, fine, B is live.
* Pass 2 writes the stashed A, still with flags = 0: re-toasting
* A for the new heap reads its reclaimed chunks without the
* tolerance -> "missing chunk".
*/
if (!raw_heap_insert(state, new_tuple, flags))
...
if (unresolved != NULL)
{
new_tuple = unresolved->tuple;
...
/* loop back to insert the previous tuple in the chain */
continue;
Note the failure above never reaches end_heap_rewrite() -- the site Zhijie
named, rewriteheap.c:313 with its hardcoded 0: B is live and always written,
so A is resolved inside this loop. A stashed tuple reaches
end_heap_rewrite() only when its successor was never written, i.e. B was
found DEAD -- the case the header comment calls "very unusual". A fix at
:313 alone would not cover this. 0001 below adds UPDATE permutations for
both failing commands to the spec.
2) The fix has a wrinkle: the failure cannot be reported through
rewrite_heap_tuple()'s return value. The caller's failure branch runs once
per scanned tuple:
if (!reform_and_rewrite_tuple(tuple, OldHeap, NewHeap,
values, isnull, rwstate,
recently_dead ? TOAST_MISSING_OK : 0))
{
Assert(recently_dead);
/*
* Missing TOAST chunks for a recently-dead tuple. Treat
* it as dead.
*/
*tups_vacuumed += 1;
*num_tuples -= 1;
*tups_recently_dead -= 1;
continue;
}
For the update pair above it executes twice:
scanning A recently dead, so flags = TOAST_MISSING_OK -- but
rewrite_heap_tuple() only stashes A into
rs_unresolved_tups and returns true; nothing is written,
the branch does not run
scanning B live, so flags = 0; the loop writes B, finds the A
stashed one round earlier waiting in rs_unresolved_tups,
and fails writing it -- still with flags = 0
If A's failed insert just returned false, this branch would now run with
tuple = B: the Assert fires (B is not recently dead), num_tuples uncounts
the B that was in fact written, and the dropped A stays counted as kept.
The root cause is that the flags are lost at the rs_unresolved_tups stash,
so 0001 attached stores them there:
typedef struct
{
TidHashKey key; /* expected xmin/old location of B tuple */
ItemPointerData old_tid; /* A's location in the old heap */
HeapTuple tuple; /* A's tuple contents */
+ uint32 flags; /* raw_heap_insert flags A was scanned with */
} UnresolvedTupData;
writes both sites -- the loop and end_heap_rewrite() -- with them, and drops a
stashed tuple whose insert fails on the spot -- the treatment this branch
gives its own tuple. end_heap_rewrite() reports the drops for the caller to
recount:
-extern void end_heap_rewrite(RewriteState state);
+extern double end_heap_rewrite(RewriteState state);
/* caller: dropped tuples were all recently dead -- count as vacuumed */
*tups_vacuumed += tuples_dropped;
*num_tuples -= tuples_dropped;
*tups_recently_dead -= tuples_dropped;
A tuple dropped in the loop can leave a still-older version waiting in
rs_unresolved_tups; it is written by end_heap_rewrite(), now with its own
flags, which also covers the end-of-scan case Zhijie described.
With 0001 the UPDATE permutations pass and the DELETE permutations' output is
unchanged; Zhijie's repro script from upthread, which fails the same way on
v5, completes ("found 500 removable, 500 nonremovable row versions"); make
check, the spec and the 056 TAP test stay green.
3) The leak Andrey mentioned on the ExecQual() continue path is easy to see at
scale. 800 recently-dead rows with a 391 kB external value each, CREATE INDEX
on v5: with a plain index the backend peaks at 17 MB RSS; with a partial index
whose predicate rejects every row, at 451 MB. The missing-TOAST skip path a
few lines above has the mirror problem -- it frees the values but not the
tracking set:
/* final cleanup of this iteration's memory */
bms_free(detoasted_attrs);
/* detoasted_attrs = NULL is missing -- the success path has it */
continue;
so the next recently-dead tuple calls bms_add_member() on the freed set.
0002 attached moves the cleanup into one helper called on all three exits of
the scan-loop iteration. With it the partial-index build holds one value at
a time: the backend's memory context total peaks at 1.4 MB
(pg_log_backend_memory_contexts), where v5 passes 200 MB mid-build. make
check, the spec and the 056 TAP test stay green with 0002 as well.
4) On the scan-and-sort check/use gap: for CLUSTER, VACUUM FULL and REPACK it
is already closed against VACUUM by the lock copy_table_data() takes:
/*
* If the OldHeap has a toast table, get lock on the toast table to keep
* it from being vacuumed.
...
*/
if (OldHeap->rd_rel->reltoastrelid)
LockRelationOid(OldHeap->rd_rel->reltoastrelid, lmode);
Measured on a 4.7 GB toast relation, with a VACUUM of it started from a second
session mid-command:
CLUSTER blocked, ungranted in pg_locks, until the command ends
VACUUM FULL blocked
REPACK blocked
CREATE INDEX runs to completion (it holds only detoast's
AccessShareLock on the toast relation)
So in the sort path, chunks cannot go away through a plain VACUUM between the
pre-check and the sort read-out; the index build is the path where reclamation
proceeds concurrently.
One caveat: the reclamation itself does not need a VACUUM. Once the deleting
transaction is behind the database-local horizon, any plain read of the toast
heap prunes the chunks:
-- toast page of a just-deleted row, before and after a bare
-- SELECT count(*) FROM pg_toast.<toast rel>; no VACUUM anywhere
SELECT lp, lp_flags FROM heap_page_items(get_raw_page(..., 0));
-- before: lp_flags = 1 (normal) for all six chunks
-- after: lp_flags = 3 (dead)
During these three commands the old toast is then only read by the rewriting
backend itself, and I could not turn that into a failure. Sort path forced,
620 MB of toast, rows recently dead only because of a read-only REPEATABLE
READ holder, holder exits during "writing new heap" with three seconds of
strict read-out detoasting still to go: CLUSTER completes. The reason is in
GlobalVisTestShouldUpdate():
/*
* The current heuristic is that we update only if RecentXmin has changed
* since the last update. ...
*/
/* does the last snapshot built have a different xmin? */
return RecentXmin != ComputeXidHorizonsResultLastXmin;
The rewrite builds no snapshot after computing its cutoffs, so its pruning
horizon stays where it was at command start, and its own reads cannot prune
the tuples it decided to keep. That holds unless something mid-command
builds a fresh snapshot; I have not looked for such a path.
In short, I did not find a way to trigger the sort-path race: VACUUM is
locked out for the whole command, and the rewriting backend's own reads
prune with a horizon frozen at command start.
5) One cosmetic thing: v5-0002 adds a line of only tabs at
heapam_handler.c:1741.
Thanks,
Rui
Attachments: download all (2 files, .tar.gz)
0001-Write-stashed-update-chain-tuples-with-their-own-TOA.patch (application/octet-stream, 10.8K) download
From 687708781e8f43a09a2a6bcd55b6d8cbb3b10d53 Mon Sep 17 00:00:00 2001
From: Rui Zhao <zhaorui126@gmail.com>
Date: Thu, 20 Aug 2026 00:10:23 +0800
Subject: [PATCH] Write stashed update-chain tuples with their own TOAST flags
rewrite_heap_tuple() stashes the prior version of an update pair in
rs_unresolved_tups and writes it out when the successor arrives, but
the write reused the successor's flags: a live successor resolves a
recently-dead prior version with flags = 0, and detoasting the prior
version's already-reclaimed chunks fails with "missing chunk". The
same applied to the leftovers end_heap_rewrite() writes, which passed
a hardcoded 0.
Keep the flags a tuple was scanned with in its UnresolvedTupData and
use them at both write-out sites. A failed insert of a stashed tuple
cannot be reported through rewrite_heap_tuple()'s return value -- the
caller's tuple has already been written, and the caller would adjust
the counters for the wrong tuple -- so drop the tuple on the spot and
have end_heap_rewrite() return the number of such drops, which the
caller folds into tups_vacuumed / num_tuples / tups_recently_dead.
Add UPDATE permutations for VACUUM FULL and REPACK to the
rewrite_stale_xmin isolation spec; they fail with "missing chunk"
without this fix.
---
.../dblink/expected/rewrite_stale_xmin.out | 118 ++++++++++++++++++
contrib/dblink/specs/rewrite_stale_xmin.spec | 27 ++++
src/backend/access/heap/heapam_handler.c | 15 ++-
src/backend/access/heap/rewriteheap.c | 44 ++++++-
src/include/access/rewriteheap.h | 2 +-
5 files changed, 199 insertions(+), 7 deletions(-)
diff --git a/contrib/dblink/expected/rewrite_stale_xmin.out b/contrib/dblink/expected/rewrite_stale_xmin.out
index 2e5a7940ea2..ff600edd68d 100644
--- a/contrib/dblink/expected/rewrite_stale_xmin.out
+++ b/contrib/dblink/expected/rewrite_stale_xmin.out
@@ -235,3 +235,121 @@ 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 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 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 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 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/specs/rewrite_stale_xmin.spec b/contrib/dblink/specs/rewrite_stale_xmin.spec
index fe88e789f85..b670c6b4435 100644
--- a/contrib/dblink/specs/rewrite_stale_xmin.spec
+++ b/contrib/dblink/specs/rewrite_stale_xmin.spec
@@ -65,6 +65,10 @@ 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_vacuum_main_only
{
VACUUM (PROCESS_TOAST false) rewrite_test;
@@ -135,3 +139,26 @@ permutation
s3_vacuum_toast
s3_create_index
s1_release
+
+# VACUUM FULL after an UPDATE: the prior version of the update pair reaches
+# the new heap through rs_unresolved_tups
+permutation
+ s1_hold_xmin
+ s2_begin
+ s3_update
+ s3_vacuum_main_only
+ s2_commit
+ s3_vacuum_toast
+ s3_vacuum_full
+ s1_release
+
+# REPACK after an UPDATE
+permutation
+ s1_hold_xmin
+ s2_begin
+ s3_update
+ s3_vacuum_main_only
+ s2_commit
+ s3_vacuum_toast
+ s3_repack
+ s1_release
diff --git a/src/backend/access/heap/heapam_handler.c b/src/backend/access/heap/heapam_handler.c
index 8c7a67ec3e1..0444bb53ace 100644
--- a/src/backend/access/heap/heapam_handler.c
+++ b/src/backend/access/heap/heapam_handler.c
@@ -1009,7 +1009,20 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,
/* Write out any remaining tuples, and fsync if needed */
if (rwstate)
- end_heap_rewrite(rwstate);
+ {
+ double tuples_dropped;
+
+ tuples_dropped = end_heap_rewrite(rwstate);
+
+ /*
+ * Tuples the rewrite dropped because their TOAST data was already
+ * reclaimed were all scanned as recently dead: count them as
+ * vacuumed instead.
+ */
+ *tups_vacuumed += tuples_dropped;
+ *num_tuples -= tuples_dropped;
+ *tups_recently_dead -= tuples_dropped;
+ }
if (bistate)
FreeBulkInsertState(bistate);
diff --git a/src/backend/access/heap/rewriteheap.c b/src/backend/access/heap/rewriteheap.c
index c68333ed03f..467a9f8d089 100644
--- a/src/backend/access/heap/rewriteheap.c
+++ b/src/backend/access/heap/rewriteheap.c
@@ -149,6 +149,8 @@ typedef struct RewriteStateData
XLogRecPtr rs_begin_lsn; /* XLogInsertLsn when starting the rewrite */
HTAB *rs_unresolved_tups; /* unmatched A tuples */
HTAB *rs_old_new_tid_map; /* unmatched B tuples */
+ double rs_tuples_dropped; /* stashed tuples dropped because their
+ * TOAST data was already reclaimed */
HTAB *rs_logical_mappings; /* logical remapping files */
uint32 rs_num_rewrite_mappings; /* # in memory mappings */
} RewriteStateData;
@@ -173,6 +175,7 @@ typedef struct
TidHashKey key; /* expected xmin/old location of B tuple */
ItemPointerData old_tid; /* A's location in the old heap */
HeapTuple tuple; /* A's tuple contents */
+ uint32 flags; /* raw_heap_insert flags A was scanned with */
} UnresolvedTupData;
typedef UnresolvedTupData *UnresolvedTup;
@@ -294,23 +297,31 @@ begin_heap_rewrite(Relation old_heap, Relation new_heap, TransactionId oldest_xm
* End a rewrite.
*
* state and any other resources are freed.
+ *
+ * Returns the number of tuples the rewrite dropped because their TOAST
+ * data had already been reclaimed. They were all scanned as recently
+ * dead, so the caller should count them as vacuumed rather than kept.
*/
-void
+double
end_heap_rewrite(RewriteState state)
{
HASH_SEQ_STATUS seq_status;
UnresolvedTup unresolved;
+ double tuples_dropped;
/*
* Write any remaining tuples in the UnresolvedTups table. If we have any
* left, they should in fact be dead, but let's err on the safe side.
+ * Each of them was scanned as recently dead, so write it with the flags
+ * it was scanned with and drop it if its TOAST data is gone.
*/
hash_seq_init(&seq_status, state->rs_unresolved_tups);
while ((unresolved = hash_seq_search(&seq_status)) != NULL)
{
ItemPointerSetInvalid(&unresolved->tuple->t_data->t_ctid);
- raw_heap_insert(state, unresolved->tuple, 0);
+ if (!raw_heap_insert(state, unresolved->tuple, unresolved->flags))
+ state->rs_tuples_dropped += 1;
}
/* Write the last page, if any */
@@ -324,8 +335,12 @@ end_heap_rewrite(RewriteState state)
logical_end_heap_rewrite(state);
+ tuples_dropped = state->rs_tuples_dropped;
+
/* Deleting the context frees everything */
MemoryContextDelete(state->rs_cxt);
+
+ return tuples_dropped;
}
/*
@@ -433,6 +448,7 @@ rewrite_heap_tuple(RewriteState state,
unresolved->old_tid = old_tuple->t_self;
unresolved->tuple = heap_copytuple(new_tuple);
+ unresolved->flags = flags;
/*
* We can't do anything more now, since we don't know where the
@@ -459,10 +475,27 @@ rewrite_heap_tuple(RewriteState state,
/* Insert the tuple and find out where it's put in new_heap */
if (!raw_heap_insert(state, new_tuple, flags))
{
- if (free_new)
- heap_freetuple(new_tuple);
+ if (!free_new)
+ {
+ /* The caller's own tuple was skipped: report it */
+ MemoryContextSwitchTo(old_cxt);
+ return false;
+ }
+
+ /*
+ * A stashed prior version. The tuple this call was made for has
+ * already been written, so the failure cannot be reported to the
+ * caller; drop the stashed tuple here instead. Only tuples
+ * scanned as recently dead are stashed, so this is the same
+ * treatment the caller gives its own tuple, and the drop is
+ * counted for end_heap_rewrite() to report. If a still older
+ * version is waiting for this one in rs_unresolved_tups, it will
+ * be written out by end_heap_rewrite().
+ */
+ state->rs_tuples_dropped += 1;
+ heap_freetuple(new_tuple);
MemoryContextSwitchTo(old_cxt);
- return false;
+ return true;
}
new_tid = new_tuple->t_self;
@@ -502,6 +535,7 @@ rewrite_heap_tuple(RewriteState state,
if (free_new)
heap_freetuple(new_tuple);
new_tuple = unresolved->tuple;
+ flags = unresolved->flags;
free_new = true;
old_tid = unresolved->old_tid;
new_tuple->t_data->t_ctid = new_tid;
diff --git a/src/include/access/rewriteheap.h b/src/include/access/rewriteheap.h
index 09110f6337a..aba8dd462df 100644
--- a/src/include/access/rewriteheap.h
+++ b/src/include/access/rewriteheap.h
@@ -24,7 +24,7 @@ typedef struct RewriteStateData *RewriteState;
extern RewriteState begin_heap_rewrite(Relation old_heap, Relation new_heap,
TransactionId oldest_xmin, TransactionId freeze_xid,
MultiXactId cutoff_multi);
-extern void end_heap_rewrite(RewriteState state);
+extern double end_heap_rewrite(RewriteState state);
/* See toast_helper.h for the values of "flags" */
extern bool rewrite_heap_tuple(RewriteState state, HeapTuple old_tuple,
--
2.43.7
0002-Free-pre-detoasted-index-values-on-every-scan-loop-e.patch (application/octet-stream, 3.8K) download
From 7db3830e6f00346c464d6a3d7b340f2f2ec4f11e Mon Sep 17 00:00:00 2001
From: Rui Zhao <zhaorui126@gmail.com>
Date: Sun, 23 Aug 2026 23:34:22 +0800
Subject: [PATCH] Free pre-detoasted index values on every scan-loop exit
heapam_index_build_range_scan() detoasts a recently-dead tuple's
external values before running the partial-index predicate, but the
ExecQual() == false path left the loop without freeing them: an index
build over N rejected recently-dead tuples kept all N detoasted copies
until the end of the scan.
The missing-TOAST skip path had the mirror problem: it freed the
values but did not reset detoasted_attrs to NULL, so the next tuple
operated on the freed set.
Move the cleanup into one helper and call it on all three exits of the
scan-loop iteration.
Measured with 800 recently-dead rows of 391 kB each and a partial
index rejecting every row: the build backend's memory context total
passes 200 MB mid-build without this fix and peaks at 1.4 MB with it.
---
src/backend/access/heap/heapam_handler.c | 55 +++++++++++++-----------
1 file changed, 31 insertions(+), 24 deletions(-)
diff --git a/src/backend/access/heap/heapam_handler.c b/src/backend/access/heap/heapam_handler.c
index 0444bb53ace..c3494a5b2c2 100644
--- a/src/backend/access/heap/heapam_handler.c
+++ b/src/backend/access/heap/heapam_handler.c
@@ -61,6 +61,8 @@ static void heap_insert_for_repack(HeapTuple tuple, Relation OldHeap,
BulkInsertState bistate);
static HeapTuple reform_tuple(HeapTuple tuple, Relation OldHeap,
Relation NewHeap, Datum *values, bool *isnull);
+static void free_detoasted_attrs(TupleTableSlot *slot,
+ Bitmapset **detoasted_attrs);
static bool SampleHeapTupleVisible(TableScanDesc scan, Buffer buffer,
HeapTuple tuple,
@@ -1209,6 +1211,30 @@ heapam_scan_analyze_next_tuple(TableScanDesc scan,
return false;
}
+/*
+ * Free the values heapam_index_build_range_scan() pre-detoasted for a
+ * recently-dead tuple, and reset the tracking set for the next tuple.
+ * Every exit from the scan-loop iteration must come through here once
+ * something was detoasted, whether the tuple was indexed or not.
+ */
+static void
+free_detoasted_attrs(TupleTableSlot *slot, Bitmapset **detoasted_attrs)
+{
+ int attno = -1;
+
+ if (*detoasted_attrs == NULL)
+ return;
+
+ while ((attno = bms_next_member(*detoasted_attrs, attno)) != -2)
+ {
+ Assert(attno > 0);
+ pfree(DatumGetPointer(slot->tts_values[attno - 1]));
+ }
+
+ bms_free(*detoasted_attrs);
+ *detoasted_attrs = NULL;
+}
+
static double
heapam_index_build_range_scan(Relation heapRelation,
Relation indexRelation,
@@ -1789,17 +1815,7 @@ heapam_index_build_range_scan(Relation heapRelation,
if (skip)
{
- attno = -1;
-
- /* cleanup any pre-detoasted values */
- while ((attno = bms_next_member(detoasted_attrs, attno)) != -2)
- {
- Assert(attno > 0);
- pfree(DatumGetPointer(slot->tts_values[attno - 1]));
- }
-
- /* final cleanup of this iteration's memory */
- bms_free(detoasted_attrs);
+ free_detoasted_attrs(slot, &detoasted_attrs);
continue;
}
}
@@ -1811,7 +1827,10 @@ heapam_index_build_range_scan(Relation heapRelation,
if (predicate != NULL)
{
if (!ExecQual(predicate, econtext))
+ {
+ free_detoasted_attrs(slot, &detoasted_attrs);
continue;
+ }
}
/*
@@ -1878,19 +1897,7 @@ heapam_index_build_range_scan(Relation heapRelation,
tupleIsAlive, callback_state);
}
- if (!bms_is_empty(detoasted_attrs))
- {
- int attno = -1;
-
- while ((attno = bms_next_member(detoasted_attrs, attno)) != -2)
- {
- Assert(attno > 0);
- pfree(DatumGetPointer(slot->tts_values[attno - 1]));
- }
-
- bms_free(detoasted_attrs);
- detoasted_attrs = NULL;
- }
+ free_detoasted_attrs(slot, &detoasted_attrs);
}
/* Report scan progress one last time. */
--
2.43.7
^ permalink raw reply [nested|flat] 33+ messages in thread
* Re: BUG #19519: REPACK can fail due to missing chunk for toast value
@ 2026-10-09 12:56 Matthias van de Meent <boekewurm+postgres@gmail.com>
parent: Andrey Borodin <x4mmm@yandex-team.ru>
0 siblings, 1 reply; 33+ messages in thread
From: Matthias van de Meent @ 2026-10-09 12:56 UTC (permalink / raw)
To: Andrey Borodin <x4mmm@yandex-team.ru>; Michael Paquier <michael@paquier.xyz>; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; Imran Zaheer <imran.zhir@gmail.com>; Alexander Lakhin <exclusion@gmail.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>; Konstantin Knizhnik <knizhnik@garret.ru>
On Wed, 5 Aug 2026 at 20:18, Andrey Borodin <x4mmm@yandex-team.ru> wrote:
>
>
>
> > On 31 Jul 2026, at 00:54, Matthias van de Meent <boekewurm+postgres@gmail.com> wrote:
> >
> > <v5-0002-Various-fixes-and-adjustments.patch>
>
[...]
> So v5 cannot be backpatched as
> is without breaking external table AMs. As I understand that the current
> plan is to settle the fix for HEAD first and consider a separate
> ABI-preserving back-branch variant afterwards.
Exactly.
> Three issues identified in the thread remain unresolved in the posted v5
> patch set:
>
> * As Zhijie reported, TOAST_MISSING_OK is lost for tuples stored in
> rs_unresolved_tups, including those inserted by end_heap_rewrite().
Fixed in the attached patch. I've adjusted various signatures with
recently_dead instead of toastflags, as toast flags don't make much
sense to pass around in components that deal with tuples that may or
may not contain externally toasted data.
> * As Matthias noted, the scan-and-sort path still has a check/use race
> because it discards the detoasted values before putting the original
> tuple into tuplesort.
Fixed in the attached patch, by rebuilding the heap tuple from the
detoasted values, and inserting that "fat" heap tuple into the
tuplesort.
> * As Dilip noted, the TOAST_MISSING_OK path for a TYPSTORAGE_PLAIN
> attribute uses detoast_external_attr_extended() instead of
> detoast_attr(). On a successful fetch, an external compressed datum
> therefore appears to remain compressed.
I _think_ I've fixed that in the attached version.
> I think the memory-leak fix in v5-0002 misses one exit path. Detoasting
> now precedes the partial index predicate, but if ExecQual() returns false,
> the loop continues without freeing detoasted_attrs and the detoasted
> values.
Thanks for the report, fixed.
> I also have a question about the concern Ekaterina raised in the related
> thread regarding real corruption. With TOAST_MISSING_OK, v5-0002 also
> returns false for an existing chunk with an unexpected size or a chunk
> outside the requested range. Is concurrent removal expected to produce
> those cases too, or could the tolerant path be limited to a missing chunk
> or a gap?
I think it is possible for chunks to be missed, as this can be caused
just by pruning (the tuple will be set LP_DEAD, and thus skipped by
the SysScan). Unexpected size or chunks outside the expected range are
also possible, but those would have to be caused by a toast-table-only
VACUUM cycle (and subsequent reuse of the OID) or reuse of cached
indexscan results after the TIDs are reused.
Attached is a flattened v6, containing v4 + the fixes descibed above.
Kind regards,
Matthias van de Meent
Databricks (https://www.databricks.com)
Attachments:
v6-0001-Fix-missing-chunk-errors-during-heap-rewrites-and.patch (application/octet-stream, 49.8K) download
From 731920d125085c81e6321e5899d378b29b1826c7 Mon Sep 17 00:00:00 2001
From: Michael Paquier <michael@paquier.xyz>
Date: Thu, 9 Jul 2026 11:46:21 +0900
Subject: [PATCH v6] Fix "missing chunk" errors during heap rewrites and index
builds
Blah, blah.
These errors happen when the tuple produced by the SnapshotAny heap
scan is RECENTLY_DEAD. Other backends may already consider those
tuples completely dead, and thus can start cleaning up the TOAST tuples
through pruning.
This problem has been reported recently by Alexander for REPACK, but it
is a much older issue (tested down to 9.5 for curiosity's sake, but I
suspect that it is much older than that).
XXX: This patch includes both TAP and isolation tests. We should remove
one pattern at the end.
XXX: Posible future improvement:
* TOAST tuple visibility is not 1:1 to heap tuple visibility, so it's
possible (and some workloads: likely) that the RECENTLY_DEAD main
tuple has normal visible toast data. If we can pass along the
visibility info of the toast data instead of always fully detoasting
the datum that could save us from performing further expensive
operations.
Reported-by: Alexander Lakhin <exclusion@gmail.com>
Co-authored-by: Michael Paquier <michael@paquier.xyz>
Co-authored-by: Matthias van de Meent <boekewurm+postgres@gmail.com>
Discussion: https://postgr.es/m/18351-f6e06364b3a2e669@postgresql.org
Discussion: https://postgr.es/m/19519-fe02d8ff679d834d@postgresql.org
---
contrib/dblink/.gitignore | 2 +
contrib/dblink/Makefile | 2 +
.../dblink/expected/rewrite_stale_xmin.out | 237 +++++++++++++++
contrib/dblink/meson.build | 5 +
contrib/dblink/specs/rewrite_stale_xmin.spec | 137 +++++++++
src/backend/access/common/detoast.c | 42 ++-
src/backend/access/heap/heapam.c | 4 +-
src/backend/access/heap/heapam_handler.c | 282 +++++++++++++++++-
src/backend/access/heap/heaptoast.c | 50 +++-
src/backend/access/heap/rewriteheap.c | 44 ++-
src/backend/access/table/toast_helper.c | 46 ++-
src/include/access/detoast.h | 9 +
src/include/access/heaptoast.h | 18 +-
src/include/access/rewriteheap.h | 6 +-
src/include/access/tableam.h | 26 +-
src/include/access/toast_helper.h | 10 +-
src/test/recovery/meson.build | 1 +
src/test/recovery/t/099_rewrite_stale_xmin.pl | 124 ++++++++
18 files changed, 989 insertions(+), 56 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/recovery/t/099_rewrite_stale_xmin.pl
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..2e5a7940ea2
--- /dev/null
+++ b/contrib/dblink/expected/rewrite_stale_xmin.out
@@ -0,0 +1,237 @@
+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_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)
+
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..fe88e789f85
--- /dev/null
+++ b/contrib/dblink/specs/rewrite_stale_xmin.spec
@@ -0,0 +1,137 @@
+# Test that heap rewrites work when the rewriting backend's own xmin is
+# held back by a transaction in another database.
+
+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_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;
+}
+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);
+}
+
+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
+
+# 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
diff --git a/src/backend/access/common/detoast.c b/src/backend/access/common/detoast.c
index a9d4e3ae98e..52a7b9a0c7b 100644
--- a/src/backend/access/common/detoast.c
+++ b/src/backend/access/common/detoast.c
@@ -17,13 +17,14 @@
#include "access/table.h"
#include "access/tableam.h"
#include "access/toast_compression.h"
+#include "access/toast_helper.h"
#include "access/toast_internals.h"
#include "common/int.h"
#include "common/pg_lzcompress.h"
#include "utils/expandeddatum.h"
#include "utils/rel.h"
-static varlena *toast_fetch_datum(varlena *attr);
+static varlena *toast_fetch_datum(varlena *attr, uint32 flags);
static varlena *toast_fetch_datum_slice(varlena *attr,
int32 sliceoffset,
int32 slicelength);
@@ -52,7 +53,7 @@ detoast_external_attr(varlena *attr)
/*
* This is an external stored plain value
*/
- result = toast_fetch_datum(attr);
+ result = toast_fetch_datum(attr, 0);
}
else if (VARATT_IS_EXTERNAL_INDIRECT(attr))
{
@@ -103,6 +104,23 @@ detoast_external_attr(varlena *attr)
}
+/* ----------
+ * detoast_external_attr_extended -
+ *
+ * Like detoast_external_attr, but returns NULL if toast chunks are
+ * missing for external pointers.
+ * ----------
+ */
+varlena *
+detoast_external_attr_extended(varlena *attr)
+{
+ if (VARATT_IS_EXTERNAL_ONDISK(attr))
+ return toast_fetch_datum(attr, TOAST_MISSING_OK);
+ else
+ return detoast_external_attr(attr);
+}
+
+
/* ----------
* detoast_attr -
*
@@ -121,7 +139,7 @@ detoast_attr(varlena *attr)
/*
* This is an externally stored datum --- fetch it back from there
*/
- attr = toast_fetch_datum(attr);
+ attr = toast_fetch_datum(attr, 0);
/* If it's compressed, decompress it */
if (VARATT_IS_COMPRESSED(attr))
{
@@ -268,7 +286,7 @@ detoast_attr_slice(varlena *attr,
preslice = toast_fetch_datum_slice(attr, 0, max_size);
}
else
- preslice = toast_fetch_datum(attr);
+ preslice = toast_fetch_datum(attr, 0);
}
else if (VARATT_IS_EXTERNAL_INDIRECT(attr))
{
@@ -343,10 +361,12 @@ detoast_attr_slice(varlena *attr,
*
* Reconstruct an in memory Datum from the chunks saved
* in the toast relation
+ *
+ * If flags uses TOAST_MISSING_OK, returns NULL when chunks are missing.
* ----------
*/
static varlena *
-toast_fetch_datum(varlena *attr)
+toast_fetch_datum(varlena *attr, uint32 flags)
{
Relation toastrel;
varlena *result;
@@ -380,8 +400,14 @@ toast_fetch_datum(varlena *attr)
toastrel = table_open(toastrelid, AccessShareLock);
/* Fetch all chunks */
- table_relation_fetch_toast_slice(toastrel, valueid,
- attrsize, 0, attrsize, result);
+ if (!table_relation_fetch_toast_slice(toastrel, valueid,
+ attrsize, 0, attrsize, result,
+ flags))
+ {
+ pfree(result);
+ table_close(toastrel, AccessShareLock);
+ return NULL;
+ }
/* Close toast table */
table_close(toastrel, AccessShareLock);
@@ -466,7 +492,7 @@ toast_fetch_datum_slice(varlena *attr, int32 sliceoffset,
/* Fetch all chunks */
table_relation_fetch_toast_slice(toastrel, valueid,
attrsize, sliceoffset, slicelength,
- result);
+ result, 0);
/* Close toast table */
table_close(toastrel, AccessShareLock);
diff --git a/src/backend/access/heap/heapam.c b/src/backend/access/heap/heapam.c
index 5c1eaadd442..8e4f0f956bd 100644
--- a/src/backend/access/heap/heapam.c
+++ b/src/backend/access/heap/heapam.c
@@ -2264,7 +2264,7 @@ heap_prepare_insert(Relation relation, HeapTuple tup, TransactionId xid,
return tup;
}
else if (HeapTupleHasExternal(tup) || tup->t_len > TOAST_TUPLE_THRESHOLD)
- return heap_toast_insert_or_update(relation, tup, NULL, options);
+ return heap_toast_insert_or_update(relation, tup, NULL, options, 0);
else
return tup;
}
@@ -3968,7 +3968,7 @@ l2:
* tuples too. We never skip the FSM here.
*/
heaptup = heap_toast_insert_or_update(relation, newtup, &oldtup,
- walLogical ? 0 : HEAP_INSERT_NO_LOGICAL);
+ walLogical ? 0 : HEAP_INSERT_NO_LOGICAL, 0);
newtupsize = MAXALIGN(heaptup->t_len);
}
else
diff --git a/src/backend/access/heap/heapam_handler.c b/src/backend/access/heap/heapam_handler.c
index 7d2065dec37..e7b0b2c3580 100644
--- a/src/backend/access/heap/heapam_handler.c
+++ b/src/backend/access/heap/heapam_handler.c
@@ -19,6 +19,7 @@
*/
#include "postgres.h"
+#include "access/detoast.h"
#include "access/genam.h"
#include "access/heapam.h"
#include "access/heaptoast.h"
@@ -26,6 +27,7 @@
#include "access/rewriteheap.h"
#include "access/syncscan.h"
#include "access/tableam.h"
+#include "access/toast_helper.h"
#include "access/tsmapi.h"
#include "access/visibilitymap.h"
#include "access/xact.h"
@@ -36,6 +38,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"
@@ -48,9 +51,11 @@
#include "utils/rel.h"
#include "utils/tuplesort.h"
-static void reform_and_rewrite_tuple(HeapTuple tuple,
+/* See toast_helper.h for values of "flags" */
+static bool reform_and_rewrite_tuple(HeapTuple tuple,
Relation OldHeap, Relation NewHeap,
- Datum *values, bool *isnull, RewriteState rwstate);
+ Datum *values, bool *isnull, RewriteState rwstate,
+ bool recently_dead);
static void heap_insert_for_repack(HeapTuple tuple, Relation OldHeap,
Relation NewHeap, Datum *values, bool *isnull,
BulkInsertState bistate);
@@ -703,6 +708,7 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,
HeapTuple tuple;
Buffer buf;
bool isdead;
+ bool recently_dead = false;
CHECK_FOR_INTERRUPTS();
@@ -789,6 +795,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 */
@@ -822,6 +829,7 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,
RelationGetRelationName(OldHeap));
/* treat as recently dead */
*tups_recently_dead += 1;
+ recently_dead = true;
isdead = false;
break;
default:
@@ -850,6 +858,95 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,
*num_tuples += 1;
if (tuplesort != NULL)
{
+ /*
+ * For RECENTLY_DEAD tuples, retrieve TOAST data that's still
+ * available before putting the tuple in the sort. If a concurrent
+ * VACUUM (or page prune) already reclaimed parts of that TOAST data,
+ * we can skip the tuple.
+ */
+ if (recently_dead && HeapTupleHasExternal(tuple))
+ {
+ Bitmapset *detoasted = NULL;
+ bool skip = false;
+ HeapTuple produced;
+
+ heap_deform_tuple(tuple, oldTupDesc, values, isnull);
+
+ for (int i = 0; i < oldTupDesc->natts; i++)
+ {
+ Form_pg_attribute att = TupleDescAttr(oldTupDesc, i);
+ varlena *d;
+
+ /* ignore non-varlena, dropped, and */
+ if (att->attlen != -1)
+ continue;
+ /* Set to NULL to avoid including it in serialization later on, if relevant */
+ if (att->attisdropped)
+ {
+ isnull[i] = true;
+ continue;
+ }
+
+ if (isnull[i])
+ continue;
+
+ d = DatumGetPointer(values[i]);
+
+ /* not external means no toast cleanup race */
+ if (!VARATT_IS_EXTERNAL_ONDISK(d))
+ continue;
+
+ /* actually detoast the value */
+ d = detoast_external_attr_extended(d);
+
+ if (d == NULL)
+ {
+ skip = true;
+ break;
+ }
+ detoasted = bms_add_member(detoasted, i);
+ values[i] = PointerGetDatum(d);
+ }
+
+ if (skip)
+ {
+ *num_tuples -= 1;
+ *tups_vacuumed += 1;
+ *tups_recently_dead -= 1;
+
+ goto cleanup_and_next;
+ }
+
+ /* no new resources allocated, store unprocessed tuple as normal */
+ if (bms_is_empty(detoasted))
+ goto normal_put;
+
+ /* the tuple contained visible externally toasted attributes. */
+ produced = heap_form_tuple(oldTupDesc, values, isnull);
+ tuplesort_putheaptuple(tuplesort, produced);
+ pfree(produced);
+
+ /*
+ * In scan-and-sort mode, report increase in number of tuples
+ * scanned
+ */
+ pgstat_progress_update_param(PROGRESS_REPACK_HEAP_TUPLES_SCANNED,
+ *num_tuples);
+
+cleanup_and_next:
+ for (int i = bms_next_member(detoasted, -1);
+ i >= 0;
+ i = bms_prev_member(detoasted, i))
+ {
+ pfree(DatumGetPointer(values[i]));
+ }
+
+ bms_free(detoasted);
+ detoasted = NULL;
+ continue;
+ }
+
+normal_put:
tuplesort_putheaptuple(tuplesort, tuple);
/*
@@ -868,8 +965,22 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,
int64 ct_val[2];
if (!concurrent)
- reform_and_rewrite_tuple(tuple, OldHeap, NewHeap,
- values, isnull, rwstate);
+ {
+ if (!reform_and_rewrite_tuple(tuple, OldHeap, NewHeap,
+ values, isnull, rwstate,
+ recently_dead))
+ {
+ Assert(recently_dead);
+ /*
+ * Missing TOAST chunks for a recently-dead tuple. Treat
+ * it as dead.
+ */
+ *tups_vacuumed += 1;
+ *num_tuples -= 1;
+ *tups_recently_dead -= 1;
+ continue;
+ }
+ }
else
heap_insert_for_repack(tuple, OldHeap, NewHeap,
values, isnull, bistate);
@@ -921,10 +1032,12 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,
n_tuples += 1;
if (!concurrent)
- reform_and_rewrite_tuple(tuple,
- OldHeap, NewHeap,
- values, isnull,
- rwstate);
+ {
+ (void) reform_and_rewrite_tuple(tuple,
+ OldHeap, NewHeap,
+ values, isnull,
+ rwstate, false);
+ }
else
heap_insert_for_repack(tuple, OldHeap, NewHeap,
values, isnull, bistate);
@@ -1156,6 +1269,7 @@ heapam_index_build_range_scan(Relation heapRelation,
BlockNumber previous_blkno = InvalidBlockNumber;
BlockNumber root_blkno = InvalidBlockNumber;
OffsetNumber root_offsets[MaxHeapTuplesPerPage];
+ Bitmapset *detoast_index_attrs = NULL;
/*
* sanity checks
@@ -1252,6 +1366,70 @@ heapam_index_build_range_scan(Relation heapRelation,
!TransactionIdIsValid(OldestXmin));
Assert(snapshot == SnapshotAny || !anyvisible);
+ /*
+ * Extract the set of attributes an index may need to detoast, including
+ * expressions and predicates.
+ */
+ for (int i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
+ {
+ int attnum = indexInfo->ii_IndexAttrNumbers[i];
+
+ if (attnum != 0)
+ detoast_index_attrs = bms_add_member(detoast_index_attrs,
+ attnum - FirstLowInvalidHeapAttributeNumber);
+ }
+ pull_varattnos((Node *) indexInfo->ii_Expressions, 1, &detoast_index_attrs);
+ pull_varattnos((Node *) indexInfo->ii_Predicate, 1, &detoast_index_attrs);
+
+ /*
+ * Post-process the attribute bitmap.
+ *
+ * We remove all non-varlena attributes (we don't need to check them
+ * during detoasting), and add all varlena attributes if the index
+ * contains a whole-row expression.
+ */
+ if (bms_is_member(-FirstLowInvalidHeapAttributeNumber, detoast_index_attrs))
+ {
+ TupleDesc desc = RelationGetDescr(heapRelation);
+
+ for (AttrNumber i = RelationGetNumberOfAttributes(heapRelation); i > 0; i--)
+ {
+ AttrNumber offset = i - FirstLowInvalidHeapAttributeNumber;
+ CompactAttribute *att = TupleDescCompactAttr(desc, i - 1);
+
+ /*
+ * If the attribute is varlena, add it to the map, else remove
+ * the attribute.
+ * We work backwards to avoid reallocations.
+ */
+ if (att->attlen == -1)
+ detoast_index_attrs = bms_add_member(detoast_index_attrs, offset);
+ else
+ detoast_index_attrs = bms_del_member(detoast_index_attrs, offset);
+ }
+
+ detoast_index_attrs = bms_del_member(detoast_index_attrs, -FirstLowInvalidHeapAttributeNumber);
+ }
+ else
+ {
+ TupleDesc desc = RelationGetDescr(heapRelation);
+
+ for (AttrNumber i = RelationGetNumberOfAttributes(heapRelation); i > 0; i--)
+ {
+ AttrNumber offset = i - FirstLowInvalidHeapAttributeNumber;
+ CompactAttribute *att = TupleDescCompactAttr(desc, i - 1);
+
+ /*
+ * If the attribute is not varlena, remove the attribute from
+ * tracking.
+ *
+ * We work backwards to avoid reallocations.
+ */
+ if (att->attlen != -1)
+ detoast_index_attrs = bms_del_member(detoast_index_attrs, offset);
+ }
+ }
+
/* Publish number of blocks to scan */
if (progress)
{
@@ -1289,6 +1467,7 @@ heapam_index_build_range_scan(Relation heapRelation,
while ((heapTuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
{
bool tupleIsAlive;
+ Bitmapset *detoasted_attrs = NULL;
CHECK_FOR_INTERRUPTS();
@@ -1590,6 +1769,61 @@ heapam_index_build_range_scan(Relation heapRelation,
/* Set up for predicate or expression evaluation */
ExecStoreBufferHeapTuple(heapTuple, slot, hscan->rs_cbuf);
+ /* For RECENTLY_DEAD tuples, pre-detoast external TOAST values. */
+ if (!tupleIsAlive && !bms_is_empty(detoast_index_attrs))
+ {
+ bool skip = false;
+ int attno;
+
+ /*
+ * Only get the attributes up to the last attribute we want to
+ * detoast.
+ */
+ attno = bms_prev_member(detoast_index_attrs, -1);
+ slot_getsomeattrs(slot, attno + FirstLowInvalidHeapAttributeNumber);
+
+ /*
+ * Iterate over the attributes which are now in tts_isnull/
+ * tts_values slots, and detoast them where needed.
+ */
+ attno = -1;
+ while ((attno = bms_next_member(detoast_index_attrs, attno)) >= 0)
+ {
+ int attnum = attno + FirstLowInvalidHeapAttributeNumber;
+ varlena *toastptr;
+
+ if (attnum <= 0)
+ continue; /* system column */
+
+ Assert(TupleDescCompactAttr(RelationGetDescr(heapRelation), attnum - 1)->attlen == -1);
+
+ if (slot->tts_isnull[attnum - 1])
+ continue;
+
+ toastptr = DatumGetPointer(slot->tts_values[attnum - 1]);
+
+ if (VARATT_IS_EXTERNAL_ONDISK(toastptr))
+ {
+ varlena *detoasted;
+
+ detoasted = detoast_external_attr_extended(toastptr);
+
+ if (detoasted == NULL)
+ {
+ skip = true;
+ break;
+ }
+
+ slot->tts_values[attnum - 1] = PointerGetDatum(detoasted);
+
+ detoasted_attrs = bms_add_member(detoasted_attrs, attnum);
+ }
+ }
+
+ if (skip)
+ goto cleanup_and_next;
+ }
+
/*
* In a partial index, discard tuples that don't satisfy the
* predicate.
@@ -1597,7 +1831,7 @@ heapam_index_build_range_scan(Relation heapRelation,
if (predicate != NULL)
{
if (!ExecQual(predicate, econtext))
- continue;
+ goto cleanup_and_next;
}
/*
@@ -1663,6 +1897,21 @@ heapam_index_build_range_scan(Relation heapRelation,
callback(indexRelation, &heapTuple->t_self, values, isnull,
tupleIsAlive, callback_state);
}
+
+cleanup_and_next:
+ if (!bms_is_empty(detoasted_attrs))
+ {
+ int attno = -1;
+
+ while ((attno = bms_next_member(detoasted_attrs, attno)) != -2)
+ {
+ Assert(attno > 0);
+ pfree(DatumGetPointer(slot->tts_values[attno - 1]));
+ }
+
+ bms_free(detoasted_attrs);
+ detoasted_attrs = NULL;
+ }
}
/* Report scan progress one last time. */
@@ -2334,20 +2583,29 @@ heapam_scan_sample_next_tuple(TableScanDesc scan, SampleScanState *scanstate,
* SET WITHOUT OIDS.
*
* So, we must reconstruct the tuple from component Datums.
+ *
+ * Returns true on success, and false on failure if flags uses
+ * TOAST_MISSING_OK. See toast_helper.h.
*/
-static void
+static bool
reform_and_rewrite_tuple(HeapTuple tuple,
Relation OldHeap, Relation NewHeap,
- Datum *values, bool *isnull, RewriteState rwstate)
+ Datum *values, bool *isnull, RewriteState rwstate,
+ bool recently_dead)
{
HeapTuple newtuple;
newtuple = reform_tuple(tuple, OldHeap, NewHeap, values, isnull);
/* The heap rewrite module does the rest */
- rewrite_heap_tuple(rwstate, tuple, newtuple);
+ if (!rewrite_heap_tuple(rwstate, tuple, newtuple, recently_dead))
+ {
+ heap_freetuple(newtuple);
+ return false;
+ }
heap_freetuple(newtuple);
+ return true;
}
/*
diff --git a/src/backend/access/heap/heaptoast.c b/src/backend/access/heap/heaptoast.c
index b03d8492959..38cb9545965 100644
--- a/src/backend/access/heap/heaptoast.c
+++ b/src/backend/access/heap/heaptoast.c
@@ -84,9 +84,10 @@ heap_toast_delete(Relation rel, HeapTuple oldtup, bool is_speculative)
* newtup: the candidate new tuple to be inserted
* oldtup: the old row version for UPDATE, or NULL for INSERT
* options: options to be passed to heap_insert() for toast rows
+ * flags: additional control flags, see heaptoast.h.
* Result:
- * either newtup if no toasting is needed, or a palloc'd modified tuple
- * that is what should actually get stored
+ * either newtup if no toasting is needed, a palloc'd modified tuple
+ * that is what should actually get stored, or NULL.
*
* NOTE: neither newtup nor oldtup will be modified. This is a change
* from the pre-8.1 API of this routine.
@@ -94,7 +95,7 @@ heap_toast_delete(Relation rel, HeapTuple oldtup, bool is_speculative)
*/
HeapTuple
heap_toast_insert_or_update(Relation rel, HeapTuple newtup, HeapTuple oldtup,
- uint32 options)
+ uint32 options, uint32 flags)
{
HeapTuple result_tuple;
TupleDesc tupleDesc;
@@ -154,7 +155,8 @@ heap_toast_insert_or_update(Relation rel, HeapTuple newtup, HeapTuple oldtup,
ttc.ttc_oldisnull = toast_oldisnull;
}
ttc.ttc_attr = toast_attr;
- toast_tuple_init(&ttc);
+ if (!toast_tuple_init(&ttc, flags))
+ return NULL;
/* ----------
* Compress and/or save external until data fits into target length
@@ -621,11 +623,15 @@ toast_build_flattened_tuple(TupleDesc tupleDesc,
* sliceoffset is the byte offset within the TOAST value from which to fetch.
* slicelength is the number of bytes to be fetched from the TOAST value.
* result is the varlena into which the results should be written.
+ * flags records more options, see toast_helper.h.
+ *
+ * Returns true on success, or false if flags uses TOAST_MISSING_OK and
+ * chunks are missing rather than raising an error.
*/
-void
+bool
heap_fetch_toast_slice(Relation toastrel, Oid8 valueid, int32 attrsize,
int32 sliceoffset, int32 slicelength,
- varlena *result)
+ varlena *result, uint32 flags)
{
Relation *toastidxs;
ScanKeyData toastkey[3];
@@ -737,28 +743,47 @@ heap_fetch_toast_slice(Relation toastrel, Oid8 valueid, int32 attrsize,
/*
* Some checks on the data we've found
*/
+
if (curchunk != expectedchunk)
+ {
+ if (flags & TOAST_MISSING_OK)
+ goto toast_broken_missing_ok;
+
ereport(ERROR,
(errcode(ERRCODE_DATA_CORRUPTED),
errmsg_internal("unexpected chunk number %d (expected %d) for toast value %" PRIu64 " in %s",
curchunk, expectedchunk, valueid,
RelationGetRelationName(toastrel))));
+ }
+
if (curchunk > endchunk)
+ {
+ if (flags & TOAST_MISSING_OK)
+ goto toast_broken_missing_ok;
+
ereport(ERROR,
(errcode(ERRCODE_DATA_CORRUPTED),
errmsg_internal("unexpected chunk number %d (out of range %d..%d) for toast value %" PRIu64 " in %s",
curchunk,
startchunk, endchunk, valueid,
RelationGetRelationName(toastrel))));
+ }
+
expected_size = curchunk < totalchunks - 1 ? max_chunk_size
: attrsize - ((totalchunks - 1) * max_chunk_size);
+
if (chunksize != expected_size)
+ {
+ if (flags & TOAST_MISSING_OK)
+ goto toast_broken_missing_ok;
+
ereport(ERROR,
(errcode(ERRCODE_DATA_CORRUPTED),
errmsg_internal("unexpected chunk size %d (expected %d) in chunk %d of %d for toast value %" PRIu64 " in %s",
chunksize, expected_size,
curchunk, totalchunks, valueid,
RelationGetRelationName(toastrel))));
+ }
/*
* Copy the data into proper place in our result
@@ -782,13 +807,26 @@ heap_fetch_toast_slice(Relation toastrel, Oid8 valueid, int32 attrsize,
* Final checks that we successfully fetched the datum
*/
if (expectedchunk != (endchunk + 1))
+ {
+ if (flags & TOAST_MISSING_OK)
+ goto toast_broken_missing_ok;
+
ereport(ERROR,
(errcode(ERRCODE_DATA_CORRUPTED),
errmsg_internal("missing chunk number %d for toast value %" PRIu64 " in %s",
expectedchunk, valueid,
RelationGetRelationName(toastrel))));
+ }
+
+ /* End scan and close indexes. */
+ systable_endscan_ordered(toastscan);
+ toast_close_indexes(toastidxs, num_indexes, AccessShareLock);
+
+ return true;
+toast_broken_missing_ok:
/* End scan and close indexes. */
systable_endscan_ordered(toastscan);
toast_close_indexes(toastidxs, num_indexes, AccessShareLock);
+ return false;
}
diff --git a/src/backend/access/heap/rewriteheap.c b/src/backend/access/heap/rewriteheap.c
index 0648e433031..0d57b3f5709 100644
--- a/src/backend/access/heap/rewriteheap.c
+++ b/src/backend/access/heap/rewriteheap.c
@@ -115,6 +115,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
#include "pgstat.h"
+#include "access/toast_helper.h"
#include "replication/slot.h"
#include "storage/bufmgr.h"
#include "storage/bulk_write.h"
@@ -172,6 +173,7 @@ typedef struct
{
TidHashKey key; /* expected xmin/old location of B tuple */
ItemPointerData old_tid; /* A's location in the old heap */
+ bool recently_dead; /* tuple was recently_dead on access */
HeapTuple tuple; /* A's tuple contents */
} UnresolvedTupData;
@@ -211,7 +213,8 @@ typedef struct RewriteMappingDataEntry
/* prototypes for internal functions */
-static void raw_heap_insert(RewriteState state, HeapTuple tup);
+static bool raw_heap_insert(RewriteState state, HeapTuple tup,
+ bool recently_dead);
/* internal logical remapping prototypes */
static void logical_begin_heap_rewrite(RewriteState state);
@@ -309,7 +312,7 @@ end_heap_rewrite(RewriteState state)
while ((unresolved = hash_seq_search(&seq_status)) != NULL)
{
ItemPointerSetInvalid(&unresolved->tuple->t_data->t_ctid);
- raw_heap_insert(state, unresolved->tuple);
+ raw_heap_insert(state, unresolved->tuple, unresolved->recently_dead);
}
/* Write the last page, if any */
@@ -338,9 +341,10 @@ end_heap_rewrite(RewriteState state)
* old_tuple original tuple in the old heap
* new_tuple new, rewritten tuple to be inserted to new heap
*/
-void
+bool
rewrite_heap_tuple(RewriteState state,
- HeapTuple old_tuple, HeapTuple new_tuple)
+ HeapTuple old_tuple, HeapTuple new_tuple,
+ bool recently_dead)
{
MemoryContext old_cxt;
ItemPointerData old_tid;
@@ -431,13 +435,14 @@ rewrite_heap_tuple(RewriteState state,
unresolved->old_tid = old_tuple->t_self;
unresolved->tuple = heap_copytuple(new_tuple);
+ unresolved->recently_dead = recently_dead;
/*
* We can't do anything more now, since we don't know where the
* tuple will be written.
*/
MemoryContextSwitchTo(old_cxt);
- return;
+ return true;
}
}
@@ -455,7 +460,13 @@ rewrite_heap_tuple(RewriteState state,
ItemPointerData new_tid;
/* Insert the tuple and find out where it's put in new_heap */
- raw_heap_insert(state, new_tuple);
+ if (!raw_heap_insert(state, new_tuple, recently_dead))
+ {
+ if (free_new)
+ heap_freetuple(new_tuple);
+ MemoryContextSwitchTo(old_cxt);
+ return false;
+ }
new_tid = new_tuple->t_self;
logical_rewrite_heap_tuple(state, old_tid, new_tuple);
@@ -496,6 +507,7 @@ rewrite_heap_tuple(RewriteState state,
new_tuple = unresolved->tuple;
free_new = true;
old_tid = unresolved->old_tid;
+ recently_dead = unresolved->recently_dead;
new_tuple->t_data->t_ctid = new_tid;
/*
@@ -532,6 +544,7 @@ rewrite_heap_tuple(RewriteState state,
}
MemoryContextSwitchTo(old_cxt);
+ return true;
}
/*
@@ -592,9 +605,17 @@ rewrite_heap_dead_tuple(RewriteState state, HeapTuple old_tuple)
* t_self of the tuple is set to the new TID of the tuple. If t_ctid of the
* tuple is invalid on entry, it's replaced with the new TID as well (in
* the inserted data only, not in the caller's copy).
+ *
+ * recently_dead is for CLUSTER-related tasks, that insert recently_dead
+ * tuples, and thus can't assume there's no concurrent MVCC cleanup of its
+ * dependent data. Setting this flag increases the level of paranoia applied
+ * when processing TOAST.
+ *
+ * If TOAST data is missing with `recently_dead set, this function will not
+ * insert the tuple, but instead return false.
*/
-static void
-raw_heap_insert(RewriteState state, HeapTuple tup)
+static bool
+raw_heap_insert(RewriteState state, HeapTuple tup, bool recently_dead)
{
Page page;
Size pageFreeSpace,
@@ -619,6 +640,7 @@ raw_heap_insert(RewriteState state, HeapTuple tup)
else if (HeapTupleHasExternal(tup) || tup->t_len > TOAST_TUPLE_THRESHOLD)
{
uint32 options = HEAP_INSERT_SKIP_FSM;
+ uint32 toastflags = recently_dead ? TOAST_MISSING_OK : 0;
/*
* While rewriting the heap for REPACK, make sure data for the TOAST
@@ -628,7 +650,9 @@ raw_heap_insert(RewriteState state, HeapTuple tup)
options |= HEAP_INSERT_NO_LOGICAL;
heaptup = heap_toast_insert_or_update(state->rs_new_rel, tup, NULL,
- options);
+ options, toastflags);
+ if (heaptup == NULL)
+ return false;
}
else
heaptup = tup;
@@ -702,6 +726,8 @@ raw_heap_insert(RewriteState state, HeapTuple tup)
/* If heaptup is a private copy, release it. */
if (heaptup != tup)
heap_freetuple(heaptup);
+
+ return true;
}
/* ------------------------------------------------------------------------
diff --git a/src/backend/access/table/toast_helper.c b/src/backend/access/table/toast_helper.c
index 2613d9dc095..a8e58d8573c 100644
--- a/src/backend/access/table/toast_helper.c
+++ b/src/backend/access/table/toast_helper.c
@@ -36,9 +36,13 @@
* toast_flags is just a single uint8, but toast_attr is a caller-provided
* array with a length equal to tupleDesc->natts. The caller need not
* perform any initialization of the array before calling this function.
+ *
+ * If flags uses TOAST_MISSING_OK and an external TOAST value cannot be
+ * fetched, returns false instead of raising an error. Returns true on
+ * success. See toast_helper.h.
*/
-void
-toast_tuple_init(ToastTupleContext *ttc)
+bool
+toast_tuple_init(ToastTupleContext *ttc, uint32 flags)
{
TupleDesc tupleDesc = ttc->ttc_rel->rd_att;
int numAttrs = tupleDesc->natts;
@@ -141,7 +145,30 @@ toast_tuple_init(ToastTupleContext *ttc)
if (VARATT_IS_EXTERNAL(new_value))
{
ttc->ttc_attr[i].tai_oldexternal = new_value;
- if (att->attstorage == TYPSTORAGE_PLAIN)
+
+ /* first, make sure to read the data from disk and into memory */
+ if ((flags & TOAST_MISSING_OK) != 0 &&
+ VARATT_IS_EXTERNAL_ONDISK(new_value))
+ {
+ new_value = detoast_external_attr_extended(new_value);
+ if (new_value == NULL)
+ goto broken_toast_missing_ok;
+ /*
+ * STORAGE_PLAIN doesn't allow compressed data here,
+ * so manually decompress here through detoast_attr() now
+ * that the value has been extracted from the toast table.
+ */
+ if (att->attstorage == TYPSTORAGE_PLAIN &&
+ VARATT_IS_COMPRESSED(new_value))
+ {
+ varlena *nv = detoast_attr(new_value);
+
+ Assert(nv != new_value);
+ pfree(new_value);
+ new_value = nv;
+ }
+ }
+ else if (att->attstorage == TYPSTORAGE_PLAIN)
new_value = detoast_attr(new_value);
else
new_value = detoast_external_attr(new_value);
@@ -163,6 +190,19 @@ toast_tuple_init(ToastTupleContext *ttc)
ttc->ttc_attr[i].tai_colflags |= TOASTCOL_IGNORE;
}
}
+
+ return true;
+
+broken_toast_missing_ok:
+ for (; i > 0; i--)
+ {
+ if (ttc->ttc_attr[i].tai_colflags & TOASTCOL_NEEDS_FREE)
+ {
+ pfree(DatumGetPointer(ttc->ttc_values[i]));
+ ttc->ttc_attr[i].tai_colflags &= ~TOASTCOL_NEEDS_FREE;
+ }
+ }
+ return false;
}
/*
diff --git a/src/include/access/detoast.h b/src/include/access/detoast.h
index 93b7a253760..c5411b34fcc 100644
--- a/src/include/access/detoast.h
+++ b/src/include/access/detoast.h
@@ -91,6 +91,15 @@ toast_external_info_get(const struct varlena *attr, toast_external_data *toast_e
*/
extern varlena *detoast_external_attr(varlena *attr);
+/* ----------
+ * detoast_external_attr_extended() -
+ *
+ * Like detoast_external_attr, but returns NULL if toast chunks
+ * are missing (instead of raising an error).
+ * ----------
+ */
+extern varlena *detoast_external_attr_extended(varlena *attr);
+
/* ----------
* detoast_attr() -
*
diff --git a/src/include/access/heaptoast.h b/src/include/access/heaptoast.h
index 4c3fda8a5f9..301b33aa970 100644
--- a/src/include/access/heaptoast.h
+++ b/src/include/access/heaptoast.h
@@ -105,11 +105,15 @@
/* ----------
* heap_toast_insert_or_update -
*
- * Called by heap_insert() and heap_update().
+ * Called by heap_insert() and heap_update(). Returns NULL if the
+ * insert/update could not be completed.
+ *
+ * See toast_helper.h for the values of "flags".
* ----------
*/
extern HeapTuple heap_toast_insert_or_update(Relation rel, HeapTuple newtup,
- HeapTuple oldtup, uint32 options);
+ HeapTuple oldtup, uint32 options,
+ uint32 flags);
/* ----------
* heap_toast_delete -
@@ -153,11 +157,15 @@ extern HeapTuple toast_build_flattened_tuple(TupleDesc tupleDesc,
/* ----------
* heap_fetch_toast_slice
*
- * Fetch a slice from a toast value stored in a heap table.
+ * Fetch a slice from a toast value stored in a heap table. Returns
+ * false if the slice could not be fetched, otherwise true on success.
+ *
+ * See toast_helper.h for the values of "flags".
* ----------
*/
-extern void heap_fetch_toast_slice(Relation toastrel, Oid8 valueid,
+extern bool heap_fetch_toast_slice(Relation toastrel, Oid8 valueid,
int32 attrsize, int32 sliceoffset,
- int32 slicelength, varlena *result);
+ int32 slicelength, varlena *result,
+ uint32 flags);
#endif /* HEAPTOAST_H */
diff --git a/src/include/access/rewriteheap.h b/src/include/access/rewriteheap.h
index 6ccf7b45c04..67467c2ddbe 100644
--- a/src/include/access/rewriteheap.h
+++ b/src/include/access/rewriteheap.h
@@ -25,8 +25,10 @@ extern RewriteState begin_heap_rewrite(Relation old_heap, Relation new_heap,
TransactionId oldest_xmin, TransactionId freeze_xid,
MultiXactId cutoff_multi);
extern void end_heap_rewrite(RewriteState state);
-extern void rewrite_heap_tuple(RewriteState state, HeapTuple old_tuple,
- HeapTuple new_tuple);
+
+/* See toast_helper.h for the values of "flags" */
+extern bool rewrite_heap_tuple(RewriteState state, HeapTuple old_tuple,
+ HeapTuple new_tuple, bool recently_dead);
extern bool rewrite_heap_dead_tuple(RewriteState state, HeapTuple old_tuple);
/*
diff --git a/src/include/access/tableam.h b/src/include/access/tableam.h
index ea3f2a6be99..42f3a96206e 100644
--- a/src/include/access/tableam.h
+++ b/src/include/access/tableam.h
@@ -782,12 +782,17 @@ typedef struct TableAmRoutine
* This callback is invoked when detoasting a value stored in a toast
* table implemented by this AM. See table_relation_fetch_toast_slice()
* for more details.
+ *
+ * If TOAST_MISSING_OK is set in flags, returns false when chunks are
+ * missing instead of raising an error. Returns true on success. See
+ * toast_helper.h for possible values of "flags".
*/
- void (*relation_fetch_toast_slice) (Relation toastrel, Oid8 valueid,
+ bool (*relation_fetch_toast_slice) (Relation toastrel, Oid8 valueid,
int32 attrsize,
int32 sliceoffset,
int32 slicelength,
- varlena *result);
+ varlena *result,
+ uint32 flags);
/* ------------------------------------------------------------------------
@@ -2003,16 +2008,21 @@ table_relation_toast_am(Relation rel)
*
* result is caller-allocated space into which the fetched bytes should be
* stored.
+ *
+ * flags: if TOAST_MISSING_OK is set, return false when toast chunks are
+ * missing instead of raising an error. Returns true on success. See
+ * also toast_helper.h.
*/
-static inline void
+static inline bool
table_relation_fetch_toast_slice(Relation toastrel, Oid8 valueid,
int32 attrsize, int32 sliceoffset,
- int32 slicelength, varlena *result)
+ int32 slicelength, varlena *result,
+ uint32 flags)
{
- toastrel->rd_tableam->relation_fetch_toast_slice(toastrel, valueid,
- attrsize,
- sliceoffset, slicelength,
- result);
+ return toastrel->rd_tableam->relation_fetch_toast_slice(toastrel, valueid,
+ attrsize,
+ sliceoffset, slicelength,
+ result, flags);
}
diff --git a/src/include/access/toast_helper.h b/src/include/access/toast_helper.h
index 2ec92397f26..4abebe82798 100644
--- a/src/include/access/toast_helper.h
+++ b/src/include/access/toast_helper.h
@@ -101,7 +101,15 @@ typedef struct
#define TOASTCOL_IGNORE 0x0010
#define TOASTCOL_INCOMPRESSIBLE 0x0020
-extern void toast_tuple_init(ToastTupleContext *ttc);
+/*
+ * Flags for TOAST fetch operations.
+ *
+ * TOAST_MISSING_OK, when set, means that a TOAST fetch tolerates missing
+ * chunks and returns a failure state instead of raising an error.
+ */
+#define TOAST_MISSING_OK (1 << 1)
+
+extern bool toast_tuple_init(ToastTupleContext *ttc, uint32 flags);
extern int toast_tuple_find_biggest_attribute(ToastTupleContext *ttc,
bool for_compression,
bool check_main);
diff --git a/src/test/recovery/meson.build b/src/test/recovery/meson.build
index e1cf57ff611..cba8a969831 100644
--- a/src/test/recovery/meson.build
+++ b/src/test/recovery/meson.build
@@ -68,6 +68,7 @@ tests += {
't/057_snapshot_commit_race.pl',
't/058_shutdown_crash_restart.pl',
't/059_remote_apply_status_interval.pl',
+ 't/099_rewrite_stale_xmin.pl',
],
},
}
diff --git a/src/test/recovery/t/099_rewrite_stale_xmin.pl b/src/test/recovery/t/099_rewrite_stale_xmin.pl
new file mode 100644
index 00000000000..fbccb5373a8
--- /dev/null
+++ b/src/test/recovery/t/099_rewrite_stale_xmin.pl
@@ -0,0 +1,124 @@
+# Copyright (c) 2025-2026, PostgreSQL Global Development Group
+#
+# Test that heap rewrites (CLUSTER, VACUUM FULL, REPACK) and index builds
+# work in the case when the backend's own xmin is held back by a transaction
+# in another database.
+
+use strict;
+use warnings;
+use PostgreSQL::Test::Cluster;
+use Test::More;
+
+my $node = PostgreSQL::Test::Cluster->new('primary');
+$node->init;
+# No Autovacuum, no random interferences.
+$node->append_conf(
+ 'postgresql.conf', qq[
+autovacuum = off
+]);
+$node->start;
+
+# Create two databases.
+$node->safe_psql('postgres', 'CREATE DATABASE db_holder');
+$node->safe_psql('postgres', 'CREATE DATABASE db_target');
+
+# Set up a table with TOAST data. Returns the toast table name.
+sub setup_table
+{
+ my ($tblname, $extra_ddl) = @_;
+ $extra_ddl //= '';
+
+ $node->safe_psql(
+ 'db_target', qq{
+ DROP TABLE IF EXISTS $tblname;
+ CREATE TABLE $tblname (id int PRIMARY KEY, data text)
+ WITH (autovacuum_enabled = off);
+ ALTER TABLE $tblname ALTER COLUMN data SET STORAGE EXTERNAL;
+ INSERT INTO $tblname VALUES (1, repeat('x', 2500));
+ INSERT INTO $tblname VALUES (2, repeat('z', 2500));
+ $extra_ddl
+ });
+
+ my $toast = $node->safe_psql(
+ 'db_target', qq{
+ SELECT 'pg_toast.' || relname FROM pg_class
+ WHERE oid = (SELECT reltoastrelid FROM pg_class
+ WHERE relname = '$tblname');
+ });
+ chomp $toast;
+ return $toast;
+}
+
+# Create precondition state. Requires that $holder is already running with
+# a write XID.
+sub create_missing_toast_state
+{
+ my ($tblname, $toast_table) = @_;
+
+ # Hold xmin in same DB to prevent main tuple removal.
+ my $xmin_holder = $node->background_psql('db_target', on_error_stop => 1);
+ $xmin_holder->query_safe("BEGIN ISOLATION LEVEL REPEATABLE READ");
+ $xmin_holder->query_safe("SELECT 1");
+
+ # Delete the row with TOAST data.
+ $node->safe_psql('db_target', "DELETE FROM $tblname WHERE id = 1");
+
+ # VACUUM main table only. The xmin_holder keeps the dead tuple.
+ $node->safe_psql('db_target', "VACUUM (PROCESS_TOAST false) $tblname");
+
+ # Release same-DB xmin.
+ $xmin_holder->query_safe("COMMIT");
+ $xmin_holder->quit;
+
+ # Vacuum toast table: toast chunks now DEAD and removed.
+ $node->safe_psql('db_target', "VACUUM $toast_table");
+}
+
+# Open a transaction holding an XID before any deletes. This XID will hold
+# back GetSnapshotData() globally, on a different database than the one
+# running the various rewrite operations.
+my $holder = $node->background_psql('db_holder', on_error_stop => 1);
+$holder->query_safe("BEGIN");
+$holder->query_safe("CREATE TEMP TABLE xid_holder(x int)");
+
+# Test 1: CLUSTER
+my $toast = setup_table('rewrite_test');
+create_missing_toast_state('rewrite_test', $toast);
+
+my ($ret, $stdout, $stderr) =
+ $node->psql('db_target', 'CLUSTER rewrite_test USING rewrite_test_pkey');
+is($ret, 0, "CLUSTER succeeds without missing-chunk error");
+unlike($stderr, qr/missing chunk/, "CLUSTER: no missing-chunk error");
+
+# Test 2: VACUUM FULL
+$toast = setup_table('rewrite_test');
+create_missing_toast_state('rewrite_test', $toast);
+
+($ret, $stdout, $stderr) =
+ $node->psql('db_target', 'VACUUM FULL rewrite_test');
+is($ret, 0, "VACUUM FULL succeeds without missing-chunk error");
+unlike($stderr, qr/missing chunk/, "VACUUM FULL: no missing-chunk error");
+
+# Test 3: REPACK
+$toast = setup_table('rewrite_test');
+create_missing_toast_state('rewrite_test', $toast);
+
+($ret, $stdout, $stderr) = $node->psql('db_target', 'REPACK rewrite_test');
+is($ret, 0, "REPACK succeeds without missing-chunk error");
+unlike($stderr, qr/missing chunk/, "REPACK: no missing-chunk error");
+
+# Test 4: CREATE INDEX on toasted column
+$toast = setup_table('rewrite_test');
+create_missing_toast_state('rewrite_test', $toast);
+
+($ret, $stdout, $stderr) = $node->psql('db_target',
+ 'CREATE INDEX rewrite_test_data_idx ON rewrite_test ((rewrite_test IS NOT NULL))');
+is($ret, 0, "CREATE INDEX succeeds without missing-chunk error");
+unlike($stderr, qr/missing chunk/, "CREATE INDEX: no missing-chunk error");
+
+# Cleanup.
+$holder->query_safe("COMMIT");
+$holder->quit;
+
+$node->stop;
+done_testing();
--
2.54.0 (Apple Git-157)
^ permalink raw reply [nested|flat] 33+ messages in thread
* Re: BUG #19519: REPACK can fail due to missing chunk for toast value
@ 2026-10-12 10:57 Matthias van de Meent <boekewurm+postgres@gmail.com>
parent: Matthias van de Meent <boekewurm+postgres@gmail.com>
0 siblings, 2 replies; 33+ messages in thread
From: Matthias van de Meent @ 2026-10-12 10:57 UTC (permalink / raw)
To: Michael Paquier <michael@paquier.xyz>; +Cc: Andrey Borodin <x4mmm@yandex-team.ru>; Heikki Linnakangas <hlinnaka@iki.fi>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; Imran Zaheer <imran.zhir@gmail.com>; Alexander Lakhin <exclusion@gmail.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>; Konstantin Knizhnik <knizhnik@garret.ru>
On Fri, 9 Oct 2026 at 14:56, Matthias van de Meent
<boekewurm+postgres@gmail.com> wrote:
>
> Attached is a flattened v6, containing v4 + the fixes descibed above.
And now v7, which fixes the bug in v6 that caused issues in the
integration suite, which I missed because I'd only tested with
regress+recovery.
The bug was that I failed to copy the visibility-related fields of the
heap tuple with inlined toast fields. Now that I've added that to the
patch the full test suite seems to pass just fine.
Kind regards,
Matthias van de Meent
Databricks (https://www.databricks.com)
Attachments:
v7-0001-Fix-missing-chunk-errors-during-heap-rewrites-and.patch (application/octet-stream, 50.5K) download
From 2809e16e74c50b3b99f4801ec079af268997bb40 Mon Sep 17 00:00:00 2001
From: Michael Paquier <michael@paquier.xyz>
Date: Thu, 9 Jul 2026 11:46:21 +0900
Subject: [PATCH v7] Fix "missing chunk" errors during heap rewrites and index
builds
Blah, blah.
These errors happen when the tuple produced by the SnapshotAny heap
scan is RECENTLY_DEAD. Other backends may already consider those
tuples completely dead, and thus can start cleaning up the TOAST tuples
through pruning.
This problem has been reported recently by Alexander for REPACK, but it
is a much older issue (tested down to 9.5 for curiosity's sake, but I
suspect that it is much older than that).
XXX: This patch includes both TAP and isolation tests. We should remove
one pattern at the end.
XXX: Posible future improvement:
* TOAST tuple visibility is not 1:1 to heap tuple visibility, so it's
possible (and some workloads: likely) that the RECENTLY_DEAD main
tuple has normal visible toast data. If we can pass along the
visibility info of the toast data instead of always fully detoasting
the datum that could save us from performing further expensive
operations.
Reported-by: Alexander Lakhin <exclusion@gmail.com>
Co-authored-by: Michael Paquier <michael@paquier.xyz>
Co-authored-by: Matthias van de Meent <boekewurm+postgres@gmail.com>
Discussion: https://postgr.es/m/18351-f6e06364b3a2e669@postgresql.org
Discussion: https://postgr.es/m/19519-fe02d8ff679d834d@postgresql.org
---
contrib/dblink/.gitignore | 2 +
contrib/dblink/Makefile | 2 +
.../dblink/expected/rewrite_stale_xmin.out | 237 ++++++++++++++
contrib/dblink/meson.build | 5 +
contrib/dblink/specs/rewrite_stale_xmin.spec | 137 ++++++++
src/backend/access/common/detoast.c | 42 ++-
src/backend/access/heap/heapam.c | 4 +-
src/backend/access/heap/heapam_handler.c | 302 +++++++++++++++++-
src/backend/access/heap/heaptoast.c | 50 ++-
src/backend/access/heap/rewriteheap.c | 44 ++-
src/backend/access/table/toast_helper.c | 46 ++-
src/include/access/detoast.h | 9 +
src/include/access/heaptoast.h | 18 +-
src/include/access/rewriteheap.h | 6 +-
src/include/access/tableam.h | 26 +-
src/include/access/toast_helper.h | 10 +-
src/test/recovery/meson.build | 1 +
src/test/recovery/t/099_rewrite_stale_xmin.pl | 124 +++++++
18 files changed, 1009 insertions(+), 56 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/recovery/t/099_rewrite_stale_xmin.pl
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..2e5a7940ea2
--- /dev/null
+++ b/contrib/dblink/expected/rewrite_stale_xmin.out
@@ -0,0 +1,237 @@
+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_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)
+
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..fe88e789f85
--- /dev/null
+++ b/contrib/dblink/specs/rewrite_stale_xmin.spec
@@ -0,0 +1,137 @@
+# Test that heap rewrites work when the rewriting backend's own xmin is
+# held back by a transaction in another database.
+
+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_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;
+}
+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);
+}
+
+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
+
+# 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
diff --git a/src/backend/access/common/detoast.c b/src/backend/access/common/detoast.c
index a9d4e3ae98e..52a7b9a0c7b 100644
--- a/src/backend/access/common/detoast.c
+++ b/src/backend/access/common/detoast.c
@@ -17,13 +17,14 @@
#include "access/table.h"
#include "access/tableam.h"
#include "access/toast_compression.h"
+#include "access/toast_helper.h"
#include "access/toast_internals.h"
#include "common/int.h"
#include "common/pg_lzcompress.h"
#include "utils/expandeddatum.h"
#include "utils/rel.h"
-static varlena *toast_fetch_datum(varlena *attr);
+static varlena *toast_fetch_datum(varlena *attr, uint32 flags);
static varlena *toast_fetch_datum_slice(varlena *attr,
int32 sliceoffset,
int32 slicelength);
@@ -52,7 +53,7 @@ detoast_external_attr(varlena *attr)
/*
* This is an external stored plain value
*/
- result = toast_fetch_datum(attr);
+ result = toast_fetch_datum(attr, 0);
}
else if (VARATT_IS_EXTERNAL_INDIRECT(attr))
{
@@ -103,6 +104,23 @@ detoast_external_attr(varlena *attr)
}
+/* ----------
+ * detoast_external_attr_extended -
+ *
+ * Like detoast_external_attr, but returns NULL if toast chunks are
+ * missing for external pointers.
+ * ----------
+ */
+varlena *
+detoast_external_attr_extended(varlena *attr)
+{
+ if (VARATT_IS_EXTERNAL_ONDISK(attr))
+ return toast_fetch_datum(attr, TOAST_MISSING_OK);
+ else
+ return detoast_external_attr(attr);
+}
+
+
/* ----------
* detoast_attr -
*
@@ -121,7 +139,7 @@ detoast_attr(varlena *attr)
/*
* This is an externally stored datum --- fetch it back from there
*/
- attr = toast_fetch_datum(attr);
+ attr = toast_fetch_datum(attr, 0);
/* If it's compressed, decompress it */
if (VARATT_IS_COMPRESSED(attr))
{
@@ -268,7 +286,7 @@ detoast_attr_slice(varlena *attr,
preslice = toast_fetch_datum_slice(attr, 0, max_size);
}
else
- preslice = toast_fetch_datum(attr);
+ preslice = toast_fetch_datum(attr, 0);
}
else if (VARATT_IS_EXTERNAL_INDIRECT(attr))
{
@@ -343,10 +361,12 @@ detoast_attr_slice(varlena *attr,
*
* Reconstruct an in memory Datum from the chunks saved
* in the toast relation
+ *
+ * If flags uses TOAST_MISSING_OK, returns NULL when chunks are missing.
* ----------
*/
static varlena *
-toast_fetch_datum(varlena *attr)
+toast_fetch_datum(varlena *attr, uint32 flags)
{
Relation toastrel;
varlena *result;
@@ -380,8 +400,14 @@ toast_fetch_datum(varlena *attr)
toastrel = table_open(toastrelid, AccessShareLock);
/* Fetch all chunks */
- table_relation_fetch_toast_slice(toastrel, valueid,
- attrsize, 0, attrsize, result);
+ if (!table_relation_fetch_toast_slice(toastrel, valueid,
+ attrsize, 0, attrsize, result,
+ flags))
+ {
+ pfree(result);
+ table_close(toastrel, AccessShareLock);
+ return NULL;
+ }
/* Close toast table */
table_close(toastrel, AccessShareLock);
@@ -466,7 +492,7 @@ toast_fetch_datum_slice(varlena *attr, int32 sliceoffset,
/* Fetch all chunks */
table_relation_fetch_toast_slice(toastrel, valueid,
attrsize, sliceoffset, slicelength,
- result);
+ result, 0);
/* Close toast table */
table_close(toastrel, AccessShareLock);
diff --git a/src/backend/access/heap/heapam.c b/src/backend/access/heap/heapam.c
index 5c1eaadd442..8e4f0f956bd 100644
--- a/src/backend/access/heap/heapam.c
+++ b/src/backend/access/heap/heapam.c
@@ -2264,7 +2264,7 @@ heap_prepare_insert(Relation relation, HeapTuple tup, TransactionId xid,
return tup;
}
else if (HeapTupleHasExternal(tup) || tup->t_len > TOAST_TUPLE_THRESHOLD)
- return heap_toast_insert_or_update(relation, tup, NULL, options);
+ return heap_toast_insert_or_update(relation, tup, NULL, options, 0);
else
return tup;
}
@@ -3968,7 +3968,7 @@ l2:
* tuples too. We never skip the FSM here.
*/
heaptup = heap_toast_insert_or_update(relation, newtup, &oldtup,
- walLogical ? 0 : HEAP_INSERT_NO_LOGICAL);
+ walLogical ? 0 : HEAP_INSERT_NO_LOGICAL, 0);
newtupsize = MAXALIGN(heaptup->t_len);
}
else
diff --git a/src/backend/access/heap/heapam_handler.c b/src/backend/access/heap/heapam_handler.c
index 7d2065dec37..b1df7d19863 100644
--- a/src/backend/access/heap/heapam_handler.c
+++ b/src/backend/access/heap/heapam_handler.c
@@ -19,6 +19,7 @@
*/
#include "postgres.h"
+#include "access/detoast.h"
#include "access/genam.h"
#include "access/heapam.h"
#include "access/heaptoast.h"
@@ -26,6 +27,7 @@
#include "access/rewriteheap.h"
#include "access/syncscan.h"
#include "access/tableam.h"
+#include "access/toast_helper.h"
#include "access/tsmapi.h"
#include "access/visibilitymap.h"
#include "access/xact.h"
@@ -36,6 +38,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"
@@ -48,9 +51,11 @@
#include "utils/rel.h"
#include "utils/tuplesort.h"
-static void reform_and_rewrite_tuple(HeapTuple tuple,
+/* See toast_helper.h for values of "flags" */
+static bool reform_and_rewrite_tuple(HeapTuple tuple,
Relation OldHeap, Relation NewHeap,
- Datum *values, bool *isnull, RewriteState rwstate);
+ Datum *values, bool *isnull, RewriteState rwstate,
+ bool recently_dead);
static void heap_insert_for_repack(HeapTuple tuple, Relation OldHeap,
Relation NewHeap, Datum *values, bool *isnull,
BulkInsertState bistate);
@@ -703,6 +708,7 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,
HeapTuple tuple;
Buffer buf;
bool isdead;
+ bool recently_dead = false;
CHECK_FOR_INTERRUPTS();
@@ -789,6 +795,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 */
@@ -822,6 +829,7 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,
RelationGetRelationName(OldHeap));
/* treat as recently dead */
*tups_recently_dead += 1;
+ recently_dead = true;
isdead = false;
break;
default:
@@ -850,6 +858,115 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,
*num_tuples += 1;
if (tuplesort != NULL)
{
+ /*
+ * For RECENTLY_DEAD tuples, retrieve TOAST data that's still
+ * available before putting the tuple in the sort. If a concurrent
+ * VACUUM (or page prune) already reclaimed parts of that TOAST data,
+ * we can skip the tuple.
+ */
+ if (recently_dead && HeapTupleHasExternal(tuple))
+ {
+ Bitmapset *detoasted = NULL;
+ bool skip = false;
+ HeapTuple replacement;
+
+ heap_deform_tuple(tuple, oldTupDesc, values, isnull);
+
+ for (int i = 0; i < oldTupDesc->natts; i++)
+ {
+ Form_pg_attribute att = TupleDescAttr(oldTupDesc, i);
+ varlena *d;
+
+ /* ignore non-varlena, dropped, and */
+ if (att->attlen != -1)
+ continue;
+ /* Set to NULL to avoid including it in serialization later on, if relevant */
+ if (att->attisdropped)
+ {
+ isnull[i] = true;
+ continue;
+ }
+
+ if (isnull[i])
+ continue;
+
+ d = DatumGetPointer(values[i]);
+
+ /* not external means no toast cleanup race */
+ if (!VARATT_IS_EXTERNAL_ONDISK(d))
+ continue;
+
+ /* actually detoast the value */
+ d = detoast_external_attr_extended(d);
+
+ if (d == NULL)
+ {
+ skip = true;
+ break;
+ }
+ detoasted = bms_add_member(detoasted, i);
+ values[i] = PointerGetDatum(d);
+ }
+
+ if (skip)
+ {
+ *num_tuples -= 1;
+ *tups_vacuumed += 1;
+ *tups_recently_dead -= 1;
+
+ goto cleanup_and_next;
+ }
+
+ /* no new resources allocated, store unprocessed tuple as normal */
+ if (bms_is_empty(detoasted))
+ goto normal_put;
+
+ /*
+ * The tuple contained visible externally toasted attributes,
+ * inline the attributes into the heaptuple to avoid later
+ * detoasting failures.
+ */
+ replacement = heap_form_tuple(oldTupDesc, values, isnull);
+
+ /* fill in the revelant identity and visibility data */
+ replacement->t_data->t_choice = tuple->t_data->t_choice;
+ replacement->t_data->t_ctid = tuple->t_data->t_ctid;
+
+ replacement->t_data->t_infomask2 &= ~HEAP2_XACT_MASK;
+ replacement->t_data->t_infomask2 |=
+ tuple->t_data->t_infomask2 & HEAP2_XACT_MASK;
+ replacement->t_data->t_infomask &= ~HEAP_XACT_MASK;
+ replacement->t_data->t_infomask |=
+ tuple->t_data->t_infomask & HEAP_XACT_MASK;
+ replacement->t_self = tuple->t_self;
+
+ /* put the tuple into the tuplesort */
+ tuplesort_putheaptuple(tuplesort, replacement);
+
+ /* and finally clean up now that we're done */
+ pfree(replacement);
+
+ /*
+ * In scan-and-sort mode, report increase in number of tuples
+ * scanned
+ */
+ pgstat_progress_update_param(PROGRESS_REPACK_HEAP_TUPLES_SCANNED,
+ *num_tuples);
+
+cleanup_and_next:
+ for (int i = bms_next_member(detoasted, -1);
+ i >= 0;
+ i = bms_prev_member(detoasted, i))
+ {
+ pfree(DatumGetPointer(values[i]));
+ }
+
+ bms_free(detoasted);
+ detoasted = NULL;
+ continue;
+ }
+
+normal_put:
tuplesort_putheaptuple(tuplesort, tuple);
/*
@@ -868,8 +985,22 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,
int64 ct_val[2];
if (!concurrent)
- reform_and_rewrite_tuple(tuple, OldHeap, NewHeap,
- values, isnull, rwstate);
+ {
+ if (!reform_and_rewrite_tuple(tuple, OldHeap, NewHeap,
+ values, isnull, rwstate,
+ recently_dead))
+ {
+ Assert(recently_dead);
+ /*
+ * Missing TOAST chunks for a recently-dead tuple. Treat
+ * it as dead.
+ */
+ *tups_vacuumed += 1;
+ *num_tuples -= 1;
+ *tups_recently_dead -= 1;
+ continue;
+ }
+ }
else
heap_insert_for_repack(tuple, OldHeap, NewHeap,
values, isnull, bistate);
@@ -921,10 +1052,12 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,
n_tuples += 1;
if (!concurrent)
- reform_and_rewrite_tuple(tuple,
- OldHeap, NewHeap,
- values, isnull,
- rwstate);
+ {
+ (void) reform_and_rewrite_tuple(tuple,
+ OldHeap, NewHeap,
+ values, isnull,
+ rwstate, false);
+ }
else
heap_insert_for_repack(tuple, OldHeap, NewHeap,
values, isnull, bistate);
@@ -1156,6 +1289,7 @@ heapam_index_build_range_scan(Relation heapRelation,
BlockNumber previous_blkno = InvalidBlockNumber;
BlockNumber root_blkno = InvalidBlockNumber;
OffsetNumber root_offsets[MaxHeapTuplesPerPage];
+ Bitmapset *detoast_index_attrs = NULL;
/*
* sanity checks
@@ -1252,6 +1386,70 @@ heapam_index_build_range_scan(Relation heapRelation,
!TransactionIdIsValid(OldestXmin));
Assert(snapshot == SnapshotAny || !anyvisible);
+ /*
+ * Extract the set of attributes an index may need to detoast, including
+ * expressions and predicates.
+ */
+ for (int i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
+ {
+ int attnum = indexInfo->ii_IndexAttrNumbers[i];
+
+ if (attnum != 0)
+ detoast_index_attrs = bms_add_member(detoast_index_attrs,
+ attnum - FirstLowInvalidHeapAttributeNumber);
+ }
+ pull_varattnos((Node *) indexInfo->ii_Expressions, 1, &detoast_index_attrs);
+ pull_varattnos((Node *) indexInfo->ii_Predicate, 1, &detoast_index_attrs);
+
+ /*
+ * Post-process the attribute bitmap.
+ *
+ * We remove all non-varlena attributes (we don't need to check them
+ * during detoasting), and add all varlena attributes if the index
+ * contains a whole-row expression.
+ */
+ if (bms_is_member(-FirstLowInvalidHeapAttributeNumber, detoast_index_attrs))
+ {
+ TupleDesc desc = RelationGetDescr(heapRelation);
+
+ for (AttrNumber i = RelationGetNumberOfAttributes(heapRelation); i > 0; i--)
+ {
+ AttrNumber offset = i - FirstLowInvalidHeapAttributeNumber;
+ CompactAttribute *att = TupleDescCompactAttr(desc, i - 1);
+
+ /*
+ * If the attribute is varlena, add it to the map, else remove
+ * the attribute.
+ * We work backwards to avoid reallocations.
+ */
+ if (att->attlen == -1)
+ detoast_index_attrs = bms_add_member(detoast_index_attrs, offset);
+ else
+ detoast_index_attrs = bms_del_member(detoast_index_attrs, offset);
+ }
+
+ detoast_index_attrs = bms_del_member(detoast_index_attrs, -FirstLowInvalidHeapAttributeNumber);
+ }
+ else
+ {
+ TupleDesc desc = RelationGetDescr(heapRelation);
+
+ for (AttrNumber i = RelationGetNumberOfAttributes(heapRelation); i > 0; i--)
+ {
+ AttrNumber offset = i - FirstLowInvalidHeapAttributeNumber;
+ CompactAttribute *att = TupleDescCompactAttr(desc, i - 1);
+
+ /*
+ * If the attribute is not varlena, remove the attribute from
+ * tracking.
+ *
+ * We work backwards to avoid reallocations.
+ */
+ if (att->attlen != -1)
+ detoast_index_attrs = bms_del_member(detoast_index_attrs, offset);
+ }
+ }
+
/* Publish number of blocks to scan */
if (progress)
{
@@ -1289,6 +1487,7 @@ heapam_index_build_range_scan(Relation heapRelation,
while ((heapTuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
{
bool tupleIsAlive;
+ Bitmapset *detoasted_attrs = NULL;
CHECK_FOR_INTERRUPTS();
@@ -1590,6 +1789,61 @@ heapam_index_build_range_scan(Relation heapRelation,
/* Set up for predicate or expression evaluation */
ExecStoreBufferHeapTuple(heapTuple, slot, hscan->rs_cbuf);
+ /* For RECENTLY_DEAD tuples, pre-detoast external TOAST values. */
+ if (!tupleIsAlive && !bms_is_empty(detoast_index_attrs))
+ {
+ bool skip = false;
+ int attno;
+
+ /*
+ * Only get the attributes up to the last attribute we want to
+ * detoast.
+ */
+ attno = bms_prev_member(detoast_index_attrs, -1);
+ slot_getsomeattrs(slot, attno + FirstLowInvalidHeapAttributeNumber);
+
+ /*
+ * Iterate over the attributes which are now in tts_isnull/
+ * tts_values slots, and detoast them where needed.
+ */
+ attno = -1;
+ while ((attno = bms_next_member(detoast_index_attrs, attno)) >= 0)
+ {
+ int attnum = attno + FirstLowInvalidHeapAttributeNumber;
+ varlena *toastptr;
+
+ if (attnum <= 0)
+ continue; /* system column */
+
+ Assert(TupleDescCompactAttr(RelationGetDescr(heapRelation), attnum - 1)->attlen == -1);
+
+ if (slot->tts_isnull[attnum - 1])
+ continue;
+
+ toastptr = DatumGetPointer(slot->tts_values[attnum - 1]);
+
+ if (VARATT_IS_EXTERNAL_ONDISK(toastptr))
+ {
+ varlena *detoasted;
+
+ detoasted = detoast_external_attr_extended(toastptr);
+
+ if (detoasted == NULL)
+ {
+ skip = true;
+ break;
+ }
+
+ slot->tts_values[attnum - 1] = PointerGetDatum(detoasted);
+
+ detoasted_attrs = bms_add_member(detoasted_attrs, attnum);
+ }
+ }
+
+ if (skip)
+ goto cleanup_and_next;
+ }
+
/*
* In a partial index, discard tuples that don't satisfy the
* predicate.
@@ -1597,7 +1851,7 @@ heapam_index_build_range_scan(Relation heapRelation,
if (predicate != NULL)
{
if (!ExecQual(predicate, econtext))
- continue;
+ goto cleanup_and_next;
}
/*
@@ -1663,6 +1917,21 @@ heapam_index_build_range_scan(Relation heapRelation,
callback(indexRelation, &heapTuple->t_self, values, isnull,
tupleIsAlive, callback_state);
}
+
+cleanup_and_next:
+ if (!bms_is_empty(detoasted_attrs))
+ {
+ int attno = -1;
+
+ while ((attno = bms_next_member(detoasted_attrs, attno)) != -2)
+ {
+ Assert(attno > 0);
+ pfree(DatumGetPointer(slot->tts_values[attno - 1]));
+ }
+
+ bms_free(detoasted_attrs);
+ detoasted_attrs = NULL;
+ }
}
/* Report scan progress one last time. */
@@ -2334,20 +2603,29 @@ heapam_scan_sample_next_tuple(TableScanDesc scan, SampleScanState *scanstate,
* SET WITHOUT OIDS.
*
* So, we must reconstruct the tuple from component Datums.
+ *
+ * Returns true on success, and false on failure if flags uses
+ * TOAST_MISSING_OK. See toast_helper.h.
*/
-static void
+static bool
reform_and_rewrite_tuple(HeapTuple tuple,
Relation OldHeap, Relation NewHeap,
- Datum *values, bool *isnull, RewriteState rwstate)
+ Datum *values, bool *isnull, RewriteState rwstate,
+ bool recently_dead)
{
HeapTuple newtuple;
newtuple = reform_tuple(tuple, OldHeap, NewHeap, values, isnull);
/* The heap rewrite module does the rest */
- rewrite_heap_tuple(rwstate, tuple, newtuple);
+ if (!rewrite_heap_tuple(rwstate, tuple, newtuple, recently_dead))
+ {
+ heap_freetuple(newtuple);
+ return false;
+ }
heap_freetuple(newtuple);
+ return true;
}
/*
diff --git a/src/backend/access/heap/heaptoast.c b/src/backend/access/heap/heaptoast.c
index b03d8492959..38cb9545965 100644
--- a/src/backend/access/heap/heaptoast.c
+++ b/src/backend/access/heap/heaptoast.c
@@ -84,9 +84,10 @@ heap_toast_delete(Relation rel, HeapTuple oldtup, bool is_speculative)
* newtup: the candidate new tuple to be inserted
* oldtup: the old row version for UPDATE, or NULL for INSERT
* options: options to be passed to heap_insert() for toast rows
+ * flags: additional control flags, see heaptoast.h.
* Result:
- * either newtup if no toasting is needed, or a palloc'd modified tuple
- * that is what should actually get stored
+ * either newtup if no toasting is needed, a palloc'd modified tuple
+ * that is what should actually get stored, or NULL.
*
* NOTE: neither newtup nor oldtup will be modified. This is a change
* from the pre-8.1 API of this routine.
@@ -94,7 +95,7 @@ heap_toast_delete(Relation rel, HeapTuple oldtup, bool is_speculative)
*/
HeapTuple
heap_toast_insert_or_update(Relation rel, HeapTuple newtup, HeapTuple oldtup,
- uint32 options)
+ uint32 options, uint32 flags)
{
HeapTuple result_tuple;
TupleDesc tupleDesc;
@@ -154,7 +155,8 @@ heap_toast_insert_or_update(Relation rel, HeapTuple newtup, HeapTuple oldtup,
ttc.ttc_oldisnull = toast_oldisnull;
}
ttc.ttc_attr = toast_attr;
- toast_tuple_init(&ttc);
+ if (!toast_tuple_init(&ttc, flags))
+ return NULL;
/* ----------
* Compress and/or save external until data fits into target length
@@ -621,11 +623,15 @@ toast_build_flattened_tuple(TupleDesc tupleDesc,
* sliceoffset is the byte offset within the TOAST value from which to fetch.
* slicelength is the number of bytes to be fetched from the TOAST value.
* result is the varlena into which the results should be written.
+ * flags records more options, see toast_helper.h.
+ *
+ * Returns true on success, or false if flags uses TOAST_MISSING_OK and
+ * chunks are missing rather than raising an error.
*/
-void
+bool
heap_fetch_toast_slice(Relation toastrel, Oid8 valueid, int32 attrsize,
int32 sliceoffset, int32 slicelength,
- varlena *result)
+ varlena *result, uint32 flags)
{
Relation *toastidxs;
ScanKeyData toastkey[3];
@@ -737,28 +743,47 @@ heap_fetch_toast_slice(Relation toastrel, Oid8 valueid, int32 attrsize,
/*
* Some checks on the data we've found
*/
+
if (curchunk != expectedchunk)
+ {
+ if (flags & TOAST_MISSING_OK)
+ goto toast_broken_missing_ok;
+
ereport(ERROR,
(errcode(ERRCODE_DATA_CORRUPTED),
errmsg_internal("unexpected chunk number %d (expected %d) for toast value %" PRIu64 " in %s",
curchunk, expectedchunk, valueid,
RelationGetRelationName(toastrel))));
+ }
+
if (curchunk > endchunk)
+ {
+ if (flags & TOAST_MISSING_OK)
+ goto toast_broken_missing_ok;
+
ereport(ERROR,
(errcode(ERRCODE_DATA_CORRUPTED),
errmsg_internal("unexpected chunk number %d (out of range %d..%d) for toast value %" PRIu64 " in %s",
curchunk,
startchunk, endchunk, valueid,
RelationGetRelationName(toastrel))));
+ }
+
expected_size = curchunk < totalchunks - 1 ? max_chunk_size
: attrsize - ((totalchunks - 1) * max_chunk_size);
+
if (chunksize != expected_size)
+ {
+ if (flags & TOAST_MISSING_OK)
+ goto toast_broken_missing_ok;
+
ereport(ERROR,
(errcode(ERRCODE_DATA_CORRUPTED),
errmsg_internal("unexpected chunk size %d (expected %d) in chunk %d of %d for toast value %" PRIu64 " in %s",
chunksize, expected_size,
curchunk, totalchunks, valueid,
RelationGetRelationName(toastrel))));
+ }
/*
* Copy the data into proper place in our result
@@ -782,13 +807,26 @@ heap_fetch_toast_slice(Relation toastrel, Oid8 valueid, int32 attrsize,
* Final checks that we successfully fetched the datum
*/
if (expectedchunk != (endchunk + 1))
+ {
+ if (flags & TOAST_MISSING_OK)
+ goto toast_broken_missing_ok;
+
ereport(ERROR,
(errcode(ERRCODE_DATA_CORRUPTED),
errmsg_internal("missing chunk number %d for toast value %" PRIu64 " in %s",
expectedchunk, valueid,
RelationGetRelationName(toastrel))));
+ }
+
+ /* End scan and close indexes. */
+ systable_endscan_ordered(toastscan);
+ toast_close_indexes(toastidxs, num_indexes, AccessShareLock);
+
+ return true;
+toast_broken_missing_ok:
/* End scan and close indexes. */
systable_endscan_ordered(toastscan);
toast_close_indexes(toastidxs, num_indexes, AccessShareLock);
+ return false;
}
diff --git a/src/backend/access/heap/rewriteheap.c b/src/backend/access/heap/rewriteheap.c
index 0648e433031..0d57b3f5709 100644
--- a/src/backend/access/heap/rewriteheap.c
+++ b/src/backend/access/heap/rewriteheap.c
@@ -115,6 +115,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
#include "pgstat.h"
+#include "access/toast_helper.h"
#include "replication/slot.h"
#include "storage/bufmgr.h"
#include "storage/bulk_write.h"
@@ -172,6 +173,7 @@ typedef struct
{
TidHashKey key; /* expected xmin/old location of B tuple */
ItemPointerData old_tid; /* A's location in the old heap */
+ bool recently_dead; /* tuple was recently_dead on access */
HeapTuple tuple; /* A's tuple contents */
} UnresolvedTupData;
@@ -211,7 +213,8 @@ typedef struct RewriteMappingDataEntry
/* prototypes for internal functions */
-static void raw_heap_insert(RewriteState state, HeapTuple tup);
+static bool raw_heap_insert(RewriteState state, HeapTuple tup,
+ bool recently_dead);
/* internal logical remapping prototypes */
static void logical_begin_heap_rewrite(RewriteState state);
@@ -309,7 +312,7 @@ end_heap_rewrite(RewriteState state)
while ((unresolved = hash_seq_search(&seq_status)) != NULL)
{
ItemPointerSetInvalid(&unresolved->tuple->t_data->t_ctid);
- raw_heap_insert(state, unresolved->tuple);
+ raw_heap_insert(state, unresolved->tuple, unresolved->recently_dead);
}
/* Write the last page, if any */
@@ -338,9 +341,10 @@ end_heap_rewrite(RewriteState state)
* old_tuple original tuple in the old heap
* new_tuple new, rewritten tuple to be inserted to new heap
*/
-void
+bool
rewrite_heap_tuple(RewriteState state,
- HeapTuple old_tuple, HeapTuple new_tuple)
+ HeapTuple old_tuple, HeapTuple new_tuple,
+ bool recently_dead)
{
MemoryContext old_cxt;
ItemPointerData old_tid;
@@ -431,13 +435,14 @@ rewrite_heap_tuple(RewriteState state,
unresolved->old_tid = old_tuple->t_self;
unresolved->tuple = heap_copytuple(new_tuple);
+ unresolved->recently_dead = recently_dead;
/*
* We can't do anything more now, since we don't know where the
* tuple will be written.
*/
MemoryContextSwitchTo(old_cxt);
- return;
+ return true;
}
}
@@ -455,7 +460,13 @@ rewrite_heap_tuple(RewriteState state,
ItemPointerData new_tid;
/* Insert the tuple and find out where it's put in new_heap */
- raw_heap_insert(state, new_tuple);
+ if (!raw_heap_insert(state, new_tuple, recently_dead))
+ {
+ if (free_new)
+ heap_freetuple(new_tuple);
+ MemoryContextSwitchTo(old_cxt);
+ return false;
+ }
new_tid = new_tuple->t_self;
logical_rewrite_heap_tuple(state, old_tid, new_tuple);
@@ -496,6 +507,7 @@ rewrite_heap_tuple(RewriteState state,
new_tuple = unresolved->tuple;
free_new = true;
old_tid = unresolved->old_tid;
+ recently_dead = unresolved->recently_dead;
new_tuple->t_data->t_ctid = new_tid;
/*
@@ -532,6 +544,7 @@ rewrite_heap_tuple(RewriteState state,
}
MemoryContextSwitchTo(old_cxt);
+ return true;
}
/*
@@ -592,9 +605,17 @@ rewrite_heap_dead_tuple(RewriteState state, HeapTuple old_tuple)
* t_self of the tuple is set to the new TID of the tuple. If t_ctid of the
* tuple is invalid on entry, it's replaced with the new TID as well (in
* the inserted data only, not in the caller's copy).
+ *
+ * recently_dead is for CLUSTER-related tasks, that insert recently_dead
+ * tuples, and thus can't assume there's no concurrent MVCC cleanup of its
+ * dependent data. Setting this flag increases the level of paranoia applied
+ * when processing TOAST.
+ *
+ * If TOAST data is missing with `recently_dead set, this function will not
+ * insert the tuple, but instead return false.
*/
-static void
-raw_heap_insert(RewriteState state, HeapTuple tup)
+static bool
+raw_heap_insert(RewriteState state, HeapTuple tup, bool recently_dead)
{
Page page;
Size pageFreeSpace,
@@ -619,6 +640,7 @@ raw_heap_insert(RewriteState state, HeapTuple tup)
else if (HeapTupleHasExternal(tup) || tup->t_len > TOAST_TUPLE_THRESHOLD)
{
uint32 options = HEAP_INSERT_SKIP_FSM;
+ uint32 toastflags = recently_dead ? TOAST_MISSING_OK : 0;
/*
* While rewriting the heap for REPACK, make sure data for the TOAST
@@ -628,7 +650,9 @@ raw_heap_insert(RewriteState state, HeapTuple tup)
options |= HEAP_INSERT_NO_LOGICAL;
heaptup = heap_toast_insert_or_update(state->rs_new_rel, tup, NULL,
- options);
+ options, toastflags);
+ if (heaptup == NULL)
+ return false;
}
else
heaptup = tup;
@@ -702,6 +726,8 @@ raw_heap_insert(RewriteState state, HeapTuple tup)
/* If heaptup is a private copy, release it. */
if (heaptup != tup)
heap_freetuple(heaptup);
+
+ return true;
}
/* ------------------------------------------------------------------------
diff --git a/src/backend/access/table/toast_helper.c b/src/backend/access/table/toast_helper.c
index 2613d9dc095..a8e58d8573c 100644
--- a/src/backend/access/table/toast_helper.c
+++ b/src/backend/access/table/toast_helper.c
@@ -36,9 +36,13 @@
* toast_flags is just a single uint8, but toast_attr is a caller-provided
* array with a length equal to tupleDesc->natts. The caller need not
* perform any initialization of the array before calling this function.
+ *
+ * If flags uses TOAST_MISSING_OK and an external TOAST value cannot be
+ * fetched, returns false instead of raising an error. Returns true on
+ * success. See toast_helper.h.
*/
-void
-toast_tuple_init(ToastTupleContext *ttc)
+bool
+toast_tuple_init(ToastTupleContext *ttc, uint32 flags)
{
TupleDesc tupleDesc = ttc->ttc_rel->rd_att;
int numAttrs = tupleDesc->natts;
@@ -141,7 +145,30 @@ toast_tuple_init(ToastTupleContext *ttc)
if (VARATT_IS_EXTERNAL(new_value))
{
ttc->ttc_attr[i].tai_oldexternal = new_value;
- if (att->attstorage == TYPSTORAGE_PLAIN)
+
+ /* first, make sure to read the data from disk and into memory */
+ if ((flags & TOAST_MISSING_OK) != 0 &&
+ VARATT_IS_EXTERNAL_ONDISK(new_value))
+ {
+ new_value = detoast_external_attr_extended(new_value);
+ if (new_value == NULL)
+ goto broken_toast_missing_ok;
+ /*
+ * STORAGE_PLAIN doesn't allow compressed data here,
+ * so manually decompress here through detoast_attr() now
+ * that the value has been extracted from the toast table.
+ */
+ if (att->attstorage == TYPSTORAGE_PLAIN &&
+ VARATT_IS_COMPRESSED(new_value))
+ {
+ varlena *nv = detoast_attr(new_value);
+
+ Assert(nv != new_value);
+ pfree(new_value);
+ new_value = nv;
+ }
+ }
+ else if (att->attstorage == TYPSTORAGE_PLAIN)
new_value = detoast_attr(new_value);
else
new_value = detoast_external_attr(new_value);
@@ -163,6 +190,19 @@ toast_tuple_init(ToastTupleContext *ttc)
ttc->ttc_attr[i].tai_colflags |= TOASTCOL_IGNORE;
}
}
+
+ return true;
+
+broken_toast_missing_ok:
+ for (; i > 0; i--)
+ {
+ if (ttc->ttc_attr[i].tai_colflags & TOASTCOL_NEEDS_FREE)
+ {
+ pfree(DatumGetPointer(ttc->ttc_values[i]));
+ ttc->ttc_attr[i].tai_colflags &= ~TOASTCOL_NEEDS_FREE;
+ }
+ }
+ return false;
}
/*
diff --git a/src/include/access/detoast.h b/src/include/access/detoast.h
index 93b7a253760..c5411b34fcc 100644
--- a/src/include/access/detoast.h
+++ b/src/include/access/detoast.h
@@ -91,6 +91,15 @@ toast_external_info_get(const struct varlena *attr, toast_external_data *toast_e
*/
extern varlena *detoast_external_attr(varlena *attr);
+/* ----------
+ * detoast_external_attr_extended() -
+ *
+ * Like detoast_external_attr, but returns NULL if toast chunks
+ * are missing (instead of raising an error).
+ * ----------
+ */
+extern varlena *detoast_external_attr_extended(varlena *attr);
+
/* ----------
* detoast_attr() -
*
diff --git a/src/include/access/heaptoast.h b/src/include/access/heaptoast.h
index 4c3fda8a5f9..301b33aa970 100644
--- a/src/include/access/heaptoast.h
+++ b/src/include/access/heaptoast.h
@@ -105,11 +105,15 @@
/* ----------
* heap_toast_insert_or_update -
*
- * Called by heap_insert() and heap_update().
+ * Called by heap_insert() and heap_update(). Returns NULL if the
+ * insert/update could not be completed.
+ *
+ * See toast_helper.h for the values of "flags".
* ----------
*/
extern HeapTuple heap_toast_insert_or_update(Relation rel, HeapTuple newtup,
- HeapTuple oldtup, uint32 options);
+ HeapTuple oldtup, uint32 options,
+ uint32 flags);
/* ----------
* heap_toast_delete -
@@ -153,11 +157,15 @@ extern HeapTuple toast_build_flattened_tuple(TupleDesc tupleDesc,
/* ----------
* heap_fetch_toast_slice
*
- * Fetch a slice from a toast value stored in a heap table.
+ * Fetch a slice from a toast value stored in a heap table. Returns
+ * false if the slice could not be fetched, otherwise true on success.
+ *
+ * See toast_helper.h for the values of "flags".
* ----------
*/
-extern void heap_fetch_toast_slice(Relation toastrel, Oid8 valueid,
+extern bool heap_fetch_toast_slice(Relation toastrel, Oid8 valueid,
int32 attrsize, int32 sliceoffset,
- int32 slicelength, varlena *result);
+ int32 slicelength, varlena *result,
+ uint32 flags);
#endif /* HEAPTOAST_H */
diff --git a/src/include/access/rewriteheap.h b/src/include/access/rewriteheap.h
index 6ccf7b45c04..67467c2ddbe 100644
--- a/src/include/access/rewriteheap.h
+++ b/src/include/access/rewriteheap.h
@@ -25,8 +25,10 @@ extern RewriteState begin_heap_rewrite(Relation old_heap, Relation new_heap,
TransactionId oldest_xmin, TransactionId freeze_xid,
MultiXactId cutoff_multi);
extern void end_heap_rewrite(RewriteState state);
-extern void rewrite_heap_tuple(RewriteState state, HeapTuple old_tuple,
- HeapTuple new_tuple);
+
+/* See toast_helper.h for the values of "flags" */
+extern bool rewrite_heap_tuple(RewriteState state, HeapTuple old_tuple,
+ HeapTuple new_tuple, bool recently_dead);
extern bool rewrite_heap_dead_tuple(RewriteState state, HeapTuple old_tuple);
/*
diff --git a/src/include/access/tableam.h b/src/include/access/tableam.h
index ea3f2a6be99..42f3a96206e 100644
--- a/src/include/access/tableam.h
+++ b/src/include/access/tableam.h
@@ -782,12 +782,17 @@ typedef struct TableAmRoutine
* This callback is invoked when detoasting a value stored in a toast
* table implemented by this AM. See table_relation_fetch_toast_slice()
* for more details.
+ *
+ * If TOAST_MISSING_OK is set in flags, returns false when chunks are
+ * missing instead of raising an error. Returns true on success. See
+ * toast_helper.h for possible values of "flags".
*/
- void (*relation_fetch_toast_slice) (Relation toastrel, Oid8 valueid,
+ bool (*relation_fetch_toast_slice) (Relation toastrel, Oid8 valueid,
int32 attrsize,
int32 sliceoffset,
int32 slicelength,
- varlena *result);
+ varlena *result,
+ uint32 flags);
/* ------------------------------------------------------------------------
@@ -2003,16 +2008,21 @@ table_relation_toast_am(Relation rel)
*
* result is caller-allocated space into which the fetched bytes should be
* stored.
+ *
+ * flags: if TOAST_MISSING_OK is set, return false when toast chunks are
+ * missing instead of raising an error. Returns true on success. See
+ * also toast_helper.h.
*/
-static inline void
+static inline bool
table_relation_fetch_toast_slice(Relation toastrel, Oid8 valueid,
int32 attrsize, int32 sliceoffset,
- int32 slicelength, varlena *result)
+ int32 slicelength, varlena *result,
+ uint32 flags)
{
- toastrel->rd_tableam->relation_fetch_toast_slice(toastrel, valueid,
- attrsize,
- sliceoffset, slicelength,
- result);
+ return toastrel->rd_tableam->relation_fetch_toast_slice(toastrel, valueid,
+ attrsize,
+ sliceoffset, slicelength,
+ result, flags);
}
diff --git a/src/include/access/toast_helper.h b/src/include/access/toast_helper.h
index 2ec92397f26..4abebe82798 100644
--- a/src/include/access/toast_helper.h
+++ b/src/include/access/toast_helper.h
@@ -101,7 +101,15 @@ typedef struct
#define TOASTCOL_IGNORE 0x0010
#define TOASTCOL_INCOMPRESSIBLE 0x0020
-extern void toast_tuple_init(ToastTupleContext *ttc);
+/*
+ * Flags for TOAST fetch operations.
+ *
+ * TOAST_MISSING_OK, when set, means that a TOAST fetch tolerates missing
+ * chunks and returns a failure state instead of raising an error.
+ */
+#define TOAST_MISSING_OK (1 << 1)
+
+extern bool toast_tuple_init(ToastTupleContext *ttc, uint32 flags);
extern int toast_tuple_find_biggest_attribute(ToastTupleContext *ttc,
bool for_compression,
bool check_main);
diff --git a/src/test/recovery/meson.build b/src/test/recovery/meson.build
index e1cf57ff611..cba8a969831 100644
--- a/src/test/recovery/meson.build
+++ b/src/test/recovery/meson.build
@@ -68,6 +68,7 @@ tests += {
't/057_snapshot_commit_race.pl',
't/058_shutdown_crash_restart.pl',
't/059_remote_apply_status_interval.pl',
+ 't/099_rewrite_stale_xmin.pl',
],
},
}
diff --git a/src/test/recovery/t/099_rewrite_stale_xmin.pl b/src/test/recovery/t/099_rewrite_stale_xmin.pl
new file mode 100644
index 00000000000..fbccb5373a8
--- /dev/null
+++ b/src/test/recovery/t/099_rewrite_stale_xmin.pl
@@ -0,0 +1,124 @@
+# Copyright (c) 2025-2026, PostgreSQL Global Development Group
+#
+# Test that heap rewrites (CLUSTER, VACUUM FULL, REPACK) and index builds
+# work in the case when the backend's own xmin is held back by a transaction
+# in another database.
+
+use strict;
+use warnings;
+use PostgreSQL::Test::Cluster;
+use Test::More;
+
+my $node = PostgreSQL::Test::Cluster->new('primary');
+$node->init;
+# No Autovacuum, no random interferences.
+$node->append_conf(
+ 'postgresql.conf', qq[
+autovacuum = off
+]);
+$node->start;
+
+# Create two databases.
+$node->safe_psql('postgres', 'CREATE DATABASE db_holder');
+$node->safe_psql('postgres', 'CREATE DATABASE db_target');
+
+# Set up a table with TOAST data. Returns the toast table name.
+sub setup_table
+{
+ my ($tblname, $extra_ddl) = @_;
+ $extra_ddl //= '';
+
+ $node->safe_psql(
+ 'db_target', qq{
+ DROP TABLE IF EXISTS $tblname;
+ CREATE TABLE $tblname (id int PRIMARY KEY, data text)
+ WITH (autovacuum_enabled = off);
+ ALTER TABLE $tblname ALTER COLUMN data SET STORAGE EXTERNAL;
+ INSERT INTO $tblname VALUES (1, repeat('x', 2500));
+ INSERT INTO $tblname VALUES (2, repeat('z', 2500));
+ $extra_ddl
+ });
+
+ my $toast = $node->safe_psql(
+ 'db_target', qq{
+ SELECT 'pg_toast.' || relname FROM pg_class
+ WHERE oid = (SELECT reltoastrelid FROM pg_class
+ WHERE relname = '$tblname');
+ });
+ chomp $toast;
+ return $toast;
+}
+
+# Create precondition state. Requires that $holder is already running with
+# a write XID.
+sub create_missing_toast_state
+{
+ my ($tblname, $toast_table) = @_;
+
+ # Hold xmin in same DB to prevent main tuple removal.
+ my $xmin_holder = $node->background_psql('db_target', on_error_stop => 1);
+ $xmin_holder->query_safe("BEGIN ISOLATION LEVEL REPEATABLE READ");
+ $xmin_holder->query_safe("SELECT 1");
+
+ # Delete the row with TOAST data.
+ $node->safe_psql('db_target', "DELETE FROM $tblname WHERE id = 1");
+
+ # VACUUM main table only. The xmin_holder keeps the dead tuple.
+ $node->safe_psql('db_target', "VACUUM (PROCESS_TOAST false) $tblname");
+
+ # Release same-DB xmin.
+ $xmin_holder->query_safe("COMMIT");
+ $xmin_holder->quit;
+
+ # Vacuum toast table: toast chunks now DEAD and removed.
+ $node->safe_psql('db_target', "VACUUM $toast_table");
+}
+
+# Open a transaction holding an XID before any deletes. This XID will hold
+# back GetSnapshotData() globally, on a different database than the one
+# running the various rewrite operations.
+my $holder = $node->background_psql('db_holder', on_error_stop => 1);
+$holder->query_safe("BEGIN");
+$holder->query_safe("CREATE TEMP TABLE xid_holder(x int)");
+
+# Test 1: CLUSTER
+my $toast = setup_table('rewrite_test');
+create_missing_toast_state('rewrite_test', $toast);
+
+my ($ret, $stdout, $stderr) =
+ $node->psql('db_target', 'CLUSTER rewrite_test USING rewrite_test_pkey');
+is($ret, 0, "CLUSTER succeeds without missing-chunk error");
+unlike($stderr, qr/missing chunk/, "CLUSTER: no missing-chunk error");
+
+# Test 2: VACUUM FULL
+$toast = setup_table('rewrite_test');
+create_missing_toast_state('rewrite_test', $toast);
+
+($ret, $stdout, $stderr) =
+ $node->psql('db_target', 'VACUUM FULL rewrite_test');
+is($ret, 0, "VACUUM FULL succeeds without missing-chunk error");
+unlike($stderr, qr/missing chunk/, "VACUUM FULL: no missing-chunk error");
+
+# Test 3: REPACK
+$toast = setup_table('rewrite_test');
+create_missing_toast_state('rewrite_test', $toast);
+
+($ret, $stdout, $stderr) = $node->psql('db_target', 'REPACK rewrite_test');
+is($ret, 0, "REPACK succeeds without missing-chunk error");
+unlike($stderr, qr/missing chunk/, "REPACK: no missing-chunk error");
+
+# Test 4: CREATE INDEX on toasted column
+$toast = setup_table('rewrite_test');
+create_missing_toast_state('rewrite_test', $toast);
+
+($ret, $stdout, $stderr) = $node->psql('db_target',
+ 'CREATE INDEX rewrite_test_data_idx ON rewrite_test ((rewrite_test IS NOT NULL))');
+is($ret, 0, "CREATE INDEX succeeds without missing-chunk error");
+unlike($stderr, qr/missing chunk/, "CREATE INDEX: no missing-chunk error");
+
+# Cleanup.
+$holder->query_safe("COMMIT");
+$holder->quit;
+
+$node->stop;
+done_testing();
--
2.54.0 (Apple Git-157)
^ permalink raw reply [nested|flat] 33+ messages in thread
* Re: BUG #19519: REPACK can fail due to missing chunk for toast value
@ 2026-10-24 04:41 shihao zhong <zhong950419@gmail.com>
parent: Matthias van de Meent <boekewurm+postgres@gmail.com>
1 sibling, 0 replies; 33+ messages in thread
From: shihao zhong @ 2026-10-24 04:41 UTC (permalink / raw)
To: Matthias van de Meent <boekewurm+postgres@gmail.com>; +Cc: Michael Paquier <michael@paquier.xyz>; Andrey Borodin <x4mmm@yandex-team.ru>; Heikki Linnakangas <hlinnaka@iki.fi>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; Imran Zaheer <imran.zhir@gmail.com>; Alexander Lakhin <exclusion@gmail.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>; Konstantin Knizhnik <knizhnik@garret.ru>
Hi Matthias,
Thanks for v7. The DELETE cases pass for me. Three notes.
1. Rui's UPDATE case still fails. If the spec does an UPDATE instead
of the DELETE, VACUUM FULL and REPACK hit
TRAP: failed Assert("recently_dead")
v7 has the first half of Rui's 0001 but not the second half, which
drops the stashed old version in place and counts it.
2. The cleanup loop in the sort path uses bms_prev_member(), so it
frees only the first value. CLUSTER with three toasted columns peaks
at 496 MB for me, and at 76 MB with bms_next_member().
3. The tests only check that nothing fails. Could they also SELECT
the table after the rewrite, and add the UPDATE case?
The attached patch fixes 1 and 2 on top of v7.
Thanks,
Shihao
Attachments:
nocfbot-v7-review-fixes.txt (text/plain, 3.8K) download
diff --git a/src/backend/access/heap/heapam_handler.c b/src/backend/access/heap/heapam_handler.c
index b1df7d19863..7b57796aa55 100644
--- a/src/backend/access/heap/heapam_handler.c
+++ b/src/backend/access/heap/heapam_handler.c
@@ -956,7 +956,7 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,
cleanup_and_next:
for (int i = bms_next_member(detoasted, -1);
i >= 0;
- i = bms_prev_member(detoasted, i))
+ i = bms_next_member(detoasted, i))
{
pfree(DatumGetPointer(values[i]));
}
@@ -1072,7 +1072,13 @@ normal_put:
/* Write out any remaining tuples, and fsync if needed */
if (rwstate)
- end_heap_rewrite(rwstate);
+ {
+ double tuples_dropped = end_heap_rewrite(rwstate);
+
+ *tups_vacuumed += tuples_dropped;
+ *num_tuples -= tuples_dropped;
+ *tups_recently_dead -= tuples_dropped;
+ }
if (bistate)
FreeBulkInsertState(bistate);
diff --git a/src/backend/access/heap/rewriteheap.c b/src/backend/access/heap/rewriteheap.c
index 0d57b3f5709..122820fd0d5 100644
--- a/src/backend/access/heap/rewriteheap.c
+++ b/src/backend/access/heap/rewriteheap.c
@@ -150,6 +150,7 @@ typedef struct RewriteStateData
XLogRecPtr rs_begin_lsn; /* XLogInsertLsn when starting the rewrite */
HTAB *rs_unresolved_tups; /* unmatched A tuples */
HTAB *rs_old_new_tid_map; /* unmatched B tuples */
+ double rs_tuples_dropped; /* stashed tuples dropped, TOAST gone */
HTAB *rs_logical_mappings; /* logical remapping files */
uint32 rs_num_rewrite_mappings; /* # in memory mappings */
} RewriteStateData;
@@ -297,11 +298,12 @@ begin_heap_rewrite(Relation old_heap, Relation new_heap, TransactionId oldest_xm
*
* state and any other resources are freed.
*/
-void
+double
end_heap_rewrite(RewriteState state)
{
HASH_SEQ_STATUS seq_status;
UnresolvedTup unresolved;
+ double tuples_dropped;
/*
* Write any remaining tuples in the UnresolvedTups table. If we have any
@@ -312,7 +314,8 @@ end_heap_rewrite(RewriteState state)
while ((unresolved = hash_seq_search(&seq_status)) != NULL)
{
ItemPointerSetInvalid(&unresolved->tuple->t_data->t_ctid);
- raw_heap_insert(state, unresolved->tuple, unresolved->recently_dead);
+ if (!raw_heap_insert(state, unresolved->tuple, unresolved->recently_dead))
+ state->rs_tuples_dropped += 1;
}
/* Write the last page, if any */
@@ -326,8 +329,12 @@ end_heap_rewrite(RewriteState state)
logical_end_heap_rewrite(state);
+ tuples_dropped = state->rs_tuples_dropped;
+
/* Deleting the context frees everything */
MemoryContextDelete(state->rs_cxt);
+
+ return tuples_dropped;
}
/*
@@ -462,10 +469,16 @@ rewrite_heap_tuple(RewriteState state,
/* Insert the tuple and find out where it's put in new_heap */
if (!raw_heap_insert(state, new_tuple, recently_dead))
{
- if (free_new)
- heap_freetuple(new_tuple);
+ if (!free_new)
+ {
+ MemoryContextSwitchTo(old_cxt);
+ return false;
+ }
+ /* stashed prior version; the caller's tuple is already written */
+ state->rs_tuples_dropped += 1;
+ heap_freetuple(new_tuple);
MemoryContextSwitchTo(old_cxt);
- return false;
+ return true;
}
new_tid = new_tuple->t_self;
diff --git a/src/include/access/rewriteheap.h b/src/include/access/rewriteheap.h
index 67467c2ddbe..ec9d64112ad 100644
--- a/src/include/access/rewriteheap.h
+++ b/src/include/access/rewriteheap.h
@@ -24,7 +24,7 @@ typedef struct RewriteStateData *RewriteState;
extern RewriteState begin_heap_rewrite(Relation old_heap, Relation new_heap,
TransactionId oldest_xmin, TransactionId freeze_xid,
MultiXactId cutoff_multi);
-extern void end_heap_rewrite(RewriteState state);
+extern double end_heap_rewrite(RewriteState state);
/* See toast_helper.h for the values of "flags" */
extern bool rewrite_heap_tuple(RewriteState state, HeapTuple old_tuple,
^ permalink raw reply [nested|flat] 33+ messages in thread
* Re: BUG #19519: REPACK can fail due to missing chunk for toast value
@ 2026-10-24 15:36 Rui Zhao <zhaorui126@gmail.com>
parent: Matthias van de Meent <boekewurm+postgres@gmail.com>
1 sibling, 1 reply; 33+ messages in thread
From: Rui Zhao @ 2026-10-24 15:36 UTC (permalink / raw)
To: Matthias van de Meent <boekewurm+postgres@gmail.com>; +Cc: Michael Paquier <michael@paquier.xyz>; Andrey Borodin <x4mmm@yandex-team.ru>; Heikki Linnakangas <hlinnaka@iki.fi>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; Imran Zaheer <imran.zhir@gmail.com>; Alexander Lakhin <exclusion@gmail.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>; Konstantin Knizhnik <knizhnik@garret.ru>
Hi Matthias,
Thanks for updating the patch. I tested v7 on 4b97fd15fb4 and found the
UPDATE case from my previous mail still fails, plus two cleanup leaks.
1. VACUUM FULL and REPACK fail when a live tuple resolves a stashed
prior version whose TOAST data is missing.
In rewrite_stale_xmin.spec, replace the DELETE with:
UPDATE rewrite_test SET data = repeat('z', 2500) WHERE id = 1;
Both the VACUUM FULL and REPACK permutations abort with assertions
enabled:
TRAP: failed Assert("recently_dead"),
File: "heapam_handler.c", Line: 993
The old version A is stashed before the scan reaches its live successor
B. rewrite_heap_tuple() writes B, then tries A using A's recently_dead
flag. That flag is now correct, but when A's TOAST fetch fails, the
function still returns false. The caller is processing B, so its
Assert(recently_dead) fails.
0001 adapts the failure handling and counting from my previous patch
to v7. rewrite_heap_tuple() returns false only when the caller's own
tuple is skipped. It counts skipped stashed tuples separately, including
those processed by end_heap_rewrite(), and corrects the rewrite counts.
The added tests cover one and two UPDATEs before VACUUM FULL and REPACK,
and check both the surviving rows and pg_class.reltuples.
2. Two cleanup loops leave detoasted values allocated. 0002 fixes both.
In heapam_relation_copy_for_cluster(), cleanup starts at the first
bitmap member but then walks backward:
for (int i = bms_next_member(detoasted, -1);
i >= 0;
i = bms_prev_member(detoasted, i))
Only the first value is freed. The last call should be
bms_next_member(). I used two EXTERNAL text columns with 100,000 bytes
each, deleted the rows while another connection held an older snapshot,
and forced CLUSTER to use a sequential scan and sort. Just before
tuplesort_performsort(), PortalContext used 10,022,200 bytes for 100
rows and 40,041,400 for 400. With 0002, it used 15,800 bytes in both
cases.
In toast_tuple_init(), the missing-TOAST cleanup stops before attribute
zero:
for (; i > 0; i--)
It should include zero. I tested a table whose first two columns are
EXTERNAL text and updated only the second column. As in
rewrite_stale_xmin.spec, I held an XID in another database and an older
snapshot in the test database. I ran VACUUM (PROCESS_TOAST false),
released the local snapshot, then vacuumed the TOAST table. This removed
the old second-column TOAST values but kept the first-column values,
which the new versions still referenced.
VACUUM FULL then reads the old row version. It fetches the first column,
but skips the row when the second column's TOAST data is missing.
The cleanup loop stops before column zero, leaving the first column's
detoasted value allocated. 0002 changes i > 0 to i >= 0 to free it.
Attached are 0001 and 0002 on top of v7. All tests I ran passed.
Regards,
Rui
Attachments: download all (2 files, .tar.gz)
nocfbot-0001-Fix-handling-of-skipped-prior-versions-during-heap-r.patch (application/octet-stream, 12.9K) download
From b48d56fb1944e0bfb2df6b5b3f9b87c5007472fd Mon Sep 17 00:00:00 2001
From: Rui Zhao <zhaorui126@gmail.com>
Date: Wed, 21 Oct 2026 23:11:16 +0800
Subject: [PATCH 1/2] Fix handling of skipped prior versions during heap
rewrites
A live tuple can resolve a stashed prior version whose TOAST data is
missing. Returning false for that prior version makes the caller treat
the live tuple as skipped, triggering Assert(recently_dead) and charging
the removal to the wrong tuple.
Return false only when the caller's tuple is skipped. Count skipped
stashed tuples separately, including those processed at the end of the
rewrite, and use that count to correct the rewrite statistics.
Add UPDATE tests for VACUUM FULL and REPACK, including a three-version
chain that leaves an older tuple for end_heap_rewrite().
---
.../dblink/expected/rewrite_stale_xmin.out | 302 ++++++++++++++++++
contrib/dblink/specs/rewrite_stale_xmin.spec | 60 ++++
src/backend/access/heap/heapam_handler.c | 9 +-
src/backend/access/heap/rewriteheap.c | 29 +-
src/include/access/rewriteheap.h | 2 +-
5 files changed, 395 insertions(+), 7 deletions(-)
diff --git a/contrib/dblink/expected/rewrite_stale_xmin.out b/contrib/dblink/expected/rewrite_stale_xmin.out
index 2e5a7940ea2..c1162dfcc3f 100644
--- a/contrib/dblink/expected/rewrite_stale_xmin.out
+++ b/contrib/dblink/expected/rewrite_stale_xmin.out
@@ -235,3 +235,305 @@ 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)
+
diff --git a/contrib/dblink/specs/rewrite_stale_xmin.spec b/contrib/dblink/specs/rewrite_stale_xmin.spec
index fe88e789f85..4fd82116f4c 100644
--- a/contrib/dblink/specs/rewrite_stale_xmin.spec
+++ b/contrib/dblink/specs/rewrite_stale_xmin.spec
@@ -65,6 +65,19 @@ 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;
@@ -135,3 +148,50 @@ permutation
s3_vacuum_toast
s3_create_index
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
diff --git a/src/backend/access/heap/heapam_handler.c b/src/backend/access/heap/heapam_handler.c
index b1df7d19863..30b070e903b 100644
--- a/src/backend/access/heap/heapam_handler.c
+++ b/src/backend/access/heap/heapam_handler.c
@@ -1072,7 +1072,14 @@ normal_put:
/* Write out any remaining tuples, and fsync if needed */
if (rwstate)
- end_heap_rewrite(rwstate);
+ {
+ double tuples_dropped = end_heap_rewrite(rwstate);
+
+ /* Stashed tuples with missing TOAST were scanned as recently dead. */
+ *tups_vacuumed += tuples_dropped;
+ *num_tuples -= tuples_dropped;
+ *tups_recently_dead -= tuples_dropped;
+ }
if (bistate)
FreeBulkInsertState(bistate);
diff --git a/src/backend/access/heap/rewriteheap.c b/src/backend/access/heap/rewriteheap.c
index 0d57b3f5709..0ba2f202dd8 100644
--- a/src/backend/access/heap/rewriteheap.c
+++ b/src/backend/access/heap/rewriteheap.c
@@ -150,6 +150,7 @@ typedef struct RewriteStateData
XLogRecPtr rs_begin_lsn; /* XLogInsertLsn when starting the rewrite */
HTAB *rs_unresolved_tups; /* unmatched A tuples */
HTAB *rs_old_new_tid_map; /* unmatched B tuples */
+ double rs_tuples_dropped; /* stashed tuples with missing TOAST */
HTAB *rs_logical_mappings; /* logical remapping files */
uint32 rs_num_rewrite_mappings; /* # in memory mappings */
} RewriteStateData;
@@ -296,12 +297,14 @@ begin_heap_rewrite(Relation old_heap, Relation new_heap, TransactionId oldest_xm
* End a rewrite.
*
* state and any other resources are freed.
+ * Returns the number of stashed tuples skipped because their TOAST is missing.
*/
-void
+double
end_heap_rewrite(RewriteState state)
{
HASH_SEQ_STATUS seq_status;
UnresolvedTup unresolved;
+ double tuples_dropped;
/*
* Write any remaining tuples in the UnresolvedTups table. If we have any
@@ -312,7 +315,8 @@ end_heap_rewrite(RewriteState state)
while ((unresolved = hash_seq_search(&seq_status)) != NULL)
{
ItemPointerSetInvalid(&unresolved->tuple->t_data->t_ctid);
- raw_heap_insert(state, unresolved->tuple, unresolved->recently_dead);
+ if (!raw_heap_insert(state, unresolved->tuple, unresolved->recently_dead))
+ state->rs_tuples_dropped += 1;
}
/* Write the last page, if any */
@@ -326,8 +330,12 @@ end_heap_rewrite(RewriteState state)
logical_end_heap_rewrite(state);
+ tuples_dropped = state->rs_tuples_dropped;
+
/* Deleting the context frees everything */
MemoryContextDelete(state->rs_cxt);
+
+ return tuples_dropped;
}
/*
@@ -462,10 +470,21 @@ rewrite_heap_tuple(RewriteState state,
/* Insert the tuple and find out where it's put in new_heap */
if (!raw_heap_insert(state, new_tuple, recently_dead))
{
- if (free_new)
- heap_freetuple(new_tuple);
+ if (!free_new)
+ {
+ MemoryContextSwitchTo(old_cxt);
+ return false;
+ }
+
+ /*
+ * The caller's tuple was already written. Count this skipped
+ * prior version separately; end_heap_rewrite() will handle any
+ * still older versions waiting for it.
+ */
+ state->rs_tuples_dropped += 1;
+ heap_freetuple(new_tuple);
MemoryContextSwitchTo(old_cxt);
- return false;
+ return true;
}
new_tid = new_tuple->t_self;
diff --git a/src/include/access/rewriteheap.h b/src/include/access/rewriteheap.h
index 67467c2ddbe..ec9d64112ad 100644
--- a/src/include/access/rewriteheap.h
+++ b/src/include/access/rewriteheap.h
@@ -24,7 +24,7 @@ typedef struct RewriteStateData *RewriteState;
extern RewriteState begin_heap_rewrite(Relation old_heap, Relation new_heap,
TransactionId oldest_xmin, TransactionId freeze_xid,
MultiXactId cutoff_multi);
-extern void end_heap_rewrite(RewriteState state);
+extern double end_heap_rewrite(RewriteState state);
/* See toast_helper.h for the values of "flags" */
extern bool rewrite_heap_tuple(RewriteState state, HeapTuple old_tuple,
--
2.43.7
nocfbot-0002-Fix-two-detoasted-value-cleanup-loops.patch (application/octet-stream, 1.7K) download
From 35efdfae7cf4112561f3db24d6804f2124817b59 Mon Sep 17 00:00:00 2001
From: Rui Zhao <zhaorui126@gmail.com>
Date: Wed, 21 Oct 2026 23:15:15 +0800
Subject: [PATCH 2/2] Fix two detoasted-value cleanup loops
The scan-and-sort path starts at the first bitmap member but then walks
backward, freeing only the first detoasted attribute. Walk forward to
free the remaining attributes too.
When toast_tuple_init() cannot fetch an external value, its cleanup
loop stops before attribute zero. Include that attribute so a value
fetched from the first column is freed when a later column is missing.
---
src/backend/access/heap/heapam_handler.c | 2 +-
src/backend/access/table/toast_helper.c | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
diff --git a/src/backend/access/heap/heapam_handler.c b/src/backend/access/heap/heapam_handler.c
index 30b070e903b..d641f70fa46 100644
--- a/src/backend/access/heap/heapam_handler.c
+++ b/src/backend/access/heap/heapam_handler.c
@@ -956,7 +956,7 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,
cleanup_and_next:
for (int i = bms_next_member(detoasted, -1);
i >= 0;
- i = bms_prev_member(detoasted, i))
+ i = bms_next_member(detoasted, i))
{
pfree(DatumGetPointer(values[i]));
}
diff --git a/src/backend/access/table/toast_helper.c b/src/backend/access/table/toast_helper.c
index a8e58d8573c..aa87452d35d 100644
--- a/src/backend/access/table/toast_helper.c
+++ b/src/backend/access/table/toast_helper.c
@@ -194,7 +194,7 @@ toast_tuple_init(ToastTupleContext *ttc, uint32 flags)
return true;
broken_toast_missing_ok:
- for (; i > 0; i--)
+ for (; i >= 0; i--)
{
if (ttc->ttc_attr[i].tai_colflags & TOASTCOL_NEEDS_FREE)
{
--
2.43.7
^ permalink raw reply [nested|flat] 33+ messages in thread
* Re: BUG #19519: REPACK can fail due to missing chunk for toast value
@ 2026-11-12 12:47 Konstantin Knizhnik <konstantin.knizhnik@databricks.com>
0 siblings, 0 replies; 33+ messages in thread
From: Konstantin Knizhnik @ 2026-11-12 12:47 UTC (permalink / raw)
To: Rui Zhao <zhaorui126@gmail.com>; +Cc: Matthias van de Meent <boekewurm+postgres@gmail.com>; Michael Paquier <michael@paquier.xyz>; Andrey Borodin <x4mmm@yandex-team.ru>; Heikki Linnakangas <hlinnaka@iki.fi>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; Imran Zaheer <imran.zhir@gmail.com>; Alexander Lakhin <exclusion@gmail.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>
> Hi,
>
> Attached is v8 of the fix for the "missing chunk number 0 for toast
> value" failures during heap rewrites and non-concurrent index builds.
>
> This is a rebase of Matthias' v7 onto current master, with Rui Zhao's
> two follow-up patches folded in, plus a bit of cleanup and one extra
> fix for a whole-row expression index.
>
> Compared to v7:
>
> - Rebased onto current master (conflict in tableam.h resolved by
> keeping master's slice validation and returning bool with flags).
> - Folded in Rui's 0001 (skipped stashed prior versions are counted as
> removed, not reported as a rewrite failure) and 0002 (cleanup loop
> off-by-ones).
> - Replaced the duplicated goto-heavy sort-path and index-build cleanup
> with a shared heap_inline_recently_dead_toast() helper.
> - Index builds now collect every varlena attribute referenced by the
> index definition, expressions (including whole-row Vars) and the
> predicate, so a whole-row expression index no longer races the same
> way. A new isolation permutation covers that case.
> - Dropped the duplicate recovery TAP test in favor of the dblink
> isolation spec (as the v7 commit message already planned). Added
> sort-path CLUSTER and UPDATE-chain permutations there.
> - Comment / include-order / pgindent cleanup; TOAST_MISSING_OK is now
> (1 << 0).
>
> Verification on current master:
>
> - make check: all 243 tests passed
> - src/test/isolation: all 139 tests passed
> - contrib/dblink isolation: rewrite_stale_xmin passed
> - The same isolation test on unpatched master fails all 11
> permutations with the missing-chunk error (CLUSTER index and sort
> paths, VACUUM FULL, REPACK, CREATE INDEX, whole-row expression
> index; DELETE and UPDATE chains).
>
> CF entry: https://commitfest.postgresql.org/patch/6824/
> I will update it with v8 shortly.
>
> Regards,
> Konstantin
>
>
> On 24/10/2026 18:36, Rui Zhao wrote:
> > Thanks for updating the patch. I tested v7 on 4b97fd15fb4 and found the
> > UPDATE case from my previous mail still fails, plus two cleanup leaks.
> >
> > Attached are 0001 and 0002 on top of v7. All tests I ran passed.
=
Attachments:
v8-0001-Fix-missing-chunk-errors-during-heap-rewrites-and.patch (application/x-apple-msg-attachment, 60.7K) download
From ffd8366a6ad0d2cf65ddfc407a09de4ad4415bac Mon Sep 17 00:00:00 2001
From: Konstantin Knizhnik <knizhnik@garret.ru>
Date: Thu, 12 Nov 2026 14:46:55 +0200
Subject: [PATCH v8] 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 skip it. This commit adds a TOAST_MISSING_OK
flag that makes the TOAST fetch paths (table_relation_fetch_toast_slice,
toast_fetch_datum, detoast_external_attr_extended, toast_tuple_init and
heap_toast_insert_or_update) report missing chunks to the caller instead
of raising an error, and uses it only for RECENTLY_DEAD tuples:
- In a heap rewrite, a RECENTLY_DEAD tuple whose TOAST data is gone is
not written and is counted as removed. This covers both directly
written tuples and update-chain members stashed in rewriteheap.c,
whose result is reported by end_heap_rewrite().
- When the rewrite sorts the tuples, the TOAST data of RECENTLY_DEAD
tuples is inlined before the sort, so that missing chunks are detected
while the tuple's visibility is still known.
- In a non-concurrent index build, the varlena attributes referenced by
the index (columns, expressions including whole-row references, and
predicate) are inlined for tuples that are not alive, and the tuple is
skipped from the index if its TOAST data is gone.
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 <exclusion@gmail.com>
Reported-by: Ekaterina Testova <e.testova@postgrespro.ru>
Author: Michael Paquier <michael@paquier.xyz>
Co-authored-by: Matthias van de Meent <boekewurm+postgres@gmail.com>
Co-authored-by: Rui Zhao <zhaorui126@gmail.com>
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/common/detoast.c | 43 +-
src/backend/access/heap/heapam.c | 4 +-
src/backend/access/heap/heapam_handler.c | 240 +++++-
src/backend/access/heap/heaptoast.c | 48 +-
src/backend/access/heap/rewriteheap.c | 71 +-
src/backend/access/table/toast_helper.c | 41 +-
src/include/access/detoast.h | 9 +
src/include/access/heaptoast.h | 16 +-
src/include/access/rewriteheap.h | 6 +-
src/include/access/tableam.h | 26 +-
src/include/access/toast_helper.h | 11 +-
16 files changed, 1467 insertions(+), 58 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..63ba262f359
--- /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 fetches TOAST data before sorting
+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/common/detoast.c b/src/backend/access/common/detoast.c
index 8223cc219c1..b27b6bb9780 100644
--- a/src/backend/access/common/detoast.c
+++ b/src/backend/access/common/detoast.c
@@ -17,6 +17,7 @@
#include "access/table.h"
#include "access/tableam.h"
#include "access/toast_compression.h"
+#include "access/toast_helper.h"
#include "access/toast_internals.h"
#include "common/int.h"
#include "common/pg_lzcompress.h"
@@ -24,7 +25,7 @@
#include "utils/memutils.h"
#include "utils/rel.h"
-static varlena *toast_fetch_datum(varlena *attr);
+static varlena *toast_fetch_datum(varlena *attr, uint32 flags);
static varlena *toast_fetch_datum_slice(varlena *attr,
int32 sliceoffset,
int32 slicelength);
@@ -61,7 +62,7 @@ detoast_external_attr(varlena *attr)
/*
* This is an external stored plain value
*/
- result = toast_fetch_datum(attr);
+ result = toast_fetch_datum(attr, 0);
}
else if (VARATT_IS_EXTERNAL_INDIRECT(attr))
{
@@ -112,6 +113,24 @@ detoast_external_attr(varlena *attr)
}
+/* ----------
+ * detoast_external_attr_extended -
+ *
+ * Like detoast_external_attr, but returns NULL instead of raising an
+ * error if the chunks of an on-disk value are missing. Only meant for
+ * RECENTLY_DEAD tuples, see TOAST_MISSING_OK.
+ * ----------
+ */
+varlena *
+detoast_external_attr_extended(varlena *attr)
+{
+ if (VARATT_IS_EXTERNAL_ONDISK(attr))
+ return toast_fetch_datum(attr, TOAST_MISSING_OK);
+ else
+ return detoast_external_attr(attr);
+}
+
+
/* ----------
* detoast_attr -
*
@@ -130,7 +149,7 @@ detoast_attr(varlena *attr)
/*
* This is an externally stored datum --- fetch it back from there
*/
- attr = toast_fetch_datum(attr);
+ attr = toast_fetch_datum(attr, 0);
/* If it's compressed, decompress it */
if (VARATT_IS_COMPRESSED(attr))
{
@@ -277,7 +296,7 @@ detoast_attr_slice(varlena *attr,
preslice = toast_fetch_datum_slice(attr, 0, max_size);
}
else
- preslice = toast_fetch_datum(attr);
+ preslice = toast_fetch_datum(attr, 0);
}
else if (VARATT_IS_EXTERNAL_INDIRECT(attr))
{
@@ -352,10 +371,12 @@ detoast_attr_slice(varlena *attr,
*
* Reconstruct an in memory Datum from the chunks saved
* in the toast relation
+ *
+ * If flags includes TOAST_MISSING_OK, returns NULL when chunks are missing.
* ----------
*/
static varlena *
-toast_fetch_datum(varlena *attr)
+toast_fetch_datum(varlena *attr, uint32 flags)
{
Relation toastrel;
varlena *result;
@@ -389,8 +410,14 @@ toast_fetch_datum(varlena *attr)
toastrel = table_open(toastrelid, AccessShareLock);
/* Fetch all chunks */
- table_relation_fetch_toast_slice(toastrel, valueid,
- attrsize, 0, attrsize, result);
+ if (!table_relation_fetch_toast_slice(toastrel, valueid,
+ attrsize, 0, attrsize, result,
+ flags))
+ {
+ pfree(result);
+ table_close(toastrel, AccessShareLock);
+ return NULL;
+ }
/* Close toast table */
table_close(toastrel, AccessShareLock);
@@ -475,7 +502,7 @@ toast_fetch_datum_slice(varlena *attr, int32 sliceoffset,
/* Fetch all chunks */
table_relation_fetch_toast_slice(toastrel, valueid,
attrsize, sliceoffset, slicelength,
- result);
+ result, 0);
/* Close toast table */
table_close(toastrel, AccessShareLock);
diff --git a/src/backend/access/heap/heapam.c b/src/backend/access/heap/heapam.c
index 3bb33699349..0b3c4ae85ed 100644
--- a/src/backend/access/heap/heapam.c
+++ b/src/backend/access/heap/heapam.c
@@ -2266,7 +2266,7 @@ heap_prepare_insert(Relation relation, HeapTuple tup, TransactionId xid,
return tup;
}
else if (HeapTupleHasExternal(tup) || tup->t_len > TOAST_TUPLE_THRESHOLD)
- return heap_toast_insert_or_update(relation, tup, NULL, options);
+ return heap_toast_insert_or_update(relation, tup, NULL, options, 0);
else
return tup;
}
@@ -3983,7 +3983,7 @@ l2:
* tuples too. We never skip the FSM here.
*/
heaptup = heap_toast_insert_or_update(relation, newtup, &oldtup,
- walLogical ? 0 : HEAP_INSERT_NO_LOGICAL);
+ walLogical ? 0 : HEAP_INSERT_NO_LOGICAL, 0);
newtupsize = MAXALIGN(heaptup->t_len);
}
else
diff --git a/src/backend/access/heap/heapam_handler.c b/src/backend/access/heap/heapam_handler.c
index 05a81e4557a..bc10b4fe891 100644
--- a/src/backend/access/heap/heapam_handler.c
+++ b/src/backend/access/heap/heapam_handler.c
@@ -19,6 +19,7 @@
*/
#include "postgres.h"
+#include "access/detoast.h"
#include "access/genam.h"
#include "access/heapam.h"
#include "access/heaptoast.h"
@@ -26,6 +27,7 @@
#include "access/rewriteheap.h"
#include "access/syncscan.h"
#include "access/tableam.h"
+#include "access/toast_helper.h"
#include "access/tsmapi.h"
#include "access/visibilitymap.h"
#include "access/xact.h"
@@ -36,6 +38,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"
@@ -48,9 +51,14 @@
#include "utils/rel.h"
#include "utils/tuplesort.h"
-static void reform_and_rewrite_tuple(HeapTuple tuple,
+static bool reform_and_rewrite_tuple(HeapTuple tuple,
Relation OldHeap, Relation NewHeap,
- Datum *values, bool *isnull, RewriteState rwstate);
+ Datum *values, bool *isnull, RewriteState rwstate,
+ bool recently_dead);
+static HeapTuple heap_inline_recently_dead_toast(HeapTuple tuple,
+ 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);
@@ -703,6 +711,7 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,
HeapTuple tuple;
Buffer buf;
bool isdead;
+ bool recently_dead = false;
CHECK_FOR_INTERRUPTS();
@@ -789,6 +798,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 */
@@ -822,6 +832,7 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,
RelationGetRelationName(OldHeap));
/* treat as recently dead */
*tups_recently_dead += 1;
+ recently_dead = true;
isdead = false;
break;
default:
@@ -850,7 +861,30 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,
*num_tuples += 1;
if (tuplesort != NULL)
{
- tuplesort_putheaptuple(tuplesort, tuple);
+ HeapTuple sorttup = tuple;
+
+ /*
+ * The tuples are written out only after the sort, by which time
+ * the TOAST data of a recently-dead tuple may be gone, so fetch
+ * it now. If it is already gone, the tuple is dead to everyone
+ * who could still read it, so skip it.
+ */
+ if (recently_dead && HeapTupleHasExternal(tuple))
+ {
+ sorttup = heap_inline_recently_dead_toast(tuple, oldTupDesc,
+ NULL, values, isnull);
+ if (sorttup == NULL)
+ {
+ *tups_vacuumed += 1;
+ *num_tuples -= 1;
+ *tups_recently_dead -= 1;
+ continue;
+ }
+ }
+
+ tuplesort_putheaptuple(tuplesort, sorttup);
+ if (sorttup != tuple)
+ heap_freetuple(sorttup);
/*
* In scan-and-sort mode, report increase in number of tuples
@@ -868,8 +902,19 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,
int64 ct_val[2];
if (!concurrent)
- reform_and_rewrite_tuple(tuple, OldHeap, NewHeap,
- values, isnull, rwstate);
+ {
+ if (!reform_and_rewrite_tuple(tuple, OldHeap, NewHeap,
+ values, isnull, rwstate,
+ recently_dead))
+ {
+ /* TOAST data of a recently-dead tuple is gone */
+ Assert(recently_dead);
+ *tups_vacuumed += 1;
+ *num_tuples -= 1;
+ *tups_recently_dead -= 1;
+ continue;
+ }
+ }
else
heap_insert_for_repack(tuple, OldHeap, NewHeap,
values, isnull, bistate);
@@ -920,11 +965,12 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,
break;
n_tuples += 1;
+ /* TOAST data of recently-dead tuples was inlined before the sort */
if (!concurrent)
- reform_and_rewrite_tuple(tuple,
- OldHeap, NewHeap,
- values, isnull,
- rwstate);
+ (void) reform_and_rewrite_tuple(tuple,
+ OldHeap, NewHeap,
+ values, isnull,
+ rwstate, false);
else
heap_insert_for_repack(tuple, OldHeap, NewHeap,
values, isnull, bistate);
@@ -939,7 +985,14 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,
/* Write out any remaining tuples, and fsync if needed */
if (rwstate)
- end_heap_rewrite(rwstate);
+ {
+ double tuples_dropped = end_heap_rewrite(rwstate);
+
+ /* Stashed tuples with missing TOAST were scanned as recently dead. */
+ *tups_vacuumed += tuples_dropped;
+ *num_tuples -= tuples_dropped;
+ *tups_recently_dead -= tuples_dropped;
+ }
if (bistate)
FreeBulkInsertState(bistate);
@@ -1156,6 +1209,9 @@ heapam_index_build_range_scan(Relation heapRelation,
BlockNumber previous_blkno = InvalidBlockNumber;
BlockNumber root_blkno = InvalidBlockNumber;
OffsetNumber root_offsets[MaxHeapTuplesPerPage];
+ Bitmapset *detoast_index_attrs = NULL;
+ Datum *inline_values = NULL;
+ bool *inline_isnull = NULL;
/*
* sanity checks
@@ -1252,6 +1308,50 @@ heapam_index_build_range_scan(Relation heapRelation,
!TransactionIdIsValid(OldestXmin));
Assert(snapshot == SnapshotAny || !anyvisible);
+ /*
+ * Collect the varlena columns that the index columns, expressions and
+ * predicate reference, so that their TOAST data can be fetched for
+ * RECENTLY_DEAD tuples; see below. A whole-row reference needs all of
+ * them. The set contains plain attribute numbers.
+ */
+ {
+ TupleDesc desc = RelationGetDescr(heapRelation);
+ Bitmapset *refattrs = 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))
+ detoast_index_attrs = bms_add_member(detoast_index_attrs,
+ attnum);
+ }
+ bms_free(refattrs);
+
+ if (detoast_index_attrs != NULL)
+ {
+ inline_values = palloc_array(Datum, desc->natts);
+ inline_isnull = palloc_array(bool, desc->natts);
+ }
+ }
+
/* Publish number of blocks to scan */
if (progress)
{
@@ -1590,6 +1690,29 @@ heapam_index_build_range_scan(Relation heapRelation,
/* Set up for predicate or expression evaluation */
ExecStoreBufferHeapTuple(heapTuple, slot, hscan->rs_cbuf);
+ /*
+ * The TOAST data of a RECENTLY_DEAD tuple can be removed while we
+ * look at it; see heap_inline_recently_dead_toast(). Fetch what the
+ * index needs up front, and skip the tuple if it is already gone.
+ */
+ if (!tupleIsAlive && detoast_index_attrs != NULL &&
+ HeapTupleHasExternal(heapTuple))
+ {
+ HeapTuple inlined;
+
+ inlined = heap_inline_recently_dead_toast(heapTuple,
+ RelationGetDescr(heapRelation),
+ detoast_index_attrs,
+ inline_values, inline_isnull);
+ if (inlined == NULL)
+ continue;
+ if (inlined != heapTuple)
+ {
+ ExecForceStoreHeapTuple(inlined, slot, true);
+ slot->tts_tableOid = RelationGetRelid(heapRelation);
+ }
+ }
+
/*
* In a partial index, discard tuples that don't satisfy the
* predicate.
@@ -1698,6 +1821,12 @@ heapam_index_build_range_scan(Relation heapRelation,
indexInfo->ii_ExpressionsState = NIL;
indexInfo->ii_PredicateState = NULL;
+ bms_free(detoast_index_attrs);
+ if (inline_values)
+ pfree(inline_values);
+ if (inline_isnull)
+ pfree(inline_isnull);
+
return reltuples;
}
@@ -2338,20 +2467,105 @@ heapam_scan_sample_next_tuple(TableScanDesc scan, SampleScanState *scanstate,
* SET WITHOUT OIDS.
*
* So, we must reconstruct the tuple from component Datums.
+ *
+ * recently_dead must be set if the tuple is RECENTLY_DEAD. Returns false if
+ * the tuple was skipped because its TOAST data is gone; see
+ * rewrite_heap_tuple().
*/
-static void
+static bool
reform_and_rewrite_tuple(HeapTuple tuple,
Relation OldHeap, Relation NewHeap,
- Datum *values, bool *isnull, RewriteState rwstate)
+ Datum *values, bool *isnull, RewriteState rwstate,
+ bool recently_dead)
{
HeapTuple newtuple;
+ bool written;
newtuple = reform_tuple(tuple, OldHeap, NewHeap, values, isnull);
/* The heap rewrite module does the rest */
- rewrite_heap_tuple(rwstate, tuple, newtuple);
+ written = rewrite_heap_tuple(rwstate, tuple, newtuple, recently_dead);
heap_freetuple(newtuple);
+ return written;
+}
+
+/*
+ * Fetch the out-of-line TOAST values of a RECENTLY_DEAD tuple, and return a
+ * copy of the tuple with those values stored inline, keeping the original
+ * tuple's identity and visibility information.
+ *
+ * Other backends may already consider a RECENTLY_DEAD tuple fully dead, so
+ * its TOAST data can be removed by VACUUM or pruning of the TOAST relation at
+ * any time. If any value is already gone, return NULL: nobody can see the
+ * tuple anymore, and the caller should treat it as dead.
+ *
+ * attrs is the set of attribute numbers to fetch, or NULL for all of them.
+ * Returns the tuple itself if there is nothing to fetch. values and isnull
+ * are caller-provided workspace of tupdesc->natts entries.
+ */
+static HeapTuple
+heap_inline_recently_dead_toast(HeapTuple tuple, TupleDesc tupdesc,
+ const Bitmapset *attrs,
+ Datum *values, bool *isnull)
+{
+ Bitmapset *fetched = NULL;
+ HeapTuple result = NULL;
+ int i;
+
+ heap_deform_tuple(tuple, tupdesc, values, isnull);
+
+ for (i = 0; i < tupdesc->natts; i++)
+ {
+ CompactAttribute *att = TupleDescCompactAttr(tupdesc, i);
+ varlena *value;
+
+ if (att->attlen != -1 || isnull[i])
+ continue;
+ if (attrs != NULL && !bms_is_member(i + 1, attrs))
+ continue;
+
+ /* reform_tuple() throws away dropped columns anyway */
+ if (att->attisdropped)
+ {
+ isnull[i] = true;
+ continue;
+ }
+
+ value = (varlena *) DatumGetPointer(values[i]);
+ if (!VARATT_IS_EXTERNAL_ONDISK(value))
+ continue;
+
+ value = detoast_external_attr_extended(value);
+ if (value == NULL)
+ goto cleanup;
+
+ values[i] = PointerGetDatum(value);
+ fetched = bms_add_member(fetched, i);
+ }
+
+ if (fetched == NULL)
+ return tuple;
+
+ result = heap_form_tuple(tupdesc, values, isnull);
+
+ result->t_data->t_choice = tuple->t_data->t_choice;
+ result->t_data->t_ctid = tuple->t_data->t_ctid;
+ result->t_data->t_infomask2 &= ~HEAP2_XACT_MASK;
+ result->t_data->t_infomask2 |=
+ tuple->t_data->t_infomask2 & HEAP2_XACT_MASK;
+ result->t_data->t_infomask &= ~HEAP_XACT_MASK;
+ result->t_data->t_infomask |= tuple->t_data->t_infomask & HEAP_XACT_MASK;
+ result->t_self = tuple->t_self;
+ result->t_tableOid = tuple->t_tableOid;
+
+cleanup:
+ i = -1;
+ while ((i = bms_next_member(fetched, i)) >= 0)
+ pfree(DatumGetPointer(values[i]));
+ bms_free(fetched);
+
+ return result;
}
/*
diff --git a/src/backend/access/heap/heaptoast.c b/src/backend/access/heap/heaptoast.c
index e329662b683..1097e076bb9 100644
--- a/src/backend/access/heap/heaptoast.c
+++ b/src/backend/access/heap/heaptoast.c
@@ -84,9 +84,11 @@ heap_toast_delete(Relation rel, HeapTuple oldtup, bool is_speculative)
* newtup: the candidate new tuple to be inserted
* oldtup: the old row version for UPDATE, or NULL for INSERT
* options: options to be passed to heap_insert() for toast rows
+ * flags: TOAST fetch flags, see toast_helper.h
* Result:
* either newtup if no toasting is needed, or a palloc'd modified tuple
- * that is what should actually get stored
+ * that is what should actually get stored, or NULL if flags includes
+ * TOAST_MISSING_OK and an external value of newtup could not be fetched
*
* NOTE: neither newtup nor oldtup will be modified. This is a change
* from the pre-8.1 API of this routine.
@@ -94,7 +96,7 @@ heap_toast_delete(Relation rel, HeapTuple oldtup, bool is_speculative)
*/
HeapTuple
heap_toast_insert_or_update(Relation rel, HeapTuple newtup, HeapTuple oldtup,
- uint32 options)
+ uint32 options, uint32 flags)
{
HeapTuple result_tuple;
TupleDesc tupleDesc;
@@ -154,7 +156,8 @@ heap_toast_insert_or_update(Relation rel, HeapTuple newtup, HeapTuple oldtup,
ttc.ttc_oldisnull = toast_oldisnull;
}
ttc.ttc_attr = toast_attr;
- toast_tuple_init(&ttc);
+ if (!toast_tuple_init(&ttc, flags))
+ return NULL;
/* ----------
* Compress and/or save external until data fits into target length
@@ -636,11 +639,15 @@ toast_build_flattened_tuple(TupleDesc tupleDesc,
* sliceoffset is the byte offset within the TOAST value from which to fetch.
* slicelength is the number of bytes to be fetched from the TOAST value.
* result is the varlena into which the results should be written.
+ * flags are TOAST fetch flags, see toast_helper.h.
+ *
+ * Returns true on success. If flags includes TOAST_MISSING_OK, returns false
+ * instead of raising an error when chunks are missing or inconsistent.
*/
-void
+bool
heap_fetch_toast_slice(Relation toastrel, Oid8 valueid, int32 attrsize,
int32 sliceoffset, int32 slicelength,
- varlena *result)
+ varlena *result, uint32 flags)
{
Relation *toastidxs;
ScanKeyData toastkey[3];
@@ -753,27 +760,45 @@ heap_fetch_toast_slice(Relation toastrel, Oid8 valueid, int32 attrsize,
* Some checks on the data we've found
*/
if (curchunk != expectedchunk)
+ {
+ if (flags & TOAST_MISSING_OK)
+ goto toast_missing;
+
ereport(ERROR,
(errcode(ERRCODE_DATA_CORRUPTED),
errmsg_internal("unexpected chunk number %d (expected %d) for toast value %" PRIu64 " in %s",
curchunk, expectedchunk, valueid,
RelationGetRelationName(toastrel))));
+ }
+
if (curchunk > endchunk)
+ {
+ if (flags & TOAST_MISSING_OK)
+ goto toast_missing;
+
ereport(ERROR,
(errcode(ERRCODE_DATA_CORRUPTED),
errmsg_internal("unexpected chunk number %d (out of range %d..%d) for toast value %" PRIu64 " in %s",
curchunk,
startchunk, endchunk, valueid,
RelationGetRelationName(toastrel))));
+ }
+
expected_size = curchunk < totalchunks - 1 ? max_chunk_size
: attrsize - ((totalchunks - 1) * max_chunk_size);
+
if (chunksize != expected_size)
+ {
+ if (flags & TOAST_MISSING_OK)
+ goto toast_missing;
+
ereport(ERROR,
(errcode(ERRCODE_DATA_CORRUPTED),
errmsg_internal("unexpected chunk size %d (expected %d) in chunk %d of %d for toast value %" PRIu64 " in %s",
chunksize, expected_size,
curchunk, totalchunks, valueid,
RelationGetRelationName(toastrel))));
+ }
/*
* Copy the data into proper place in our result
@@ -797,13 +822,26 @@ heap_fetch_toast_slice(Relation toastrel, Oid8 valueid, int32 attrsize,
* Final checks that we successfully fetched the datum
*/
if (expectedchunk != (endchunk + 1))
+ {
+ if (flags & TOAST_MISSING_OK)
+ goto toast_missing;
+
ereport(ERROR,
(errcode(ERRCODE_DATA_CORRUPTED),
errmsg_internal("missing chunk number %d for toast value %" PRIu64 " in %s",
expectedchunk, valueid,
RelationGetRelationName(toastrel))));
+ }
/* End scan and close indexes. */
systable_endscan_ordered(toastscan);
toast_close_indexes(toastidxs, num_indexes, AccessShareLock);
+
+ return true;
+
+toast_missing:
+ systable_endscan_ordered(toastscan);
+ toast_close_indexes(toastidxs, num_indexes, AccessShareLock);
+
+ return false;
}
diff --git a/src/backend/access/heap/rewriteheap.c b/src/backend/access/heap/rewriteheap.c
index be0f6646b83..2ab3f77edfc 100644
--- a/src/backend/access/heap/rewriteheap.c
+++ b/src/backend/access/heap/rewriteheap.c
@@ -108,6 +108,7 @@
#include "access/heapam_xlog.h"
#include "access/heaptoast.h"
#include "access/rewriteheap.h"
+#include "access/toast_helper.h"
#include "access/transam.h"
#include "access/xact.h"
#include "access/xloginsert.h"
@@ -149,6 +150,7 @@ typedef struct RewriteStateData
XLogRecPtr rs_begin_lsn; /* XLogInsertLsn when starting the rewrite */
HTAB *rs_unresolved_tups; /* unmatched A tuples */
HTAB *rs_old_new_tid_map; /* unmatched B tuples */
+ double rs_tuples_dropped; /* # stashed tuples skipped, TOAST gone */
HTAB *rs_logical_mappings; /* logical remapping files */
uint32 rs_num_rewrite_mappings; /* # in memory mappings */
} RewriteStateData;
@@ -172,6 +174,7 @@ typedef struct
{
TidHashKey key; /* expected xmin/old location of B tuple */
ItemPointerData old_tid; /* A's location in the old heap */
+ bool recently_dead; /* A was RECENTLY_DEAD */
HeapTuple tuple; /* A's tuple contents */
} UnresolvedTupData;
@@ -211,7 +214,8 @@ typedef struct RewriteMappingDataEntry
/* prototypes for internal functions */
-static void raw_heap_insert(RewriteState state, HeapTuple tup);
+static bool raw_heap_insert(RewriteState state, HeapTuple tup,
+ bool recently_dead);
/* internal logical remapping prototypes */
static void logical_begin_heap_rewrite(RewriteState state);
@@ -293,12 +297,16 @@ begin_heap_rewrite(Relation old_heap, Relation new_heap, TransactionId oldest_xm
* End a rewrite.
*
* state and any other resources are freed.
+ *
+ * Returns the number of stashed tuples that were skipped because their TOAST
+ * data was gone; see rewrite_heap_tuple().
*/
-void
+double
end_heap_rewrite(RewriteState state)
{
HASH_SEQ_STATUS seq_status;
UnresolvedTup unresolved;
+ double tuples_dropped;
/*
* Write any remaining tuples in the UnresolvedTups table. If we have any
@@ -309,7 +317,8 @@ end_heap_rewrite(RewriteState state)
while ((unresolved = hash_seq_search(&seq_status)) != NULL)
{
ItemPointerSetInvalid(&unresolved->tuple->t_data->t_ctid);
- raw_heap_insert(state, unresolved->tuple);
+ if (!raw_heap_insert(state, unresolved->tuple, unresolved->recently_dead))
+ state->rs_tuples_dropped += 1;
}
/* Write the last page, if any */
@@ -323,8 +332,12 @@ end_heap_rewrite(RewriteState state)
logical_end_heap_rewrite(state);
+ tuples_dropped = state->rs_tuples_dropped;
+
/* Deleting the context frees everything */
MemoryContextDelete(state->rs_cxt);
+
+ return tuples_dropped;
}
/*
@@ -337,10 +350,18 @@ end_heap_rewrite(RewriteState state)
* state opaque state as returned by begin_heap_rewrite
* old_tuple original tuple in the old heap
* new_tuple new, rewritten tuple to be inserted to new heap
+ * recently_dead old_tuple is RECENTLY_DEAD
+ *
+ * The TOAST data of a RECENTLY_DEAD tuple may already have been removed; see
+ * raw_heap_insert(). Returns false if new_tuple was skipped for that reason,
+ * in which case the caller should count it as dead. Skipped older versions
+ * of the same update chain, which were stashed earlier and get written out
+ * here or in end_heap_rewrite(), are counted in rs_tuples_dropped instead.
*/
-void
+bool
rewrite_heap_tuple(RewriteState state,
- HeapTuple old_tuple, HeapTuple new_tuple)
+ HeapTuple old_tuple, HeapTuple new_tuple,
+ bool recently_dead)
{
MemoryContext old_cxt;
ItemPointerData old_tid;
@@ -438,13 +459,14 @@ rewrite_heap_tuple(RewriteState state,
unresolved->old_tid = old_tuple->t_self;
unresolved->tuple = heap_copytuple(new_tuple);
+ unresolved->recently_dead = recently_dead;
/*
* We can't do anything more now, since we don't know where the
* tuple will be written.
*/
MemoryContextSwitchTo(old_cxt);
- return;
+ return true;
}
}
@@ -462,7 +484,24 @@ rewrite_heap_tuple(RewriteState state,
ItemPointerData new_tid;
/* Insert the tuple and find out where it's put in new_heap */
- raw_heap_insert(state, new_tuple);
+ if (!raw_heap_insert(state, new_tuple, recently_dead))
+ {
+ if (!free_new)
+ {
+ MemoryContextSwitchTo(old_cxt);
+ return false;
+ }
+
+ /*
+ * This is a stashed older version, and the caller's tuple has
+ * already been written. Any still older version waiting for this
+ * one is written out by end_heap_rewrite().
+ */
+ state->rs_tuples_dropped += 1;
+ heap_freetuple(new_tuple);
+ MemoryContextSwitchTo(old_cxt);
+ return true;
+ }
new_tid = new_tuple->t_self;
logical_rewrite_heap_tuple(state, old_tid, new_tuple);
@@ -503,6 +542,7 @@ rewrite_heap_tuple(RewriteState state,
new_tuple = unresolved->tuple;
free_new = true;
old_tid = unresolved->old_tid;
+ recently_dead = unresolved->recently_dead;
new_tuple->t_data->t_ctid = new_tid;
/*
@@ -539,6 +579,7 @@ rewrite_heap_tuple(RewriteState state,
}
MemoryContextSwitchTo(old_cxt);
+ return true;
}
/*
@@ -599,9 +640,14 @@ rewrite_heap_dead_tuple(RewriteState state, HeapTuple old_tuple)
* t_self of the tuple is set to the new TID of the tuple. If t_ctid of the
* tuple is invalid on entry, it's replaced with the new TID as well (in
* the inserted data only, not in the caller's copy).
+ *
+ * recently_dead must be set if the tuple is RECENTLY_DEAD. Other backends
+ * may already consider such a tuple fully dead, and VACUUM or pruning of the
+ * TOAST relation may have removed its TOAST data. In that case nobody can
+ * see the tuple anymore, so it is not inserted, and false is returned.
*/
-static void
-raw_heap_insert(RewriteState state, HeapTuple tup)
+static bool
+raw_heap_insert(RewriteState state, HeapTuple tup, bool recently_dead)
{
Page page;
Size pageFreeSpace,
@@ -629,6 +675,7 @@ raw_heap_insert(RewriteState state, HeapTuple tup)
else if (HeapTupleHasExternal(tup) || tup->t_len > TOAST_TUPLE_THRESHOLD)
{
uint32 options = HEAP_INSERT_SKIP_FSM;
+ uint32 toastflags = recently_dead ? TOAST_MISSING_OK : 0;
/*
* While rewriting the heap for REPACK, make sure data for the TOAST
@@ -638,7 +685,9 @@ raw_heap_insert(RewriteState state, HeapTuple tup)
options |= HEAP_INSERT_NO_LOGICAL;
heaptup = heap_toast_insert_or_update(state->rs_new_rel, tup, NULL,
- options);
+ options, toastflags);
+ if (heaptup == NULL)
+ return false;
}
else
heaptup = tup;
@@ -712,6 +761,8 @@ raw_heap_insert(RewriteState state, HeapTuple tup)
/* If heaptup is a private copy, release it. */
if (heaptup != tup)
heap_freetuple(heaptup);
+
+ return true;
}
/* ------------------------------------------------------------------------
diff --git a/src/backend/access/table/toast_helper.c b/src/backend/access/table/toast_helper.c
index 2613d9dc095..e74e28d8e2c 100644
--- a/src/backend/access/table/toast_helper.c
+++ b/src/backend/access/table/toast_helper.c
@@ -36,9 +36,12 @@
* toast_flags is just a single uint8, but toast_attr is a caller-provided
* array with a length equal to tupleDesc->natts. The caller need not
* perform any initialization of the array before calling this function.
+ *
+ * If flags includes TOAST_MISSING_OK and an external value of the new tuple
+ * cannot be fetched, returns false instead of raising an error.
*/
-void
-toast_tuple_init(ToastTupleContext *ttc)
+bool
+toast_tuple_init(ToastTupleContext *ttc, uint32 flags)
{
TupleDesc tupleDesc = ttc->ttc_rel->rd_att;
int numAttrs = tupleDesc->natts;
@@ -141,7 +144,25 @@ toast_tuple_init(ToastTupleContext *ttc)
if (VARATT_IS_EXTERNAL(new_value))
{
ttc->ttc_attr[i].tai_oldexternal = new_value;
- if (att->attstorage == TYPSTORAGE_PLAIN)
+
+ if ((flags & TOAST_MISSING_OK) != 0 &&
+ VARATT_IS_EXTERNAL_ONDISK(new_value))
+ {
+ new_value = detoast_external_attr_extended(new_value);
+ if (new_value == NULL)
+ goto toast_missing;
+
+ /* PLAIN storage does not allow compressed values */
+ if (att->attstorage == TYPSTORAGE_PLAIN &&
+ VARATT_IS_COMPRESSED(new_value))
+ {
+ varlena *decompressed = detoast_attr(new_value);
+
+ pfree(new_value);
+ new_value = decompressed;
+ }
+ }
+ else if (att->attstorage == TYPSTORAGE_PLAIN)
new_value = detoast_attr(new_value);
else
new_value = detoast_external_attr(new_value);
@@ -163,6 +184,20 @@ toast_tuple_init(ToastTupleContext *ttc)
ttc->ttc_attr[i].tai_colflags |= TOASTCOL_IGNORE;
}
}
+
+ return true;
+
+toast_missing:
+ /* release the values fetched so far */
+ for (; i >= 0; i--)
+ {
+ if (ttc->ttc_attr[i].tai_colflags & TOASTCOL_NEEDS_FREE)
+ {
+ pfree(DatumGetPointer(ttc->ttc_values[i]));
+ ttc->ttc_attr[i].tai_colflags &= ~TOASTCOL_NEEDS_FREE;
+ }
+ }
+ return false;
}
/*
diff --git a/src/include/access/detoast.h b/src/include/access/detoast.h
index 93b7a253760..c5411b34fcc 100644
--- a/src/include/access/detoast.h
+++ b/src/include/access/detoast.h
@@ -91,6 +91,15 @@ toast_external_info_get(const struct varlena *attr, toast_external_data *toast_e
*/
extern varlena *detoast_external_attr(varlena *attr);
+/* ----------
+ * detoast_external_attr_extended() -
+ *
+ * Like detoast_external_attr, but returns NULL if toast chunks
+ * are missing (instead of raising an error).
+ * ----------
+ */
+extern varlena *detoast_external_attr_extended(varlena *attr);
+
/* ----------
* detoast_attr() -
*
diff --git a/src/include/access/heaptoast.h b/src/include/access/heaptoast.h
index 4c3fda8a5f9..f51f965507f 100644
--- a/src/include/access/heaptoast.h
+++ b/src/include/access/heaptoast.h
@@ -105,11 +105,14 @@
/* ----------
* heap_toast_insert_or_update -
*
- * Called by heap_insert() and heap_update().
+ * Called by heap_insert() and heap_update(). Returns NULL if flags
+ * includes TOAST_MISSING_OK and an external value could not be fetched.
+ * See toast_helper.h for the values of "flags".
* ----------
*/
extern HeapTuple heap_toast_insert_or_update(Relation rel, HeapTuple newtup,
- HeapTuple oldtup, uint32 options);
+ HeapTuple oldtup, uint32 options,
+ uint32 flags);
/* ----------
* heap_toast_delete -
@@ -153,11 +156,14 @@ extern HeapTuple toast_build_flattened_tuple(TupleDesc tupleDesc,
/* ----------
* heap_fetch_toast_slice
*
- * Fetch a slice from a toast value stored in a heap table.
+ * Fetch a slice from a toast value stored in a heap table. Returns
+ * false if flags includes TOAST_MISSING_OK and chunks are missing.
+ * See toast_helper.h for the values of "flags".
* ----------
*/
-extern void heap_fetch_toast_slice(Relation toastrel, Oid8 valueid,
+extern bool heap_fetch_toast_slice(Relation toastrel, Oid8 valueid,
int32 attrsize, int32 sliceoffset,
- int32 slicelength, varlena *result);
+ int32 slicelength, varlena *result,
+ uint32 flags);
#endif /* HEAPTOAST_H */
diff --git a/src/include/access/rewriteheap.h b/src/include/access/rewriteheap.h
index 6ccf7b45c04..63a78179071 100644
--- a/src/include/access/rewriteheap.h
+++ b/src/include/access/rewriteheap.h
@@ -24,9 +24,9 @@ typedef struct RewriteStateData *RewriteState;
extern RewriteState begin_heap_rewrite(Relation old_heap, Relation new_heap,
TransactionId oldest_xmin, TransactionId freeze_xid,
MultiXactId cutoff_multi);
-extern void end_heap_rewrite(RewriteState state);
-extern void rewrite_heap_tuple(RewriteState state, HeapTuple old_tuple,
- HeapTuple new_tuple);
+extern double end_heap_rewrite(RewriteState state);
+extern bool rewrite_heap_tuple(RewriteState state, HeapTuple old_tuple,
+ HeapTuple new_tuple, bool recently_dead);
extern bool rewrite_heap_dead_tuple(RewriteState state, HeapTuple old_tuple);
/*
diff --git a/src/include/access/tableam.h b/src/include/access/tableam.h
index 9d2fc7f9acb..70bf786ce08 100644
--- a/src/include/access/tableam.h
+++ b/src/include/access/tableam.h
@@ -782,12 +782,17 @@ typedef struct TableAmRoutine
* This callback is invoked when detoasting a value stored in a toast
* table implemented by this AM. See table_relation_fetch_toast_slice()
* for more details.
+ *
+ * Returns true on success. If flags (see toast_helper.h) includes
+ * TOAST_MISSING_OK, returns false instead of raising an error when chunks
+ * are missing.
*/
- void (*relation_fetch_toast_slice) (Relation toastrel, Oid8 valueid,
+ bool (*relation_fetch_toast_slice) (Relation toastrel, Oid8 valueid,
int32 attrsize,
int32 sliceoffset,
int32 slicelength,
- varlena *result);
+ varlena *result,
+ uint32 flags);
/* ------------------------------------------------------------------------
@@ -2003,11 +2008,16 @@ table_relation_toast_am(Relation rel)
*
* result is caller-allocated space into which the fetched bytes should be
* stored.
+ *
+ * flags are TOAST fetch flags, see toast_helper.h. Returns true on success.
+ * If flags includes TOAST_MISSING_OK, returns false instead of raising an
+ * error when chunks are missing.
*/
-static inline void
+static inline bool
table_relation_fetch_toast_slice(Relation toastrel, Oid8 valueid,
int32 attrsize, int32 sliceoffset,
- int32 slicelength, varlena *result)
+ int32 slicelength, varlena *result,
+ uint32 flags)
{
if (attrsize < 0 || sliceoffset < 0 || slicelength < 0)
elog(ERROR, "invalid toast slice: offset %d, length %d, value size %d",
@@ -2015,10 +2025,10 @@ table_relation_fetch_toast_slice(Relation toastrel, Oid8 valueid,
if (slicelength > attrsize - sliceoffset)
elog(ERROR, "slice length is too big");
- toastrel->rd_tableam->relation_fetch_toast_slice(toastrel, valueid,
- attrsize,
- sliceoffset, slicelength,
- result);
+ return toastrel->rd_tableam->relation_fetch_toast_slice(toastrel, valueid,
+ attrsize,
+ sliceoffset, slicelength,
+ result, flags);
}
diff --git a/src/include/access/toast_helper.h b/src/include/access/toast_helper.h
index 2ec92397f26..622700e3131 100644
--- a/src/include/access/toast_helper.h
+++ b/src/include/access/toast_helper.h
@@ -101,7 +101,16 @@ typedef struct
#define TOASTCOL_IGNORE 0x0010
#define TOASTCOL_INCOMPRESSIBLE 0x0020
-extern void toast_tuple_init(ToastTupleContext *ttc);
+/*
+ * Flags for TOAST fetch operations.
+ *
+ * TOAST_MISSING_OK makes the fetch report missing or inconsistent chunks to
+ * the caller instead of raising an error. This is only appropriate for
+ * RECENTLY_DEAD tuples, whose TOAST data may legitimately be gone already.
+ */
+#define TOAST_MISSING_OK (1 << 0)
+
+extern bool toast_tuple_init(ToastTupleContext *ttc, uint32 flags);
extern int toast_tuple_find_biggest_attribute(ToastTupleContext *ttc,
bool for_compression,
bool check_main);
--
2.54.0 (Apple Git-157)
=
^ permalink raw reply [nested|flat] 33+ messages in thread
* Re: BUG #19519: REPACK can fail due to missing chunk for toast value
@ 2026-11-12 12:49 Konstantin Knizhnik <knizhnik@garret.ru>
parent: Rui Zhao <zhaorui126@gmail.com>
0 siblings, 0 replies; 33+ messages in thread
From: Konstantin Knizhnik @ 2026-11-12 12:49 UTC (permalink / raw)
To: Rui Zhao <zhaorui126@gmail.com>; +Cc: Matthias van de Meent <boekewurm+postgres@gmail.com>; Michael Paquier <michael@paquier.xyz>; Andrey Borodin <x4mmm@yandex-team.ru>; Heikki Linnakangas <hlinnaka@iki.fi>; Srinath Reddy Sadipiralla <srinath2133@gmail.com>; Imran Zaheer <imran.zhir@gmail.com>; Alexander Lakhin <exclusion@gmail.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>
Hi,
Attached is v8 of the fix for the "missing chunk number 0 for toast
value" failures during heap rewrites and non-concurrent index builds.
This is a rebase of Matthias' v7 onto current master, with Rui Zhao's
two follow-up patches folded in, plus a bit of cleanup and one extra
fix for a whole-row expression index.
Compared to v7:
- Rebased onto current master (conflict in tableam.h resolved by
keeping master's slice validation and returning bool with flags).
- Folded in Rui's 0001 (skipped stashed prior versions are counted as
removed, not reported as a rewrite failure) and 0002 (cleanup loop
off-by-ones).
- Replaced the duplicated goto-heavy sort-path and index-build cleanup
with a shared heap_inline_recently_dead_toast() helper.
- Index builds now collect every varlena attribute referenced by the
index definition, expressions (including whole-row Vars) and the
predicate, so a whole-row expression index no longer races the same
way. A new isolation permutation covers that case.
- Dropped the duplicate recovery TAP test in favor of the dblink
isolation spec (as the v7 commit message already planned). Added
sort-path CLUSTER and UPDATE-chain permutations there.
- Comment / include-order / pgindent cleanup; TOAST_MISSING_OK is now
(1 << 0).
Verification on current master:
- make check: all 243 tests passed
- src/test/isolation: all 139 tests passed
- contrib/dblink isolation: rewrite_stale_xmin passed
- The same isolation test on unpatched master fails all 11
permutations with the missing-chunk error (CLUSTER index and sort
paths, VACUUM FULL, REPACK, CREATE INDEX, whole-row expression
index; DELETE and UPDATE chains).
CF entry: https://commitfest.postgresql.org/patch/6824/
I will update it with v8 shortly.
Regards,
Konstantin
On 24/10/2026 18:36, Rui Zhao wrote:
> Thanks for updating the patch. I tested v7 on 4b97fd15fb4 and found the
> UPDATE case from my previous mail still fails, plus two cleanup leaks.
>
> Attached are 0001 and 0002 on top of v7. All tests I ran passed.
Attachments:
v8-0001-Fix-missing-chunk-errors-during-heap-rewrites-and.patch (text/x-diff, 60.7K) download
From ffd8366a6ad0d2cf65ddfc407a09de4ad4415bac Mon Sep 17 00:00:00 2001
From: Konstantin Knizhnik <knizhnik@garret.ru>
Date: Thu, 12 Nov 2026 14:46:55 +0200
Subject: [PATCH v8] 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 skip it. This commit adds a TOAST_MISSING_OK
flag that makes the TOAST fetch paths (table_relation_fetch_toast_slice,
toast_fetch_datum, detoast_external_attr_extended, toast_tuple_init and
heap_toast_insert_or_update) report missing chunks to the caller instead
of raising an error, and uses it only for RECENTLY_DEAD tuples:
- In a heap rewrite, a RECENTLY_DEAD tuple whose TOAST data is gone is
not written and is counted as removed. This covers both directly
written tuples and update-chain members stashed in rewriteheap.c,
whose result is reported by end_heap_rewrite().
- When the rewrite sorts the tuples, the TOAST data of RECENTLY_DEAD
tuples is inlined before the sort, so that missing chunks are detected
while the tuple's visibility is still known.
- In a non-concurrent index build, the varlena attributes referenced by
the index (columns, expressions including whole-row references, and
predicate) are inlined for tuples that are not alive, and the tuple is
skipped from the index if its TOAST data is gone.
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 <exclusion@gmail.com>
Reported-by: Ekaterina Testova <e.testova@postgrespro.ru>
Author: Michael Paquier <michael@paquier.xyz>
Co-authored-by: Matthias van de Meent <boekewurm+postgres@gmail.com>
Co-authored-by: Rui Zhao <zhaorui126@gmail.com>
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/common/detoast.c | 43 +-
src/backend/access/heap/heapam.c | 4 +-
src/backend/access/heap/heapam_handler.c | 240 +++++-
src/backend/access/heap/heaptoast.c | 48 +-
src/backend/access/heap/rewriteheap.c | 71 +-
src/backend/access/table/toast_helper.c | 41 +-
src/include/access/detoast.h | 9 +
src/include/access/heaptoast.h | 16 +-
src/include/access/rewriteheap.h | 6 +-
src/include/access/tableam.h | 26 +-
src/include/access/toast_helper.h | 11 +-
16 files changed, 1467 insertions(+), 58 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..63ba262f359
--- /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 fetches TOAST data before sorting
+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/common/detoast.c b/src/backend/access/common/detoast.c
index 8223cc219c1..b27b6bb9780 100644
--- a/src/backend/access/common/detoast.c
+++ b/src/backend/access/common/detoast.c
@@ -17,6 +17,7 @@
#include "access/table.h"
#include "access/tableam.h"
#include "access/toast_compression.h"
+#include "access/toast_helper.h"
#include "access/toast_internals.h"
#include "common/int.h"
#include "common/pg_lzcompress.h"
@@ -24,7 +25,7 @@
#include "utils/memutils.h"
#include "utils/rel.h"
-static varlena *toast_fetch_datum(varlena *attr);
+static varlena *toast_fetch_datum(varlena *attr, uint32 flags);
static varlena *toast_fetch_datum_slice(varlena *attr,
int32 sliceoffset,
int32 slicelength);
@@ -61,7 +62,7 @@ detoast_external_attr(varlena *attr)
/*
* This is an external stored plain value
*/
- result = toast_fetch_datum(attr);
+ result = toast_fetch_datum(attr, 0);
}
else if (VARATT_IS_EXTERNAL_INDIRECT(attr))
{
@@ -112,6 +113,24 @@ detoast_external_attr(varlena *attr)
}
+/* ----------
+ * detoast_external_attr_extended -
+ *
+ * Like detoast_external_attr, but returns NULL instead of raising an
+ * error if the chunks of an on-disk value are missing. Only meant for
+ * RECENTLY_DEAD tuples, see TOAST_MISSING_OK.
+ * ----------
+ */
+varlena *
+detoast_external_attr_extended(varlena *attr)
+{
+ if (VARATT_IS_EXTERNAL_ONDISK(attr))
+ return toast_fetch_datum(attr, TOAST_MISSING_OK);
+ else
+ return detoast_external_attr(attr);
+}
+
+
/* ----------
* detoast_attr -
*
@@ -130,7 +149,7 @@ detoast_attr(varlena *attr)
/*
* This is an externally stored datum --- fetch it back from there
*/
- attr = toast_fetch_datum(attr);
+ attr = toast_fetch_datum(attr, 0);
/* If it's compressed, decompress it */
if (VARATT_IS_COMPRESSED(attr))
{
@@ -277,7 +296,7 @@ detoast_attr_slice(varlena *attr,
preslice = toast_fetch_datum_slice(attr, 0, max_size);
}
else
- preslice = toast_fetch_datum(attr);
+ preslice = toast_fetch_datum(attr, 0);
}
else if (VARATT_IS_EXTERNAL_INDIRECT(attr))
{
@@ -352,10 +371,12 @@ detoast_attr_slice(varlena *attr,
*
* Reconstruct an in memory Datum from the chunks saved
* in the toast relation
+ *
+ * If flags includes TOAST_MISSING_OK, returns NULL when chunks are missing.
* ----------
*/
static varlena *
-toast_fetch_datum(varlena *attr)
+toast_fetch_datum(varlena *attr, uint32 flags)
{
Relation toastrel;
varlena *result;
@@ -389,8 +410,14 @@ toast_fetch_datum(varlena *attr)
toastrel = table_open(toastrelid, AccessShareLock);
/* Fetch all chunks */
- table_relation_fetch_toast_slice(toastrel, valueid,
- attrsize, 0, attrsize, result);
+ if (!table_relation_fetch_toast_slice(toastrel, valueid,
+ attrsize, 0, attrsize, result,
+ flags))
+ {
+ pfree(result);
+ table_close(toastrel, AccessShareLock);
+ return NULL;
+ }
/* Close toast table */
table_close(toastrel, AccessShareLock);
@@ -475,7 +502,7 @@ toast_fetch_datum_slice(varlena *attr, int32 sliceoffset,
/* Fetch all chunks */
table_relation_fetch_toast_slice(toastrel, valueid,
attrsize, sliceoffset, slicelength,
- result);
+ result, 0);
/* Close toast table */
table_close(toastrel, AccessShareLock);
diff --git a/src/backend/access/heap/heapam.c b/src/backend/access/heap/heapam.c
index 3bb33699349..0b3c4ae85ed 100644
--- a/src/backend/access/heap/heapam.c
+++ b/src/backend/access/heap/heapam.c
@@ -2266,7 +2266,7 @@ heap_prepare_insert(Relation relation, HeapTuple tup, TransactionId xid,
return tup;
}
else if (HeapTupleHasExternal(tup) || tup->t_len > TOAST_TUPLE_THRESHOLD)
- return heap_toast_insert_or_update(relation, tup, NULL, options);
+ return heap_toast_insert_or_update(relation, tup, NULL, options, 0);
else
return tup;
}
@@ -3983,7 +3983,7 @@ l2:
* tuples too. We never skip the FSM here.
*/
heaptup = heap_toast_insert_or_update(relation, newtup, &oldtup,
- walLogical ? 0 : HEAP_INSERT_NO_LOGICAL);
+ walLogical ? 0 : HEAP_INSERT_NO_LOGICAL, 0);
newtupsize = MAXALIGN(heaptup->t_len);
}
else
diff --git a/src/backend/access/heap/heapam_handler.c b/src/backend/access/heap/heapam_handler.c
index 05a81e4557a..bc10b4fe891 100644
--- a/src/backend/access/heap/heapam_handler.c
+++ b/src/backend/access/heap/heapam_handler.c
@@ -19,6 +19,7 @@
*/
#include "postgres.h"
+#include "access/detoast.h"
#include "access/genam.h"
#include "access/heapam.h"
#include "access/heaptoast.h"
@@ -26,6 +27,7 @@
#include "access/rewriteheap.h"
#include "access/syncscan.h"
#include "access/tableam.h"
+#include "access/toast_helper.h"
#include "access/tsmapi.h"
#include "access/visibilitymap.h"
#include "access/xact.h"
@@ -36,6 +38,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"
@@ -48,9 +51,14 @@
#include "utils/rel.h"
#include "utils/tuplesort.h"
-static void reform_and_rewrite_tuple(HeapTuple tuple,
+static bool reform_and_rewrite_tuple(HeapTuple tuple,
Relation OldHeap, Relation NewHeap,
- Datum *values, bool *isnull, RewriteState rwstate);
+ Datum *values, bool *isnull, RewriteState rwstate,
+ bool recently_dead);
+static HeapTuple heap_inline_recently_dead_toast(HeapTuple tuple,
+ 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);
@@ -703,6 +711,7 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,
HeapTuple tuple;
Buffer buf;
bool isdead;
+ bool recently_dead = false;
CHECK_FOR_INTERRUPTS();
@@ -789,6 +798,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 */
@@ -822,6 +832,7 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,
RelationGetRelationName(OldHeap));
/* treat as recently dead */
*tups_recently_dead += 1;
+ recently_dead = true;
isdead = false;
break;
default:
@@ -850,7 +861,30 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,
*num_tuples += 1;
if (tuplesort != NULL)
{
- tuplesort_putheaptuple(tuplesort, tuple);
+ HeapTuple sorttup = tuple;
+
+ /*
+ * The tuples are written out only after the sort, by which time
+ * the TOAST data of a recently-dead tuple may be gone, so fetch
+ * it now. If it is already gone, the tuple is dead to everyone
+ * who could still read it, so skip it.
+ */
+ if (recently_dead && HeapTupleHasExternal(tuple))
+ {
+ sorttup = heap_inline_recently_dead_toast(tuple, oldTupDesc,
+ NULL, values, isnull);
+ if (sorttup == NULL)
+ {
+ *tups_vacuumed += 1;
+ *num_tuples -= 1;
+ *tups_recently_dead -= 1;
+ continue;
+ }
+ }
+
+ tuplesort_putheaptuple(tuplesort, sorttup);
+ if (sorttup != tuple)
+ heap_freetuple(sorttup);
/*
* In scan-and-sort mode, report increase in number of tuples
@@ -868,8 +902,19 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,
int64 ct_val[2];
if (!concurrent)
- reform_and_rewrite_tuple(tuple, OldHeap, NewHeap,
- values, isnull, rwstate);
+ {
+ if (!reform_and_rewrite_tuple(tuple, OldHeap, NewHeap,
+ values, isnull, rwstate,
+ recently_dead))
+ {
+ /* TOAST data of a recently-dead tuple is gone */
+ Assert(recently_dead);
+ *tups_vacuumed += 1;
+ *num_tuples -= 1;
+ *tups_recently_dead -= 1;
+ continue;
+ }
+ }
else
heap_insert_for_repack(tuple, OldHeap, NewHeap,
values, isnull, bistate);
@@ -920,11 +965,12 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,
break;
n_tuples += 1;
+ /* TOAST data of recently-dead tuples was inlined before the sort */
if (!concurrent)
- reform_and_rewrite_tuple(tuple,
- OldHeap, NewHeap,
- values, isnull,
- rwstate);
+ (void) reform_and_rewrite_tuple(tuple,
+ OldHeap, NewHeap,
+ values, isnull,
+ rwstate, false);
else
heap_insert_for_repack(tuple, OldHeap, NewHeap,
values, isnull, bistate);
@@ -939,7 +985,14 @@ heapam_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,
/* Write out any remaining tuples, and fsync if needed */
if (rwstate)
- end_heap_rewrite(rwstate);
+ {
+ double tuples_dropped = end_heap_rewrite(rwstate);
+
+ /* Stashed tuples with missing TOAST were scanned as recently dead. */
+ *tups_vacuumed += tuples_dropped;
+ *num_tuples -= tuples_dropped;
+ *tups_recently_dead -= tuples_dropped;
+ }
if (bistate)
FreeBulkInsertState(bistate);
@@ -1156,6 +1209,9 @@ heapam_index_build_range_scan(Relation heapRelation,
BlockNumber previous_blkno = InvalidBlockNumber;
BlockNumber root_blkno = InvalidBlockNumber;
OffsetNumber root_offsets[MaxHeapTuplesPerPage];
+ Bitmapset *detoast_index_attrs = NULL;
+ Datum *inline_values = NULL;
+ bool *inline_isnull = NULL;
/*
* sanity checks
@@ -1252,6 +1308,50 @@ heapam_index_build_range_scan(Relation heapRelation,
!TransactionIdIsValid(OldestXmin));
Assert(snapshot == SnapshotAny || !anyvisible);
+ /*
+ * Collect the varlena columns that the index columns, expressions and
+ * predicate reference, so that their TOAST data can be fetched for
+ * RECENTLY_DEAD tuples; see below. A whole-row reference needs all of
+ * them. The set contains plain attribute numbers.
+ */
+ {
+ TupleDesc desc = RelationGetDescr(heapRelation);
+ Bitmapset *refattrs = 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))
+ detoast_index_attrs = bms_add_member(detoast_index_attrs,
+ attnum);
+ }
+ bms_free(refattrs);
+
+ if (detoast_index_attrs != NULL)
+ {
+ inline_values = palloc_array(Datum, desc->natts);
+ inline_isnull = palloc_array(bool, desc->natts);
+ }
+ }
+
/* Publish number of blocks to scan */
if (progress)
{
@@ -1590,6 +1690,29 @@ heapam_index_build_range_scan(Relation heapRelation,
/* Set up for predicate or expression evaluation */
ExecStoreBufferHeapTuple(heapTuple, slot, hscan->rs_cbuf);
+ /*
+ * The TOAST data of a RECENTLY_DEAD tuple can be removed while we
+ * look at it; see heap_inline_recently_dead_toast(). Fetch what the
+ * index needs up front, and skip the tuple if it is already gone.
+ */
+ if (!tupleIsAlive && detoast_index_attrs != NULL &&
+ HeapTupleHasExternal(heapTuple))
+ {
+ HeapTuple inlined;
+
+ inlined = heap_inline_recently_dead_toast(heapTuple,
+ RelationGetDescr(heapRelation),
+ detoast_index_attrs,
+ inline_values, inline_isnull);
+ if (inlined == NULL)
+ continue;
+ if (inlined != heapTuple)
+ {
+ ExecForceStoreHeapTuple(inlined, slot, true);
+ slot->tts_tableOid = RelationGetRelid(heapRelation);
+ }
+ }
+
/*
* In a partial index, discard tuples that don't satisfy the
* predicate.
@@ -1698,6 +1821,12 @@ heapam_index_build_range_scan(Relation heapRelation,
indexInfo->ii_ExpressionsState = NIL;
indexInfo->ii_PredicateState = NULL;
+ bms_free(detoast_index_attrs);
+ if (inline_values)
+ pfree(inline_values);
+ if (inline_isnull)
+ pfree(inline_isnull);
+
return reltuples;
}
@@ -2338,20 +2467,105 @@ heapam_scan_sample_next_tuple(TableScanDesc scan, SampleScanState *scanstate,
* SET WITHOUT OIDS.
*
* So, we must reconstruct the tuple from component Datums.
+ *
+ * recently_dead must be set if the tuple is RECENTLY_DEAD. Returns false if
+ * the tuple was skipped because its TOAST data is gone; see
+ * rewrite_heap_tuple().
*/
-static void
+static bool
reform_and_rewrite_tuple(HeapTuple tuple,
Relation OldHeap, Relation NewHeap,
- Datum *values, bool *isnull, RewriteState rwstate)
+ Datum *values, bool *isnull, RewriteState rwstate,
+ bool recently_dead)
{
HeapTuple newtuple;
+ bool written;
newtuple = reform_tuple(tuple, OldHeap, NewHeap, values, isnull);
/* The heap rewrite module does the rest */
- rewrite_heap_tuple(rwstate, tuple, newtuple);
+ written = rewrite_heap_tuple(rwstate, tuple, newtuple, recently_dead);
heap_freetuple(newtuple);
+ return written;
+}
+
+/*
+ * Fetch the out-of-line TOAST values of a RECENTLY_DEAD tuple, and return a
+ * copy of the tuple with those values stored inline, keeping the original
+ * tuple's identity and visibility information.
+ *
+ * Other backends may already consider a RECENTLY_DEAD tuple fully dead, so
+ * its TOAST data can be removed by VACUUM or pruning of the TOAST relation at
+ * any time. If any value is already gone, return NULL: nobody can see the
+ * tuple anymore, and the caller should treat it as dead.
+ *
+ * attrs is the set of attribute numbers to fetch, or NULL for all of them.
+ * Returns the tuple itself if there is nothing to fetch. values and isnull
+ * are caller-provided workspace of tupdesc->natts entries.
+ */
+static HeapTuple
+heap_inline_recently_dead_toast(HeapTuple tuple, TupleDesc tupdesc,
+ const Bitmapset *attrs,
+ Datum *values, bool *isnull)
+{
+ Bitmapset *fetched = NULL;
+ HeapTuple result = NULL;
+ int i;
+
+ heap_deform_tuple(tuple, tupdesc, values, isnull);
+
+ for (i = 0; i < tupdesc->natts; i++)
+ {
+ CompactAttribute *att = TupleDescCompactAttr(tupdesc, i);
+ varlena *value;
+
+ if (att->attlen != -1 || isnull[i])
+ continue;
+ if (attrs != NULL && !bms_is_member(i + 1, attrs))
+ continue;
+
+ /* reform_tuple() throws away dropped columns anyway */
+ if (att->attisdropped)
+ {
+ isnull[i] = true;
+ continue;
+ }
+
+ value = (varlena *) DatumGetPointer(values[i]);
+ if (!VARATT_IS_EXTERNAL_ONDISK(value))
+ continue;
+
+ value = detoast_external_attr_extended(value);
+ if (value == NULL)
+ goto cleanup;
+
+ values[i] = PointerGetDatum(value);
+ fetched = bms_add_member(fetched, i);
+ }
+
+ if (fetched == NULL)
+ return tuple;
+
+ result = heap_form_tuple(tupdesc, values, isnull);
+
+ result->t_data->t_choice = tuple->t_data->t_choice;
+ result->t_data->t_ctid = tuple->t_data->t_ctid;
+ result->t_data->t_infomask2 &= ~HEAP2_XACT_MASK;
+ result->t_data->t_infomask2 |=
+ tuple->t_data->t_infomask2 & HEAP2_XACT_MASK;
+ result->t_data->t_infomask &= ~HEAP_XACT_MASK;
+ result->t_data->t_infomask |= tuple->t_data->t_infomask & HEAP_XACT_MASK;
+ result->t_self = tuple->t_self;
+ result->t_tableOid = tuple->t_tableOid;
+
+cleanup:
+ i = -1;
+ while ((i = bms_next_member(fetched, i)) >= 0)
+ pfree(DatumGetPointer(values[i]));
+ bms_free(fetched);
+
+ return result;
}
/*
diff --git a/src/backend/access/heap/heaptoast.c b/src/backend/access/heap/heaptoast.c
index e329662b683..1097e076bb9 100644
--- a/src/backend/access/heap/heaptoast.c
+++ b/src/backend/access/heap/heaptoast.c
@@ -84,9 +84,11 @@ heap_toast_delete(Relation rel, HeapTuple oldtup, bool is_speculative)
* newtup: the candidate new tuple to be inserted
* oldtup: the old row version for UPDATE, or NULL for INSERT
* options: options to be passed to heap_insert() for toast rows
+ * flags: TOAST fetch flags, see toast_helper.h
* Result:
* either newtup if no toasting is needed, or a palloc'd modified tuple
- * that is what should actually get stored
+ * that is what should actually get stored, or NULL if flags includes
+ * TOAST_MISSING_OK and an external value of newtup could not be fetched
*
* NOTE: neither newtup nor oldtup will be modified. This is a change
* from the pre-8.1 API of this routine.
@@ -94,7 +96,7 @@ heap_toast_delete(Relation rel, HeapTuple oldtup, bool is_speculative)
*/
HeapTuple
heap_toast_insert_or_update(Relation rel, HeapTuple newtup, HeapTuple oldtup,
- uint32 options)
+ uint32 options, uint32 flags)
{
HeapTuple result_tuple;
TupleDesc tupleDesc;
@@ -154,7 +156,8 @@ heap_toast_insert_or_update(Relation rel, HeapTuple newtup, HeapTuple oldtup,
ttc.ttc_oldisnull = toast_oldisnull;
}
ttc.ttc_attr = toast_attr;
- toast_tuple_init(&ttc);
+ if (!toast_tuple_init(&ttc, flags))
+ return NULL;
/* ----------
* Compress and/or save external until data fits into target length
@@ -636,11 +639,15 @@ toast_build_flattened_tuple(TupleDesc tupleDesc,
* sliceoffset is the byte offset within the TOAST value from which to fetch.
* slicelength is the number of bytes to be fetched from the TOAST value.
* result is the varlena into which the results should be written.
+ * flags are TOAST fetch flags, see toast_helper.h.
+ *
+ * Returns true on success. If flags includes TOAST_MISSING_OK, returns false
+ * instead of raising an error when chunks are missing or inconsistent.
*/
-void
+bool
heap_fetch_toast_slice(Relation toastrel, Oid8 valueid, int32 attrsize,
int32 sliceoffset, int32 slicelength,
- varlena *result)
+ varlena *result, uint32 flags)
{
Relation *toastidxs;
ScanKeyData toastkey[3];
@@ -753,27 +760,45 @@ heap_fetch_toast_slice(Relation toastrel, Oid8 valueid, int32 attrsize,
* Some checks on the data we've found
*/
if (curchunk != expectedchunk)
+ {
+ if (flags & TOAST_MISSING_OK)
+ goto toast_missing;
+
ereport(ERROR,
(errcode(ERRCODE_DATA_CORRUPTED),
errmsg_internal("unexpected chunk number %d (expected %d) for toast value %" PRIu64 " in %s",
curchunk, expectedchunk, valueid,
RelationGetRelationName(toastrel))));
+ }
+
if (curchunk > endchunk)
+ {
+ if (flags & TOAST_MISSING_OK)
+ goto toast_missing;
+
ereport(ERROR,
(errcode(ERRCODE_DATA_CORRUPTED),
errmsg_internal("unexpected chunk number %d (out of range %d..%d) for toast value %" PRIu64 " in %s",
curchunk,
startchunk, endchunk, valueid,
RelationGetRelationName(toastrel))));
+ }
+
expected_size = curchunk < totalchunks - 1 ? max_chunk_size
: attrsize - ((totalchunks - 1) * max_chunk_size);
+
if (chunksize != expected_size)
+ {
+ if (flags & TOAST_MISSING_OK)
+ goto toast_missing;
+
ereport(ERROR,
(errcode(ERRCODE_DATA_CORRUPTED),
errmsg_internal("unexpected chunk size %d (expected %d) in chunk %d of %d for toast value %" PRIu64 " in %s",
chunksize, expected_size,
curchunk, totalchunks, valueid,
RelationGetRelationName(toastrel))));
+ }
/*
* Copy the data into proper place in our result
@@ -797,13 +822,26 @@ heap_fetch_toast_slice(Relation toastrel, Oid8 valueid, int32 attrsize,
* Final checks that we successfully fetched the datum
*/
if (expectedchunk != (endchunk + 1))
+ {
+ if (flags & TOAST_MISSING_OK)
+ goto toast_missing;
+
ereport(ERROR,
(errcode(ERRCODE_DATA_CORRUPTED),
errmsg_internal("missing chunk number %d for toast value %" PRIu64 " in %s",
expectedchunk, valueid,
RelationGetRelationName(toastrel))));
+ }
/* End scan and close indexes. */
systable_endscan_ordered(toastscan);
toast_close_indexes(toastidxs, num_indexes, AccessShareLock);
+
+ return true;
+
+toast_missing:
+ systable_endscan_ordered(toastscan);
+ toast_close_indexes(toastidxs, num_indexes, AccessShareLock);
+
+ return false;
}
diff --git a/src/backend/access/heap/rewriteheap.c b/src/backend/access/heap/rewriteheap.c
index be0f6646b83..2ab3f77edfc 100644
--- a/src/backend/access/heap/rewriteheap.c
+++ b/src/backend/access/heap/rewriteheap.c
@@ -108,6 +108,7 @@
#include "access/heapam_xlog.h"
#include "access/heaptoast.h"
#include "access/rewriteheap.h"
+#include "access/toast_helper.h"
#include "access/transam.h"
#include "access/xact.h"
#include "access/xloginsert.h"
@@ -149,6 +150,7 @@ typedef struct RewriteStateData
XLogRecPtr rs_begin_lsn; /* XLogInsertLsn when starting the rewrite */
HTAB *rs_unresolved_tups; /* unmatched A tuples */
HTAB *rs_old_new_tid_map; /* unmatched B tuples */
+ double rs_tuples_dropped; /* # stashed tuples skipped, TOAST gone */
HTAB *rs_logical_mappings; /* logical remapping files */
uint32 rs_num_rewrite_mappings; /* # in memory mappings */
} RewriteStateData;
@@ -172,6 +174,7 @@ typedef struct
{
TidHashKey key; /* expected xmin/old location of B tuple */
ItemPointerData old_tid; /* A's location in the old heap */
+ bool recently_dead; /* A was RECENTLY_DEAD */
HeapTuple tuple; /* A's tuple contents */
} UnresolvedTupData;
@@ -211,7 +214,8 @@ typedef struct RewriteMappingDataEntry
/* prototypes for internal functions */
-static void raw_heap_insert(RewriteState state, HeapTuple tup);
+static bool raw_heap_insert(RewriteState state, HeapTuple tup,
+ bool recently_dead);
/* internal logical remapping prototypes */
static void logical_begin_heap_rewrite(RewriteState state);
@@ -293,12 +297,16 @@ begin_heap_rewrite(Relation old_heap, Relation new_heap, TransactionId oldest_xm
* End a rewrite.
*
* state and any other resources are freed.
+ *
+ * Returns the number of stashed tuples that were skipped because their TOAST
+ * data was gone; see rewrite_heap_tuple().
*/
-void
+double
end_heap_rewrite(RewriteState state)
{
HASH_SEQ_STATUS seq_status;
UnresolvedTup unresolved;
+ double tuples_dropped;
/*
* Write any remaining tuples in the UnresolvedTups table. If we have any
@@ -309,7 +317,8 @@ end_heap_rewrite(RewriteState state)
while ((unresolved = hash_seq_search(&seq_status)) != NULL)
{
ItemPointerSetInvalid(&unresolved->tuple->t_data->t_ctid);
- raw_heap_insert(state, unresolved->tuple);
+ if (!raw_heap_insert(state, unresolved->tuple, unresolved->recently_dead))
+ state->rs_tuples_dropped += 1;
}
/* Write the last page, if any */
@@ -323,8 +332,12 @@ end_heap_rewrite(RewriteState state)
logical_end_heap_rewrite(state);
+ tuples_dropped = state->rs_tuples_dropped;
+
/* Deleting the context frees everything */
MemoryContextDelete(state->rs_cxt);
+
+ return tuples_dropped;
}
/*
@@ -337,10 +350,18 @@ end_heap_rewrite(RewriteState state)
* state opaque state as returned by begin_heap_rewrite
* old_tuple original tuple in the old heap
* new_tuple new, rewritten tuple to be inserted to new heap
+ * recently_dead old_tuple is RECENTLY_DEAD
+ *
+ * The TOAST data of a RECENTLY_DEAD tuple may already have been removed; see
+ * raw_heap_insert(). Returns false if new_tuple was skipped for that reason,
+ * in which case the caller should count it as dead. Skipped older versions
+ * of the same update chain, which were stashed earlier and get written out
+ * here or in end_heap_rewrite(), are counted in rs_tuples_dropped instead.
*/
-void
+bool
rewrite_heap_tuple(RewriteState state,
- HeapTuple old_tuple, HeapTuple new_tuple)
+ HeapTuple old_tuple, HeapTuple new_tuple,
+ bool recently_dead)
{
MemoryContext old_cxt;
ItemPointerData old_tid;
@@ -438,13 +459,14 @@ rewrite_heap_tuple(RewriteState state,
unresolved->old_tid = old_tuple->t_self;
unresolved->tuple = heap_copytuple(new_tuple);
+ unresolved->recently_dead = recently_dead;
/*
* We can't do anything more now, since we don't know where the
* tuple will be written.
*/
MemoryContextSwitchTo(old_cxt);
- return;
+ return true;
}
}
@@ -462,7 +484,24 @@ rewrite_heap_tuple(RewriteState state,
ItemPointerData new_tid;
/* Insert the tuple and find out where it's put in new_heap */
- raw_heap_insert(state, new_tuple);
+ if (!raw_heap_insert(state, new_tuple, recently_dead))
+ {
+ if (!free_new)
+ {
+ MemoryContextSwitchTo(old_cxt);
+ return false;
+ }
+
+ /*
+ * This is a stashed older version, and the caller's tuple has
+ * already been written. Any still older version waiting for this
+ * one is written out by end_heap_rewrite().
+ */
+ state->rs_tuples_dropped += 1;
+ heap_freetuple(new_tuple);
+ MemoryContextSwitchTo(old_cxt);
+ return true;
+ }
new_tid = new_tuple->t_self;
logical_rewrite_heap_tuple(state, old_tid, new_tuple);
@@ -503,6 +542,7 @@ rewrite_heap_tuple(RewriteState state,
new_tuple = unresolved->tuple;
free_new = true;
old_tid = unresolved->old_tid;
+ recently_dead = unresolved->recently_dead;
new_tuple->t_data->t_ctid = new_tid;
/*
@@ -539,6 +579,7 @@ rewrite_heap_tuple(RewriteState state,
}
MemoryContextSwitchTo(old_cxt);
+ return true;
}
/*
@@ -599,9 +640,14 @@ rewrite_heap_dead_tuple(RewriteState state, HeapTuple old_tuple)
* t_self of the tuple is set to the new TID of the tuple. If t_ctid of the
* tuple is invalid on entry, it's replaced with the new TID as well (in
* the inserted data only, not in the caller's copy).
+ *
+ * recently_dead must be set if the tuple is RECENTLY_DEAD. Other backends
+ * may already consider such a tuple fully dead, and VACUUM or pruning of the
+ * TOAST relation may have removed its TOAST data. In that case nobody can
+ * see the tuple anymore, so it is not inserted, and false is returned.
*/
-static void
-raw_heap_insert(RewriteState state, HeapTuple tup)
+static bool
+raw_heap_insert(RewriteState state, HeapTuple tup, bool recently_dead)
{
Page page;
Size pageFreeSpace,
@@ -629,6 +675,7 @@ raw_heap_insert(RewriteState state, HeapTuple tup)
else if (HeapTupleHasExternal(tup) || tup->t_len > TOAST_TUPLE_THRESHOLD)
{
uint32 options = HEAP_INSERT_SKIP_FSM;
+ uint32 toastflags = recently_dead ? TOAST_MISSING_OK : 0;
/*
* While rewriting the heap for REPACK, make sure data for the TOAST
@@ -638,7 +685,9 @@ raw_heap_insert(RewriteState state, HeapTuple tup)
options |= HEAP_INSERT_NO_LOGICAL;
heaptup = heap_toast_insert_or_update(state->rs_new_rel, tup, NULL,
- options);
+ options, toastflags);
+ if (heaptup == NULL)
+ return false;
}
else
heaptup = tup;
@@ -712,6 +761,8 @@ raw_heap_insert(RewriteState state, HeapTuple tup)
/* If heaptup is a private copy, release it. */
if (heaptup != tup)
heap_freetuple(heaptup);
+
+ return true;
}
/* ------------------------------------------------------------------------
diff --git a/src/backend/access/table/toast_helper.c b/src/backend/access/table/toast_helper.c
index 2613d9dc095..e74e28d8e2c 100644
--- a/src/backend/access/table/toast_helper.c
+++ b/src/backend/access/table/toast_helper.c
@@ -36,9 +36,12 @@
* toast_flags is just a single uint8, but toast_attr is a caller-provided
* array with a length equal to tupleDesc->natts. The caller need not
* perform any initialization of the array before calling this function.
+ *
+ * If flags includes TOAST_MISSING_OK and an external value of the new tuple
+ * cannot be fetched, returns false instead of raising an error.
*/
-void
-toast_tuple_init(ToastTupleContext *ttc)
+bool
+toast_tuple_init(ToastTupleContext *ttc, uint32 flags)
{
TupleDesc tupleDesc = ttc->ttc_rel->rd_att;
int numAttrs = tupleDesc->natts;
@@ -141,7 +144,25 @@ toast_tuple_init(ToastTupleContext *ttc)
if (VARATT_IS_EXTERNAL(new_value))
{
ttc->ttc_attr[i].tai_oldexternal = new_value;
- if (att->attstorage == TYPSTORAGE_PLAIN)
+
+ if ((flags & TOAST_MISSING_OK) != 0 &&
+ VARATT_IS_EXTERNAL_ONDISK(new_value))
+ {
+ new_value = detoast_external_attr_extended(new_value);
+ if (new_value == NULL)
+ goto toast_missing;
+
+ /* PLAIN storage does not allow compressed values */
+ if (att->attstorage == TYPSTORAGE_PLAIN &&
+ VARATT_IS_COMPRESSED(new_value))
+ {
+ varlena *decompressed = detoast_attr(new_value);
+
+ pfree(new_value);
+ new_value = decompressed;
+ }
+ }
+ else if (att->attstorage == TYPSTORAGE_PLAIN)
new_value = detoast_attr(new_value);
else
new_value = detoast_external_attr(new_value);
@@ -163,6 +184,20 @@ toast_tuple_init(ToastTupleContext *ttc)
ttc->ttc_attr[i].tai_colflags |= TOASTCOL_IGNORE;
}
}
+
+ return true;
+
+toast_missing:
+ /* release the values fetched so far */
+ for (; i >= 0; i--)
+ {
+ if (ttc->ttc_attr[i].tai_colflags & TOASTCOL_NEEDS_FREE)
+ {
+ pfree(DatumGetPointer(ttc->ttc_values[i]));
+ ttc->ttc_attr[i].tai_colflags &= ~TOASTCOL_NEEDS_FREE;
+ }
+ }
+ return false;
}
/*
diff --git a/src/include/access/detoast.h b/src/include/access/detoast.h
index 93b7a253760..c5411b34fcc 100644
--- a/src/include/access/detoast.h
+++ b/src/include/access/detoast.h
@@ -91,6 +91,15 @@ toast_external_info_get(const struct varlena *attr, toast_external_data *toast_e
*/
extern varlena *detoast_external_attr(varlena *attr);
+/* ----------
+ * detoast_external_attr_extended() -
+ *
+ * Like detoast_external_attr, but returns NULL if toast chunks
+ * are missing (instead of raising an error).
+ * ----------
+ */
+extern varlena *detoast_external_attr_extended(varlena *attr);
+
/* ----------
* detoast_attr() -
*
diff --git a/src/include/access/heaptoast.h b/src/include/access/heaptoast.h
index 4c3fda8a5f9..f51f965507f 100644
--- a/src/include/access/heaptoast.h
+++ b/src/include/access/heaptoast.h
@@ -105,11 +105,14 @@
/* ----------
* heap_toast_insert_or_update -
*
- * Called by heap_insert() and heap_update().
+ * Called by heap_insert() and heap_update(). Returns NULL if flags
+ * includes TOAST_MISSING_OK and an external value could not be fetched.
+ * See toast_helper.h for the values of "flags".
* ----------
*/
extern HeapTuple heap_toast_insert_or_update(Relation rel, HeapTuple newtup,
- HeapTuple oldtup, uint32 options);
+ HeapTuple oldtup, uint32 options,
+ uint32 flags);
/* ----------
* heap_toast_delete -
@@ -153,11 +156,14 @@ extern HeapTuple toast_build_flattened_tuple(TupleDesc tupleDesc,
/* ----------
* heap_fetch_toast_slice
*
- * Fetch a slice from a toast value stored in a heap table.
+ * Fetch a slice from a toast value stored in a heap table. Returns
+ * false if flags includes TOAST_MISSING_OK and chunks are missing.
+ * See toast_helper.h for the values of "flags".
* ----------
*/
-extern void heap_fetch_toast_slice(Relation toastrel, Oid8 valueid,
+extern bool heap_fetch_toast_slice(Relation toastrel, Oid8 valueid,
int32 attrsize, int32 sliceoffset,
- int32 slicelength, varlena *result);
+ int32 slicelength, varlena *result,
+ uint32 flags);
#endif /* HEAPTOAST_H */
diff --git a/src/include/access/rewriteheap.h b/src/include/access/rewriteheap.h
index 6ccf7b45c04..63a78179071 100644
--- a/src/include/access/rewriteheap.h
+++ b/src/include/access/rewriteheap.h
@@ -24,9 +24,9 @@ typedef struct RewriteStateData *RewriteState;
extern RewriteState begin_heap_rewrite(Relation old_heap, Relation new_heap,
TransactionId oldest_xmin, TransactionId freeze_xid,
MultiXactId cutoff_multi);
-extern void end_heap_rewrite(RewriteState state);
-extern void rewrite_heap_tuple(RewriteState state, HeapTuple old_tuple,
- HeapTuple new_tuple);
+extern double end_heap_rewrite(RewriteState state);
+extern bool rewrite_heap_tuple(RewriteState state, HeapTuple old_tuple,
+ HeapTuple new_tuple, bool recently_dead);
extern bool rewrite_heap_dead_tuple(RewriteState state, HeapTuple old_tuple);
/*
diff --git a/src/include/access/tableam.h b/src/include/access/tableam.h
index 9d2fc7f9acb..70bf786ce08 100644
--- a/src/include/access/tableam.h
+++ b/src/include/access/tableam.h
@@ -782,12 +782,17 @@ typedef struct TableAmRoutine
* This callback is invoked when detoasting a value stored in a toast
* table implemented by this AM. See table_relation_fetch_toast_slice()
* for more details.
+ *
+ * Returns true on success. If flags (see toast_helper.h) includes
+ * TOAST_MISSING_OK, returns false instead of raising an error when chunks
+ * are missing.
*/
- void (*relation_fetch_toast_slice) (Relation toastrel, Oid8 valueid,
+ bool (*relation_fetch_toast_slice) (Relation toastrel, Oid8 valueid,
int32 attrsize,
int32 sliceoffset,
int32 slicelength,
- varlena *result);
+ varlena *result,
+ uint32 flags);
/* ------------------------------------------------------------------------
@@ -2003,11 +2008,16 @@ table_relation_toast_am(Relation rel)
*
* result is caller-allocated space into which the fetched bytes should be
* stored.
+ *
+ * flags are TOAST fetch flags, see toast_helper.h. Returns true on success.
+ * If flags includes TOAST_MISSING_OK, returns false instead of raising an
+ * error when chunks are missing.
*/
-static inline void
+static inline bool
table_relation_fetch_toast_slice(Relation toastrel, Oid8 valueid,
int32 attrsize, int32 sliceoffset,
- int32 slicelength, varlena *result)
+ int32 slicelength, varlena *result,
+ uint32 flags)
{
if (attrsize < 0 || sliceoffset < 0 || slicelength < 0)
elog(ERROR, "invalid toast slice: offset %d, length %d, value size %d",
@@ -2015,10 +2025,10 @@ table_relation_fetch_toast_slice(Relation toastrel, Oid8 valueid,
if (slicelength > attrsize - sliceoffset)
elog(ERROR, "slice length is too big");
- toastrel->rd_tableam->relation_fetch_toast_slice(toastrel, valueid,
- attrsize,
- sliceoffset, slicelength,
- result);
+ return toastrel->rd_tableam->relation_fetch_toast_slice(toastrel, valueid,
+ attrsize,
+ sliceoffset, slicelength,
+ result, flags);
}
diff --git a/src/include/access/toast_helper.h b/src/include/access/toast_helper.h
index 2ec92397f26..622700e3131 100644
--- a/src/include/access/toast_helper.h
+++ b/src/include/access/toast_helper.h
@@ -101,7 +101,16 @@ typedef struct
#define TOASTCOL_IGNORE 0x0010
#define TOASTCOL_INCOMPRESSIBLE 0x0020
-extern void toast_tuple_init(ToastTupleContext *ttc);
+/*
+ * Flags for TOAST fetch operations.
+ *
+ * TOAST_MISSING_OK makes the fetch report missing or inconsistent chunks to
+ * the caller instead of raising an error. This is only appropriate for
+ * RECENTLY_DEAD tuples, whose TOAST data may legitimately be gone already.
+ */
+#define TOAST_MISSING_OK (1 << 0)
+
+extern bool toast_tuple_init(ToastTupleContext *ttc, uint32 flags);
extern int toast_tuple_find_biggest_attribute(ToastTupleContext *ttc,
bool for_compression,
bool check_main);
--
2.54.0 (Apple Git-157)
^ permalink raw reply [nested|flat] 33+ messages in thread
end of thread, other threads:[~2026-11-12 12:49 UTC | newest]
Thread overview: 33+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2026-06-14 07:00 BUG #19519: REPACK can fail due to missing chunk for toast value PG Bug reporting form <noreply@postgresql.org>
2026-06-17 17:03 ` Srinath Reddy Sadipiralla <srinath2133@gmail.com>
2026-07-03 06:45 ` Imran Zaheer <imran.zhir@gmail.com>
2026-07-06 06:36 ` Michael Paquier <michael@paquier.xyz>
2026-07-06 13:38 ` Konstantin Knizhnik <knizhnik@garret.ru>
2026-07-06 18:00 ` Alexander Lakhin <exclusion@gmail.com>
2026-07-06 18:21 ` Matthias van de Meent <boekewurm+postgres@gmail.com>
2026-07-06 23:18 ` Michael Paquier <michael@paquier.xyz>
2026-07-06 23:51 ` Matthias van de Meent <boekewurm+postgres@gmail.com>
2026-07-07 01:42 ` Michael Paquier <michael@paquier.xyz>
2026-07-07 05:21 ` Michael Paquier <michael@paquier.xyz>
2026-07-07 17:10 ` Srinath Reddy Sadipiralla <srinath2133@gmail.com>
2026-07-07 22:15 ` Michael Paquier <michael@paquier.xyz>
2026-07-08 01:10 ` Michael Paquier <michael@paquier.xyz>
2026-07-08 12:00 ` Heikki Linnakangas <hlinnaka@iki.fi>
2026-07-08 15:00 ` Imran Zaheer <imran.zhir@gmail.com>
2026-07-08 22:49 ` Michael Paquier <michael@paquier.xyz>
2026-07-09 02:47 ` Michael Paquier <michael@paquier.xyz>
2026-07-24 11:39 ` Zhijie Hou (Fujitsu) <houzj.fnst@fujitsu.com>
2026-07-30 19:54 ` Matthias van de Meent <boekewurm+postgres@gmail.com>
2026-08-05 18:18 ` Andrey Borodin <x4mmm@yandex-team.ru>
2026-10-09 12:56 ` Matthias van de Meent <boekewurm+postgres@gmail.com>
2026-10-12 10:57 ` Matthias van de Meent <boekewurm+postgres@gmail.com>
2026-10-24 04:41 ` shihao zhong <zhong950419@gmail.com>
2026-10-24 15:36 ` Rui Zhao <zhaorui126@gmail.com>
2026-11-12 12:49 ` Konstantin Knizhnik <knizhnik@garret.ru>
2026-08-23 17:12 ` Rui Zhao <zhaorui126@gmail.com>
2026-07-09 05:17 ` Konstantin Knizhnik <knizhnik@garret.ru>
2026-07-09 05:43 ` Michael Paquier <michael@paquier.xyz>
2026-07-09 10:08 ` Konstantin Knizhnik <knizhnik@garret.ru>
2026-07-21 15:44 ` Dilip Kumar <dilipbalaut@gmail.com>
2026-07-17 10:22 ` Matthias van de Meent <boekewurm+postgres@gmail.com>
2026-11-12 12:47 Re: BUG #19519: REPACK can fail due to missing chunk for toast value Konstantin Knizhnik <konstantin.knizhnik@databricks.com>
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox