pg.ddx.io  pgsql-hackers@postgresql.org mailing list archive  
help / color / mirror / Atom feed
REPACK (CONCURRENTLY) loses missing values of columns added without a rewrite
9+ messages / 4 participants
[nested] [flat]

Commits from this thread:
  2026-09-25 a4052efe2a 45da2c1d75  Fix REPACK (CONCURRENTLY) for columns added without a table rewrite
* REPACK (CONCURRENTLY) loses missing values of columns added without a rewrite
@ 2026-09-22 18:01  Sami Imseih <samimseih.pg@gmail.com>
  0 siblings, 2 replies; 9+ messages in thread

From: Sami Imseih @ 2026-09-22 18:01 UTC (permalink / raw)
  To: Postgres hackers <pgsql-hackers@lists.postgresql.org>

Hi,

REPACK (CONCURRENTLY) is not correctly accounting for missing values when
applying decoded changes to the transient relation (NewHeap). This is
because it is using the NewHeap descriptor, which intentionally has no
missing values when it is formed in make_new_heap().

This can leave a column with NULL instead of its default value, even if the
column is NOT NULL. It only happens today when an UPDATE during the repack
fires a BEFORE UPDATE trigger that returns OLD, so the new row version
reuses a tuple written before the ALTER TABLE ... ADD COLUMN ... DEFAULT.

```
# session 1
CREATE EXTENSION injection_points;
CREATE TABLE t(i int primary key, j int);
INSERT INTO t VALUES (1,1),(2,2),(3,3);
ALTER TABLE t ADD COLUMN c int NOT NULL DEFAULT 42;
CREATE FUNCTION retold() RETURNS trigger LANGUAGE plpgsql AS 'BEGIN
RETURN OLD; END';
CREATE TRIGGER tr BEFORE UPDATE ON t FOR EACH ROW EXECUTE FUNCTION retold();
SELECT injection_points_attach('repack-concurrently-before-lock', 'wait');
REPACK (CONCURRENTLY) t;

# session 2
UPDATE t SET j = j WHERE i IN (1,2);
SELECT injection_points_wakeup('repack-concurrently-before-lock');
SELECT injection_points_detach('repack-concurrently-before-lock');
SELECT * FROM t;
```

The final SELECT * FROM t; results in

```
 i | j | c
---+---+----
 3 | 3 | 42
 1 | 1 |
 2 | 2 |
(3 rows)
```

where i = 1 and 2 are missing the value of the default column.

The same issue has been found previously in different cases. 16828d5c027
made every consumer of a stored tuple responsible for the missing values,
ba9f18abd36 worked around one such case by expanding the tuple in
MaterializeTupleForTrigger(), and 20d3fe9009d replaced that workaround by
using the real tuple descriptor instead.

The attached patch takes the same approach as 20d3fe9009d, which is to use
the real tuple descriptor rather than expand the tuple. It deforms the decoded
tuples with the descriptor of the relation they were decoded from, which is
the only one that has the missing values. Tuples formed with it are still
valid for the transient relation, whose attributes are a copy of the source
relation ones. An isolation test is included.

My first thought was to expand the decoded tuple with heap_expand_tuple(),
but that is the workaround of ba9f18abd which 20d3fe9009d got rid of.
heap_expand_tuple() has had no caller in the tree since then, and
minimal_expand_tuple() has had none since 4da597edf1b, so as a separate
cleanup for v20 it may be worth removing both.

I will add this to the v19 open items, as I think it should be backpatched.

--
Sami Imseih
Amazon Web Services

Attachments:

v1-0001-Fix-REPACK-CONCURRENTLY-for-columns-added-without.patch (application/octet-stream, 9.5K) download From 970a30586cb141eea0dbc3f08cf4d562dc479575 Mon Sep 17 00:00:00 2001 From: Sami Imseih <samimseih.pg@gmail.com> Date: Tue, 22 Sep 2026 17:01:29 +0000 Subject: [PATCH v1 1/1] Fix REPACK (CONCURRENTLY) for columns added without a table rewrite When applying the concurrent data changes, REPACK deformed the decoded tuples with the descriptor of the transient relation. That descriptor has no "missing" values, because make_new_heap() gives the transient relation none of the defaults and constraints of the source relation. A tuple written before an ALTER TABLE ... ADD COLUMN that did not rewrite the table has fewer attributes than the descriptor, so the missing values came out as NULL, even in a column declared NOT NULL. Such tuples will be rare, because new row versions are normally formed with the current descriptor. A BEFORE ROW UPDATE trigger returning OLD is one way to produce one. Fix by deforming the decoded tuples with the descriptor of the source relation, which does have the missing values. Tuples formed with it are still valid for the transient relation, whose attributes are a copy of the source relation ones. Commit 20d3fe9009d took the same approach for INSERT and UPDATE in the executor. Expanding the decoded tuple with heap_expand_tuple() would be the other option, but that is the workaround of commit ba9f18abd that 20d3fe9009d got rid of, so do not bring it back. Add an isolation test. --- src/backend/commands/repack.c | 24 ++++-- src/test/modules/injection_points/Makefile | 1 + .../expected/repack_missingval.out | 46 ++++++++++ src/test/modules/injection_points/meson.build | 1 + .../specs/repack_missingval.spec | 85 +++++++++++++++++++ 5 files changed, 151 insertions(+), 6 deletions(-) create mode 100644 src/test/modules/injection_points/expected/repack_missingval.out create mode 100644 src/test/modules/injection_points/specs/repack_missingval.spec diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 759be53d6b8..4e21c9f80bb 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -109,6 +109,12 @@ typedef struct ChangeContext /* The relation the changes are applied to. */ Relation cc_rel; + /* + * The relation the changes were decoded from. Its descriptor is the one + * to deform the decoded tuples with, see apply_concurrent_changes(). + */ + Relation cc_src_rel; + /* Needed to update indexes of cc_rel. */ ResultRelInfo *cc_rri; EState *cc_estate; @@ -199,6 +205,7 @@ static void process_concurrent_changes(XLogRecPtr end_of_wal, bool done); static void initialize_change_context(ChangeContext *chgcxt, Relation relation, + Relation src_relation, Oid ident_index_id); static void release_change_context(ChangeContext *chgcxt); static void rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, @@ -2688,12 +2695,15 @@ apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt) bool have_old_tuple = false; MemoryContext oldcxt; - spilled_tuple = MakeSingleTupleTableSlot(RelationGetDescr(rel), - &TTSOpsVirtual); + /* + * Deform the decoded tuples with the descriptor of cc_src_rel, which is + * the only one that has the missing values. Tuples formed with it are + * still valid for cc_rel, whose attributes are a copy of cc_src_rel's. + */ + spilled_tuple = MakeSingleTupleTableSlot(RelationGetDescr(chgcxt->cc_src_rel), &TTSOpsVirtual); ondisk_tuple = MakeSingleTupleTableSlot(RelationGetDescr(rel), table_slot_callbacks(rel)); - old_update_tuple = MakeSingleTupleTableSlot(RelationGetDescr(rel), - &TTSOpsVirtual); + old_update_tuple = MakeSingleTupleTableSlot(RelationGetDescr(chgcxt->cc_src_rel), &TTSOpsVirtual); oldcxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(chgcxt->cc_estate)); @@ -3156,9 +3166,11 @@ process_concurrent_changes(XLogRecPtr end_of_wal, ChangeContext *chgcxt, bool do */ static void initialize_change_context(ChangeContext *chgcxt, - Relation relation, Oid ident_index_id) + Relation relation, Relation src_relation, + Oid ident_index_id) { chgcxt->cc_rel = relation; + chgcxt->cc_src_rel = src_relation; /* Only initialize fields needed by ExecInsertIndexTuples(). */ chgcxt->cc_estate = CreateExecutorState(); @@ -3377,7 +3389,7 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, get_rel_name(identIdx)); /* Gather information to apply concurrent changes. */ - initialize_change_context(&chgcxt, NewHeap, ident_idx_new); + initialize_change_context(&chgcxt, NewHeap, OldHeap, ident_idx_new); /* * During testing, wait for another backend to perform concurrent data diff --git a/src/test/modules/injection_points/Makefile b/src/test/modules/injection_points/Makefile index 9d8b4b3540c..bb70049f75d 100644 --- a/src/test/modules/injection_points/Makefile +++ b/src/test/modules/injection_points/Makefile @@ -19,6 +19,7 @@ ISOLATION = basic \ reindex_concurrently_deferred \ repack \ repack_decode \ + repack_missingval \ repack_temporal \ repack_temporal_multirange \ repack_toast \ diff --git a/src/test/modules/injection_points/expected/repack_missingval.out b/src/test/modules/injection_points/expected/repack_missingval.out new file mode 100644 index 00000000000..d51aa616a5c --- /dev/null +++ b/src/test/modules/injection_points/expected/repack_missingval.out @@ -0,0 +1,46 @@ +Parsed test spec with 2 sessions + +starting permutation: s1_wait_before_lock s2_update s2_wakeup_before_lock s1_check +injection_points_attach +----------------------- + +(1 row) + +step s1_wait_before_lock: + REPACK (CONCURRENTLY) repack_test; + <waiting ...> +step s2_update: + UPDATE repack_test SET j = j WHERE i IN (1, 2); + +step s2_wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step s1_wait_before_lock: <... completed> +step s1_check: + SELECT i, j, c, d FROM repack_test ORDER BY i; + + WITH s AS MATERIALIZED (SELECT c, d FROM repack_test) + SELECT count(*) FROM s WHERE c IS NULL OR d IS NULL; + +i|j| c|d +-+-+--+--- +1|1|42|xyz +2|2|42|xyz +3|3|42|xyz +(3 rows) + +count +----- + 0 +(1 row) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/meson.build b/src/test/modules/injection_points/meson.build index 80a09f34d78..7177ad32567 100644 --- a/src/test/modules/injection_points/meson.build +++ b/src/test/modules/injection_points/meson.build @@ -48,6 +48,7 @@ tests += { 'reindex_concurrently_deferred', 'repack', 'repack_decode', + 'repack_missingval', 'repack_temporal', 'repack_temporal_multirange', 'repack_toast', diff --git a/src/test/modules/injection_points/specs/repack_missingval.spec b/src/test/modules/injection_points/specs/repack_missingval.spec new file mode 100644 index 00000000000..efbe4d0b8b4 --- /dev/null +++ b/src/test/modules/injection_points/specs/repack_missingval.spec @@ -0,0 +1,85 @@ +# REPACK (CONCURRENTLY); +# +# Test columns whose values are "missing" from the existing tuples, because +# ALTER TABLE ... ADD COLUMN did not have to rewrite the table. +setup +{ + CREATE EXTENSION IF NOT EXISTS injection_points; + + CREATE TABLE repack_test(i int PRIMARY KEY, j int); + INSERT INTO repack_test(i, j) VALUES (1, 1), (2, 2), (3, 3); + + -- A constant default does not rewrite the table, so the rows above keep + -- their shorter tuples and the values of "c" and "d" are only stored in + -- pg_attribute.attmissingval. Use both a pass-by-value and a + -- pass-by-reference type. + ALTER TABLE repack_test ADD COLUMN c int NOT NULL DEFAULT 42; + ALTER TABLE repack_test ADD COLUMN d text NOT NULL DEFAULT 'xyz'; + + CREATE FUNCTION repack_return_old() RETURNS trigger + LANGUAGE plpgsql AS $$ + BEGIN + RETURN OLD; + END; + $$; + + -- By returning OLD, the trigger makes the new row version reuse the + -- shorter tuple, which is then what logical decoding sees. + CREATE TRIGGER return_old BEFORE UPDATE ON repack_test + FOR EACH ROW EXECUTE FUNCTION repack_return_old(); +} + +teardown +{ + DROP TABLE repack_test; + DROP FUNCTION repack_return_old(); + DROP EXTENSION injection_points; +} + +session s1 +setup +{ + SELECT injection_points_set_local(); + SELECT injection_points_attach('repack-concurrently-before-lock', 'wait'); +} + +# Perform the initial load and wait for s2 to change the data. +step s1_wait_before_lock +{ + REPACK (CONCURRENTLY) repack_test; +} + +# The missing values must have survived the concurrent changes. The second +# query needs the MATERIALIZED CTE because the planner would otherwise use +# attnotnull to answer it without looking at the heap. +step s1_check +{ + SELECT i, j, c, d FROM repack_test ORDER BY i; + + WITH s AS MATERIALIZED (SELECT c, d FROM repack_test) + SELECT count(*) FROM s WHERE c IS NULL OR d IS NULL; +} +teardown +{ + SELECT injection_points_detach('repack-concurrently-before-lock'); +} + +session s2 + +# The trigger returns OLD, so these rows keep the tuples they had before the +# ALTER TABLE ... ADD COLUMN above. +step s2_update +{ + UPDATE repack_test SET j = j WHERE i IN (1, 2); +} +step s2_wakeup_before_lock +{ + SELECT injection_points_wakeup('repack-concurrently-before-lock'); +} + +# Test if the missing values find their way into the repacked table. +permutation + s1_wait_before_lock + s2_update + s2_wakeup_before_lock + s1_check -- 2.50.1
^ permalink raw reply [nested|flat] 9+ messages in thread

* Re: REPACK (CONCURRENTLY) loses missing values of columns added without a rewrite
@ 2026-09-22 18:41  Sami Imseih <samimseih.pg@gmail.com>
  parent: Sami Imseih <samimseih.pg@gmail.com>
  1 sibling, 1 reply; 9+ messages in thread

From: Sami Imseih @ 2026-09-22 18:41 UTC (permalink / raw)
  To: Postgres hackers <pgsql-hackers@lists.postgresql.org>

Hi,

v2- just simplifies the test a bit; otherwise same as v1.


--
Sami Imseih
Amazon Web Services

Attachments:

v2-0001-Fix-REPACK-CONCURRENTLY-for-columns-added-without.patch (application/octet-stream, 9.0K) download From 21b19d9e15e7d2edbf58da9303f30bb0c950bd73 Mon Sep 17 00:00:00 2001 From: Sami Imseih <samimseih.pg@gmail.com> Date: Tue, 22 Sep 2026 18:24:43 +0000 Subject: [PATCH v2 1/1] Fix REPACK (CONCURRENTLY) for columns added without a table rewrite When applying the concurrent data changes, REPACK deformed the decoded tuples with the descriptor of the transient relation. That descriptor has no "missing" values, because make_new_heap() gives the transient relation none of the defaults and constraints of the source relation. A tuple written before an ALTER TABLE ... ADD COLUMN that did not rewrite the table has fewer attributes than the descriptor, so the missing values came out as NULL, even in a column declared NOT NULL. Such tuples will be rare, because new row versions are normally formed with the current descriptor. A BEFORE ROW UPDATE trigger returning OLD is one way to produce one. Fix by deforming the decoded tuples with the descriptor of the source relation, which does have the missing values. Tuples formed with it are still valid for the transient relation, whose attributes are a copy of the source relation ones. Commit 20d3fe9009d took the same approach for INSERT and UPDATE in the executor. Expanding the decoded tuple with heap_expand_tuple() would be the other option, but that is the workaround of commit ba9f18abd that 20d3fe9009d got rid of, so do not bring it back. Add an isolation test. --- src/backend/commands/repack.c | 24 ++++-- src/test/modules/injection_points/Makefile | 1 + .../expected/repack_missingval.out | 38 +++++++++ src/test/modules/injection_points/meson.build | 1 + .../specs/repack_missingval.spec | 79 +++++++++++++++++++ 5 files changed, 137 insertions(+), 6 deletions(-) create mode 100644 src/test/modules/injection_points/expected/repack_missingval.out create mode 100644 src/test/modules/injection_points/specs/repack_missingval.spec diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 759be53d6b8..4e21c9f80bb 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -109,6 +109,12 @@ typedef struct ChangeContext /* The relation the changes are applied to. */ Relation cc_rel; + /* + * The relation the changes were decoded from. Its descriptor is the one + * to deform the decoded tuples with, see apply_concurrent_changes(). + */ + Relation cc_src_rel; + /* Needed to update indexes of cc_rel. */ ResultRelInfo *cc_rri; EState *cc_estate; @@ -199,6 +205,7 @@ static void process_concurrent_changes(XLogRecPtr end_of_wal, bool done); static void initialize_change_context(ChangeContext *chgcxt, Relation relation, + Relation src_relation, Oid ident_index_id); static void release_change_context(ChangeContext *chgcxt); static void rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, @@ -2688,12 +2695,15 @@ apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt) bool have_old_tuple = false; MemoryContext oldcxt; - spilled_tuple = MakeSingleTupleTableSlot(RelationGetDescr(rel), - &TTSOpsVirtual); + /* + * Deform the decoded tuples with the descriptor of cc_src_rel, which is + * the only one that has the missing values. Tuples formed with it are + * still valid for cc_rel, whose attributes are a copy of cc_src_rel's. + */ + spilled_tuple = MakeSingleTupleTableSlot(RelationGetDescr(chgcxt->cc_src_rel), &TTSOpsVirtual); ondisk_tuple = MakeSingleTupleTableSlot(RelationGetDescr(rel), table_slot_callbacks(rel)); - old_update_tuple = MakeSingleTupleTableSlot(RelationGetDescr(rel), - &TTSOpsVirtual); + old_update_tuple = MakeSingleTupleTableSlot(RelationGetDescr(chgcxt->cc_src_rel), &TTSOpsVirtual); oldcxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(chgcxt->cc_estate)); @@ -3156,9 +3166,11 @@ process_concurrent_changes(XLogRecPtr end_of_wal, ChangeContext *chgcxt, bool do */ static void initialize_change_context(ChangeContext *chgcxt, - Relation relation, Oid ident_index_id) + Relation relation, Relation src_relation, + Oid ident_index_id) { chgcxt->cc_rel = relation; + chgcxt->cc_src_rel = src_relation; /* Only initialize fields needed by ExecInsertIndexTuples(). */ chgcxt->cc_estate = CreateExecutorState(); @@ -3377,7 +3389,7 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, get_rel_name(identIdx)); /* Gather information to apply concurrent changes. */ - initialize_change_context(&chgcxt, NewHeap, ident_idx_new); + initialize_change_context(&chgcxt, NewHeap, OldHeap, ident_idx_new); /* * During testing, wait for another backend to perform concurrent data diff --git a/src/test/modules/injection_points/Makefile b/src/test/modules/injection_points/Makefile index 9d8b4b3540c..bb70049f75d 100644 --- a/src/test/modules/injection_points/Makefile +++ b/src/test/modules/injection_points/Makefile @@ -19,6 +19,7 @@ ISOLATION = basic \ reindex_concurrently_deferred \ repack \ repack_decode \ + repack_missingval \ repack_temporal \ repack_temporal_multirange \ repack_toast \ diff --git a/src/test/modules/injection_points/expected/repack_missingval.out b/src/test/modules/injection_points/expected/repack_missingval.out new file mode 100644 index 00000000000..aa67a5544d0 --- /dev/null +++ b/src/test/modules/injection_points/expected/repack_missingval.out @@ -0,0 +1,38 @@ +Parsed test spec with 2 sessions + +starting permutation: s1_wait_before_lock s2_update s2_wakeup_before_lock s1_check +injection_points_attach +----------------------- + +(1 row) + +step s1_wait_before_lock: + REPACK (CONCURRENTLY) repack_test; + <waiting ...> +step s2_update: + UPDATE repack_test SET j = j WHERE i IN (1, 2); + +step s2_wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step s1_wait_before_lock: <... completed> +step s1_check: + SELECT i, j, c, d FROM repack_test ORDER BY i; + +i|j| c|d +-+-+--+--- +1|1|42|xyz +2|2|42|xyz +3|3|42|xyz +(3 rows) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/meson.build b/src/test/modules/injection_points/meson.build index 80a09f34d78..7177ad32567 100644 --- a/src/test/modules/injection_points/meson.build +++ b/src/test/modules/injection_points/meson.build @@ -48,6 +48,7 @@ tests += { 'reindex_concurrently_deferred', 'repack', 'repack_decode', + 'repack_missingval', 'repack_temporal', 'repack_temporal_multirange', 'repack_toast', diff --git a/src/test/modules/injection_points/specs/repack_missingval.spec b/src/test/modules/injection_points/specs/repack_missingval.spec new file mode 100644 index 00000000000..c6146f43d3c --- /dev/null +++ b/src/test/modules/injection_points/specs/repack_missingval.spec @@ -0,0 +1,79 @@ +# REPACK (CONCURRENTLY) +# +# Test columns whose values are "missing" from the existing tuples, because +# ALTER TABLE ... ADD COLUMN did not have to rewrite the table. +setup +{ + CREATE EXTENSION IF NOT EXISTS injection_points; + + CREATE TABLE repack_test(i int PRIMARY KEY, j int); + INSERT INTO repack_test(i, j) VALUES (1, 1), (2, 2), (3, 3); + + -- A constant default does not rewrite the table, so the rows above keep + -- their shorter tuples and the values of "c" and "d" are only stored in + -- pg_attribute.attmissingval. Use both a fixed-length and a + -- variable-length type, because attmissingval stores those two kinds of + -- value differently. + ALTER TABLE repack_test ADD COLUMN c int NOT NULL DEFAULT 42; + ALTER TABLE repack_test ADD COLUMN d text NOT NULL DEFAULT 'xyz'; + + CREATE FUNCTION repack_return_old() RETURNS trigger + LANGUAGE plpgsql AS $$ + BEGIN + RETURN OLD; + END; + $$; + + -- By returning OLD, the trigger makes the new row version reuse the + -- shorter tuple, which is then what logical decoding sees. + CREATE TRIGGER return_old BEFORE UPDATE ON repack_test + FOR EACH ROW EXECUTE FUNCTION repack_return_old(); +} + +teardown +{ + DROP TABLE repack_test; + DROP FUNCTION repack_return_old(); + DROP EXTENSION injection_points; +} + +session s1 +setup +{ + SELECT injection_points_set_local(); + SELECT injection_points_attach('repack-concurrently-before-lock', 'wait'); +} + +# Perform the initial load and wait for s2 to change the data. +step s1_wait_before_lock +{ + REPACK (CONCURRENTLY) repack_test; +} + +# The missing values must have survived the concurrent changes. +step s1_check +{ + SELECT i, j, c, d FROM repack_test ORDER BY i; +} +teardown +{ + SELECT injection_points_detach('repack-concurrently-before-lock'); +} + +session s2 + +# Update two of the three rows, without changing the data. +step s2_update +{ + UPDATE repack_test SET j = j WHERE i IN (1, 2); +} +step s2_wakeup_before_lock +{ + SELECT injection_points_wakeup('repack-concurrently-before-lock'); +} + +permutation + s1_wait_before_lock + s2_update + s2_wakeup_before_lock + s1_check -- 2.50.1
^ permalink raw reply [nested|flat] 9+ messages in thread

* Re: REPACK (CONCURRENTLY) loses missing values of columns added without a rewrite
@ 2026-09-23 04:37  shihao zhong <zhong950419@gmail.com>
  parent: Sami Imseih <samimseih.pg@gmail.com>
  0 siblings, 1 reply; 9+ messages in thread

From: shihao zhong @ 2026-09-23 04:37 UTC (permalink / raw)
  To: Sami Imseih <samimseih.pg@gmail.com>; +Cc: Postgres hackers <pgsql-hackers@lists.postgresql.org>

Hi Sami,

v2 fixes the issue you mentioned.

I think It also fixes another case. If the added column is in the replica
identity index, REPACK looks up the row with a NULL key. That fails the
Assert in find_target_tuple(), or gives "could not find target tuple"
without assertions. Adding this to the test covers it:

    CREATE UNIQUE INDEX repack_test_i_c_idx ON repack_test (i, c);
    ALTER TABLE repack_test REPLICA IDENTITY USING INDEX
repack_test_i_c_idx;

Thanks,
Shihao

^ permalink  raw  reply  [nested|flat] 9+ messages in thread

* Re: REPACK (CONCURRENTLY) loses missing values of columns added without a rewrite
@ 2026-09-23 18:41  Sami Imseih <samimseih.pg@gmail.com>
  parent: shihao zhong <zhong950419@gmail.com>
  0 siblings, 2 replies; 9+ messages in thread

From: Sami Imseih @ 2026-09-23 18:41 UTC (permalink / raw)
  To: shihao zhong <zhong950419@gmail.com>; +Cc: Postgres hackers <pgsql-hackers@lists.postgresql.org>

> v2 fixes the issue you mentioned.

Thanks for checking!

> I think It also fixes another case. If the added column is in the replica
> identity index, REPACK looks up the row with a NULL key. That fails the
> Assert in find_target_tuple(), or gives "could not find target tuple"
> without assertions. Adding this to the test covers it:
>
>     CREATE UNIQUE INDEX repack_test_i_c_idx ON repack_test (i, c);
>     ALTER TABLE repack_test REPLICA IDENTITY USING INDEX repack_test_i_c_idx;

ahh, good repro. It's worse for a pass-by-reference column, i.e. TEXT.
find_target_tuple() only sets sk_argument, never SK_ISNULL, so the
comparison function gets a NULL pointer rather than a NULL key.
So a non assert build will actually segfault.

v3 uses a TEXT column in the identity index, which covers the int case
too since both go through the same sk_argument.

--
Sami Imseih
Amazon Web Services (AWS)

Attachments:

v3-0001-Fix-REPACK-CONCURRENTLY-for-columns-added-without.patch (application/octet-stream, 9.6K) download From 5f5f9042f3099517fa45e0dd69b2075f1d167563 Mon Sep 17 00:00:00 2001 From: Sami Imseih <samimseih.pg@gmail.com> Date: Tue, 22 Sep 2026 18:24:43 +0000 Subject: [PATCH v3 1/1] Fix REPACK (CONCURRENTLY) for columns added without a table rewrite When applying the concurrent data changes, REPACK deformed the decoded tuples with the descriptor of the transient relation. That descriptor has no "missing" values, because make_new_heap() gives the transient relation none of the defaults and constraints of the source relation. A tuple written before an ALTER TABLE ... ADD COLUMN that did not rewrite the table has fewer attributes than the descriptor, so the missing values came out as NULL, even in a column declared NOT NULL. If such a value belongs to the replica identity, the key used to find the target tuple was NULL too, so the tuple could not be found. The scan key does not remember that a value is NULL, so a pass-by-reference key would even crash the comparison function. Such tuples will be rare, because new row versions are normally formed with the current descriptor. A BEFORE ROW UPDATE trigger returning OLD is one way to produce one. Fix by deforming the decoded tuples with the descriptor of the source relation, which does have the missing values. Tuples formed with it are still valid for the transient relation, whose attributes are a copy of the source relation ones. Commit 20d3fe9009d took the same approach for INSERT and UPDATE in the executor. Expanding the decoded tuple with heap_expand_tuple() would be the other option, but that is the workaround of commit ba9f18abd that 20d3fe9009d got rid of, so do not bring it back. Add an isolation test. Reported-by: Shihao Zhong <zhong950419@gmail.com> Discussion: https://postgr.es/m/CAN12+Y+NJwr5EqKVrHpPD=5+b_NRAOzU9fhrVDO3H46x2WRxoA@mail.gmail.com --- src/backend/commands/repack.c | 24 ++++-- src/test/modules/injection_points/Makefile | 1 + .../expected/repack_missingval.out | 38 +++++++++ src/test/modules/injection_points/meson.build | 1 + .../specs/repack_missingval.spec | 83 +++++++++++++++++++ 5 files changed, 141 insertions(+), 6 deletions(-) create mode 100644 src/test/modules/injection_points/expected/repack_missingval.out create mode 100644 src/test/modules/injection_points/specs/repack_missingval.spec diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 759be53d6b8..4e21c9f80bb 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -109,6 +109,12 @@ typedef struct ChangeContext /* The relation the changes are applied to. */ Relation cc_rel; + /* + * The relation the changes were decoded from. Its descriptor is the one + * to deform the decoded tuples with, see apply_concurrent_changes(). + */ + Relation cc_src_rel; + /* Needed to update indexes of cc_rel. */ ResultRelInfo *cc_rri; EState *cc_estate; @@ -199,6 +205,7 @@ static void process_concurrent_changes(XLogRecPtr end_of_wal, bool done); static void initialize_change_context(ChangeContext *chgcxt, Relation relation, + Relation src_relation, Oid ident_index_id); static void release_change_context(ChangeContext *chgcxt); static void rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, @@ -2688,12 +2695,15 @@ apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt) bool have_old_tuple = false; MemoryContext oldcxt; - spilled_tuple = MakeSingleTupleTableSlot(RelationGetDescr(rel), - &TTSOpsVirtual); + /* + * Deform the decoded tuples with the descriptor of cc_src_rel, which is + * the only one that has the missing values. Tuples formed with it are + * still valid for cc_rel, whose attributes are a copy of cc_src_rel's. + */ + spilled_tuple = MakeSingleTupleTableSlot(RelationGetDescr(chgcxt->cc_src_rel), &TTSOpsVirtual); ondisk_tuple = MakeSingleTupleTableSlot(RelationGetDescr(rel), table_slot_callbacks(rel)); - old_update_tuple = MakeSingleTupleTableSlot(RelationGetDescr(rel), - &TTSOpsVirtual); + old_update_tuple = MakeSingleTupleTableSlot(RelationGetDescr(chgcxt->cc_src_rel), &TTSOpsVirtual); oldcxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(chgcxt->cc_estate)); @@ -3156,9 +3166,11 @@ process_concurrent_changes(XLogRecPtr end_of_wal, ChangeContext *chgcxt, bool do */ static void initialize_change_context(ChangeContext *chgcxt, - Relation relation, Oid ident_index_id) + Relation relation, Relation src_relation, + Oid ident_index_id) { chgcxt->cc_rel = relation; + chgcxt->cc_src_rel = src_relation; /* Only initialize fields needed by ExecInsertIndexTuples(). */ chgcxt->cc_estate = CreateExecutorState(); @@ -3377,7 +3389,7 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, get_rel_name(identIdx)); /* Gather information to apply concurrent changes. */ - initialize_change_context(&chgcxt, NewHeap, ident_idx_new); + initialize_change_context(&chgcxt, NewHeap, OldHeap, ident_idx_new); /* * During testing, wait for another backend to perform concurrent data diff --git a/src/test/modules/injection_points/Makefile b/src/test/modules/injection_points/Makefile index 9d8b4b3540c..bb70049f75d 100644 --- a/src/test/modules/injection_points/Makefile +++ b/src/test/modules/injection_points/Makefile @@ -19,6 +19,7 @@ ISOLATION = basic \ reindex_concurrently_deferred \ repack \ repack_decode \ + repack_missingval \ repack_temporal \ repack_temporal_multirange \ repack_toast \ diff --git a/src/test/modules/injection_points/expected/repack_missingval.out b/src/test/modules/injection_points/expected/repack_missingval.out new file mode 100644 index 00000000000..351d76b3cbc --- /dev/null +++ b/src/test/modules/injection_points/expected/repack_missingval.out @@ -0,0 +1,38 @@ +Parsed test spec with 2 sessions + +starting permutation: s1_wait_before_lock s2_update s2_wakeup_before_lock s1_check +injection_points_attach +----------------------- + +(1 row) + +step s1_wait_before_lock: + REPACK (CONCURRENTLY) repack_test; + <waiting ...> +step s2_update: + UPDATE repack_test SET j = j WHERE i IN (1, 2); + +step s2_wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step s1_wait_before_lock: <... completed> +step s1_check: + SELECT i, j, c FROM repack_test ORDER BY i; + +i|j|c +-+-+--- +1|1|xyz +2|2|xyz +3|3|xyz +(3 rows) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/meson.build b/src/test/modules/injection_points/meson.build index 80a09f34d78..7177ad32567 100644 --- a/src/test/modules/injection_points/meson.build +++ b/src/test/modules/injection_points/meson.build @@ -48,6 +48,7 @@ tests += { 'reindex_concurrently_deferred', 'repack', 'repack_decode', + 'repack_missingval', 'repack_temporal', 'repack_temporal_multirange', 'repack_toast', diff --git a/src/test/modules/injection_points/specs/repack_missingval.spec b/src/test/modules/injection_points/specs/repack_missingval.spec new file mode 100644 index 00000000000..95995a2bd97 --- /dev/null +++ b/src/test/modules/injection_points/specs/repack_missingval.spec @@ -0,0 +1,83 @@ +# REPACK (CONCURRENTLY) +# +# Test columns whose values are "missing" from the existing tuples, because +# ALTER TABLE ... ADD COLUMN did not have to rewrite the table. +setup +{ + CREATE EXTENSION IF NOT EXISTS injection_points; + + CREATE TABLE repack_test(i int PRIMARY KEY, j int); + INSERT INTO repack_test(i, j) VALUES (1, 1), (2, 2), (3, 3); + + -- A constant default does not rewrite the table, so the rows above keep + -- their shorter tuples and the value of "c" is only stored in + -- pg_attribute.attmissingval. + ALTER TABLE repack_test ADD COLUMN c text NOT NULL DEFAULT 'xyz'; + + -- With "c" in the replica identity, a missing value is also used as the key + -- to find the target tuple, not only to form the new row version. Use a + -- pass-by-reference type, because a NULL key of that kind can crash the + -- comparison function. + CREATE UNIQUE INDEX repack_test_ident_idx ON repack_test (i, c); + ALTER TABLE repack_test REPLICA IDENTITY USING INDEX repack_test_ident_idx; + + CREATE FUNCTION repack_return_old() RETURNS trigger + LANGUAGE plpgsql AS $$ + BEGIN + RETURN OLD; + END; + $$; + + -- By returning OLD, the trigger makes the new row version reuse the + -- shorter tuple, which is then what logical decoding sees. + CREATE TRIGGER return_old BEFORE UPDATE ON repack_test + FOR EACH ROW EXECUTE FUNCTION repack_return_old(); +} + +teardown +{ + DROP TABLE repack_test; + DROP FUNCTION repack_return_old(); + DROP EXTENSION injection_points; +} + +session s1 +setup +{ + SELECT injection_points_set_local(); + SELECT injection_points_attach('repack-concurrently-before-lock', 'wait'); +} + +# Perform the initial load and wait for s2 to change the data. +step s1_wait_before_lock +{ + REPACK (CONCURRENTLY) repack_test; +} + +# The missing values must have survived the concurrent changes. +step s1_check +{ + SELECT i, j, c FROM repack_test ORDER BY i; +} +teardown +{ + SELECT injection_points_detach('repack-concurrently-before-lock'); +} + +session s2 + +# Update two of the three rows, without changing the data. +step s2_update +{ + UPDATE repack_test SET j = j WHERE i IN (1, 2); +} +step s2_wakeup_before_lock +{ + SELECT injection_points_wakeup('repack-concurrently-before-lock'); +} + +permutation + s1_wait_before_lock + s2_update + s2_wakeup_before_lock + s1_check -- 2.50.1
^ permalink raw reply [nested|flat] 9+ messages in thread

* Re: REPACK (CONCURRENTLY) loses missing values of columns added without a rewrite
@ 2026-09-24 00:52  shihao zhong <zhong950419@gmail.com>
  parent: Sami Imseih <samimseih.pg@gmail.com>
  1 sibling, 0 replies; 9+ messages in thread

From: shihao zhong @ 2026-09-24 00:52 UTC (permalink / raw)
  To: Sami Imseih <samimseih.pg@gmail.com>; +Cc: Postgres hackers <pgsql-hackers@lists.postgresql.org>

Hi Sami,

v3 looks good to me.

Move to RFC state

Thanks,
Shihao

^ permalink  raw  reply  [nested|flat] 9+ messages in thread

* Re: REPACK (CONCURRENTLY) loses missing values of columns added without a rewrite
@ 2026-09-24 12:03  Kirill Reshke <reshkekirill@gmail.com>
  parent: Sami Imseih <samimseih.pg@gmail.com>
  1 sibling, 0 replies; 9+ messages in thread

From: Kirill Reshke @ 2026-09-24 12:03 UTC (permalink / raw)
  To: Sami Imseih <samimseih.pg@gmail.com>; +Cc: shihao zhong <zhong950419@gmail.com>; Postgres hackers <pgsql-hackers@lists.postgresql.org>

On Wed, 23 Sept 2026 at 23:41, Sami Imseih <samimseih.pg@gmail.com> wrote:
>
> > v2 fixes the issue you mentioned.
>
> Thanks for checking!
>
> > I think It also fixes another case. If the added column is in the replica
> > identity index, REPACK looks up the row with a NULL key. That fails the
> > Assert in find_target_tuple(), or gives "could not find target tuple"
> > without assertions. Adding this to the test covers it:
> >
> >     CREATE UNIQUE INDEX repack_test_i_c_idx ON repack_test (i, c);
> >     ALTER TABLE repack_test REPLICA IDENTITY USING INDEX repack_test_i_c_idx;
>
> ahh, good repro. It's worse for a pass-by-reference column, i.e. TEXT.
> find_target_tuple() only sets sk_argument, never SK_ISNULL, so the
> comparison function gets a NULL pointer rather than a NULL key.
> So a non assert build will actually segfault.
>
> v3 uses a TEXT column in the identity index, which covers the int case
> too since both go through the same sk_argument.
>
> --
> Sami Imseih
> Amazon Web Services (AWS)

Hi!
I reproduced this while stress testing REPACK (CONCURRENTLY) on HEAD.
Whats worse, this issue makes the database unrestorable via pg_dump/COPY.

I also checked DROP COLUMN, ALTER TYPE, SET STORAGE, SET COMPRESSION,
SET NOT NULL, ADD/DROP CONSTRAINT NOT VALID/VALIDATE, virtual
generated columns and found no related issue (both with and without
v3).

So patch LGTM


-- 
Best regards,
Kirill Reshke





^ permalink  raw  reply  [nested|flat] 9+ messages in thread

* Re: REPACK (CONCURRENTLY) loses missing values of columns added without a rewrite
@ 2026-09-24 12:18  Álvaro Herrera <alvherre@kurilemu.de>
  parent: Sami Imseih <samimseih.pg@gmail.com>
  1 sibling, 1 reply; 9+ messages in thread

From: Álvaro Herrera @ 2026-09-24 12:18 UTC (permalink / raw)
  To: Sami Imseih <samimseih.pg@gmail.com>; +Cc: Postgres hackers <pgsql-hackers@lists.postgresql.org>

On 2026-Sep-22, Sami Imseih wrote:

> REPACK (CONCURRENTLY) is not correctly accounting for missing values when
> applying decoded changes to the transient relation (NewHeap). This is
> because it is using the NewHeap descriptor, which intentionally has no
> missing values when it is formed in make_new_heap().

Hah, interesting, thanks.

I wonder why in your fix we keep a pointer to the whole relation instead
of just to its tupledesc.  What about the attached v4?

I considered using CreateTupleDescCopyConstr, but it seems pointless:
the Relation pointer cannot go away while repack is running anyway.  I
ran your test with only CreateTupleDescCopy() to see how would your new
test would fail (because such a descriptor wouldn't have the missing
attrs), but it failed differently, because attnotnull is not set.
Anyway, this was just a perhaps pointless experiment.

-- 
Álvaro Herrera               48°01'N 7°57'E  —  https://www.EnterpriseDB.com/
"Los cuentos de hadas no dan al niño su primera idea sobre los monstruos.
Lo que le dan es su primera idea de la posible derrota del monstruo."
                                                   (G. K. Chesterton)

Attachments:

v4-0001-Fix-REPACK-CONCURRENTLY-for-columns-added-without.patch (text/x-diff, 9.7K) download From 3775be2f017889e2766b8b5b61ca240288f7da31 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81lvaro=20Herrera?= <alvherre@kurilemu.de> Date: Thu, 24 Sep 2026 14:10:14 +0200 Subject: [PATCH v4] Fix REPACK (CONCURRENTLY) for columns added without a table rewrite When applying the concurrent data changes, REPACK deformed the decoded tuples with the descriptor of the transient relation. That descriptor has no "missing" values, because make_new_heap() gives the transient relation none of the defaults and constraints of the source relation. A tuple written before an ALTER TABLE ... ADD COLUMN that did not rewrite the table has fewer attributes than the descriptor, so the missing values came out as NULL, even in a column declared NOT NULL. If such a value belongs to the replica identity, the key used to find the target tuple was NULL too, so the tuple could not be found. The scan key does not remember that a value is NULL, so a pass-by-reference key would even crash the comparison function. Such tuples will be rare, because new row versions are normally formed with the current descriptor. A BEFORE ROW UPDATE trigger returning OLD is one way to produce one. Fix by deforming the decoded tuples with the descriptor of the source relation, which does have the missing values. Tuples formed with it are still valid for the transient relation, whose attributes are a copy of the source relation ones. Commit 20d3fe9009d took the same approach for INSERT and UPDATE in the executor. Expanding the decoded tuple with heap_expand_tuple() would be the other option, but that is the workaround of commit ba9f18abd that 20d3fe9009d got rid of, so do not bring it back. Add an isolation test. Author: Sami Imseih <samimseih.pg@gmail.com> Reported-by: Shihao Zhong <zhong950419@gmail.com> Reviewed-by: Kirill Reshke <reshkekirill@gmail.com> Backpatch-through: 19 Discussion: https://postgr.es/m/CAN12+Y+NJwr5EqKVrHpPD=5+b_NRAOzU9fhrVDO3H46x2WRxoA@mail.gmail.com --- src/backend/commands/repack.c | 23 +++-- src/test/modules/injection_points/Makefile | 1 + .../expected/repack_missingval.out | 38 +++++++++ src/test/modules/injection_points/meson.build | 1 + .../specs/repack_missingval.spec | 83 +++++++++++++++++++ 5 files changed, 140 insertions(+), 6 deletions(-) create mode 100644 src/test/modules/injection_points/expected/repack_missingval.out create mode 100644 src/test/modules/injection_points/specs/repack_missingval.spec diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 759be53d6b8..8a4dc63f37a 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -109,6 +109,9 @@ typedef struct ChangeContext /* The relation the changes are applied to. */ Relation cc_rel; + /* The tuple descriptor to deform decoded tuples with */ + TupleDesc cc_tupdesc; + /* Needed to update indexes of cc_rel. */ ResultRelInfo *cc_rri; EState *cc_estate; @@ -199,6 +202,7 @@ static void process_concurrent_changes(XLogRecPtr end_of_wal, bool done); static void initialize_change_context(ChangeContext *chgcxt, Relation relation, + Relation src_relation, Oid ident_index_id); static void release_change_context(ChangeContext *chgcxt); static void rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, @@ -2688,12 +2692,10 @@ apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt) bool have_old_tuple = false; MemoryContext oldcxt; - spilled_tuple = MakeSingleTupleTableSlot(RelationGetDescr(rel), - &TTSOpsVirtual); + spilled_tuple = MakeSingleTupleTableSlot(chgcxt->cc_tupdesc, &TTSOpsVirtual); ondisk_tuple = MakeSingleTupleTableSlot(RelationGetDescr(rel), table_slot_callbacks(rel)); - old_update_tuple = MakeSingleTupleTableSlot(RelationGetDescr(rel), - &TTSOpsVirtual); + old_update_tuple = MakeSingleTupleTableSlot(chgcxt->cc_tupdesc, &TTSOpsVirtual); oldcxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(chgcxt->cc_estate)); @@ -3156,10 +3158,19 @@ process_concurrent_changes(XLogRecPtr end_of_wal, ChangeContext *chgcxt, bool do */ static void initialize_change_context(ChangeContext *chgcxt, - Relation relation, Oid ident_index_id) + Relation relation, Relation src_relation, + Oid ident_index_id) { chgcxt->cc_rel = relation; + /* + * Use the descriptor of the source relation as the one to deform the + * decoded tuples with; in particular, this descriptor contains all the + * missing attributes. Tuples formed with it are also valid for the target + * relation, as the attributes are otherwise identical. + */ + chgcxt->cc_tupdesc = RelationGetDescr(src_relation); + /* Only initialize fields needed by ExecInsertIndexTuples(). */ chgcxt->cc_estate = CreateExecutorState(); @@ -3377,7 +3388,7 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, get_rel_name(identIdx)); /* Gather information to apply concurrent changes. */ - initialize_change_context(&chgcxt, NewHeap, ident_idx_new); + initialize_change_context(&chgcxt, NewHeap, OldHeap, ident_idx_new); /* * During testing, wait for another backend to perform concurrent data diff --git a/src/test/modules/injection_points/Makefile b/src/test/modules/injection_points/Makefile index 1c680abf7dd..136f0f77951 100644 --- a/src/test/modules/injection_points/Makefile +++ b/src/test/modules/injection_points/Makefile @@ -20,6 +20,7 @@ ISOLATION = basic \ repack \ repack_commit_race \ repack_decode \ + repack_missingval \ repack_temporal \ repack_temporal_multirange \ repack_toast \ diff --git a/src/test/modules/injection_points/expected/repack_missingval.out b/src/test/modules/injection_points/expected/repack_missingval.out new file mode 100644 index 00000000000..351d76b3cbc --- /dev/null +++ b/src/test/modules/injection_points/expected/repack_missingval.out @@ -0,0 +1,38 @@ +Parsed test spec with 2 sessions + +starting permutation: s1_wait_before_lock s2_update s2_wakeup_before_lock s1_check +injection_points_attach +----------------------- + +(1 row) + +step s1_wait_before_lock: + REPACK (CONCURRENTLY) repack_test; + <waiting ...> +step s2_update: + UPDATE repack_test SET j = j WHERE i IN (1, 2); + +step s2_wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step s1_wait_before_lock: <... completed> +step s1_check: + SELECT i, j, c FROM repack_test ORDER BY i; + +i|j|c +-+-+--- +1|1|xyz +2|2|xyz +3|3|xyz +(3 rows) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/meson.build b/src/test/modules/injection_points/meson.build index 45117b6ffec..db6b93a8115 100644 --- a/src/test/modules/injection_points/meson.build +++ b/src/test/modules/injection_points/meson.build @@ -49,6 +49,7 @@ tests += { 'repack', 'repack_commit_race', 'repack_decode', + 'repack_missingval', 'repack_temporal', 'repack_temporal_multirange', 'repack_toast', diff --git a/src/test/modules/injection_points/specs/repack_missingval.spec b/src/test/modules/injection_points/specs/repack_missingval.spec new file mode 100644 index 00000000000..95995a2bd97 --- /dev/null +++ b/src/test/modules/injection_points/specs/repack_missingval.spec @@ -0,0 +1,83 @@ +# REPACK (CONCURRENTLY) +# +# Test columns whose values are "missing" from the existing tuples, because +# ALTER TABLE ... ADD COLUMN did not have to rewrite the table. +setup +{ + CREATE EXTENSION IF NOT EXISTS injection_points; + + CREATE TABLE repack_test(i int PRIMARY KEY, j int); + INSERT INTO repack_test(i, j) VALUES (1, 1), (2, 2), (3, 3); + + -- A constant default does not rewrite the table, so the rows above keep + -- their shorter tuples and the value of "c" is only stored in + -- pg_attribute.attmissingval. + ALTER TABLE repack_test ADD COLUMN c text NOT NULL DEFAULT 'xyz'; + + -- With "c" in the replica identity, a missing value is also used as the key + -- to find the target tuple, not only to form the new row version. Use a + -- pass-by-reference type, because a NULL key of that kind can crash the + -- comparison function. + CREATE UNIQUE INDEX repack_test_ident_idx ON repack_test (i, c); + ALTER TABLE repack_test REPLICA IDENTITY USING INDEX repack_test_ident_idx; + + CREATE FUNCTION repack_return_old() RETURNS trigger + LANGUAGE plpgsql AS $$ + BEGIN + RETURN OLD; + END; + $$; + + -- By returning OLD, the trigger makes the new row version reuse the + -- shorter tuple, which is then what logical decoding sees. + CREATE TRIGGER return_old BEFORE UPDATE ON repack_test + FOR EACH ROW EXECUTE FUNCTION repack_return_old(); +} + +teardown +{ + DROP TABLE repack_test; + DROP FUNCTION repack_return_old(); + DROP EXTENSION injection_points; +} + +session s1 +setup +{ + SELECT injection_points_set_local(); + SELECT injection_points_attach('repack-concurrently-before-lock', 'wait'); +} + +# Perform the initial load and wait for s2 to change the data. +step s1_wait_before_lock +{ + REPACK (CONCURRENTLY) repack_test; +} + +# The missing values must have survived the concurrent changes. +step s1_check +{ + SELECT i, j, c FROM repack_test ORDER BY i; +} +teardown +{ + SELECT injection_points_detach('repack-concurrently-before-lock'); +} + +session s2 + +# Update two of the three rows, without changing the data. +step s2_update +{ + UPDATE repack_test SET j = j WHERE i IN (1, 2); +} +step s2_wakeup_before_lock +{ + SELECT injection_points_wakeup('repack-concurrently-before-lock'); +} + +permutation + s1_wait_before_lock + s2_update + s2_wakeup_before_lock + s1_check -- 2.47.3
^ permalink raw reply [nested|flat] 9+ messages in thread

* Re: REPACK (CONCURRENTLY) loses missing values of columns added without a rewrite
@ 2026-09-24 14:43  Sami Imseih <samimseih.pg@gmail.com>
  parent: Álvaro Herrera <alvherre@kurilemu.de>
  0 siblings, 1 reply; 9+ messages in thread

From: Sami Imseih @ 2026-09-24 14:43 UTC (permalink / raw)
  To: Álvaro Herrera <alvherre@kurilemu.de>; +Cc: Postgres hackers <pgsql-hackers@lists.postgresql.org>

Thanks!

> I wonder why in your fix we keep a pointer to the whole relation instead
> of just to its tupledesc.  What about the attached v4?

It was expedient. The tupledesc is all we need, so v4 is better. This LGTM.

> I ran your test with only CreateTupleDescCopy() to see how would your new
> test would fail (because such a descriptor wouldn't have the missing
> attrs), but it failed differently, because attnotnull is not set.
> Anyway, this was just a perhaps pointless experiment.

Thanks for checking.  Right, CreateTupleDescCopy() would just reintroduce
the problem we're fixing.

v5 attached fixes indentation.

--
Sami Imseih
Amazon Web Services (AWS)

Attachments:

v5-0001-Fix-REPACK-CONCURRENTLY-for-columns-added-without.patch (application/octet-stream, 9.7K) download From 351ebf1d1a84df63241dde1da06b349a6beff576 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81lvaro=20Herrera?= <alvherre@kurilemu.de> Date: Thu, 24 Sep 2026 14:10:14 +0200 Subject: [PATCH v5 1/1] Fix REPACK (CONCURRENTLY) for columns added without a table rewrite When applying the concurrent data changes, REPACK deformed the decoded tuples with the descriptor of the transient relation. That descriptor has no "missing" values, because make_new_heap() gives the transient relation none of the defaults and constraints of the source relation. A tuple written before an ALTER TABLE ... ADD COLUMN that did not rewrite the table has fewer attributes than the descriptor, so the missing values came out as NULL, even in a column declared NOT NULL. If such a value belongs to the replica identity, the key used to find the target tuple was NULL too, so the tuple could not be found. The scan key does not remember that a value is NULL, so a pass-by-reference key would even crash the comparison function. Such tuples will be rare, because new row versions are normally formed with the current descriptor. A BEFORE ROW UPDATE trigger returning OLD is one way to produce one. Fix by deforming the decoded tuples with the descriptor of the source relation, which does have the missing values. Tuples formed with it are still valid for the transient relation, whose attributes are a copy of the source relation ones. Commit 20d3fe9009d took the same approach for INSERT and UPDATE in the executor. Expanding the decoded tuple with heap_expand_tuple() would be the other option, but that is the workaround of commit ba9f18abd that 20d3fe9009d got rid of, so do not bring it back. Add an isolation test. Author: Sami Imseih <samimseih.pg@gmail.com> Reported-by: Shihao Zhong <zhong950419@gmail.com> Reviewed-by: Kirill Reshke <reshkekirill@gmail.com> Backpatch-through: 19 Discussion: https://postgr.es/m/CAN12+Y+NJwr5EqKVrHpPD=5+b_NRAOzU9fhrVDO3H46x2WRxoA@mail.gmail.com --- src/backend/commands/repack.c | 23 +++-- src/test/modules/injection_points/Makefile | 1 + .../expected/repack_missingval.out | 38 +++++++++ src/test/modules/injection_points/meson.build | 1 + .../specs/repack_missingval.spec | 83 +++++++++++++++++++ 5 files changed, 140 insertions(+), 6 deletions(-) create mode 100644 src/test/modules/injection_points/expected/repack_missingval.out create mode 100644 src/test/modules/injection_points/specs/repack_missingval.spec diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c index 759be53d6b8..f5a32e06cd0 100644 --- a/src/backend/commands/repack.c +++ b/src/backend/commands/repack.c @@ -109,6 +109,9 @@ typedef struct ChangeContext /* The relation the changes are applied to. */ Relation cc_rel; + /* The tuple descriptor to deform decoded tuples with */ + TupleDesc cc_tupdesc; + /* Needed to update indexes of cc_rel. */ ResultRelInfo *cc_rri; EState *cc_estate; @@ -199,6 +202,7 @@ static void process_concurrent_changes(XLogRecPtr end_of_wal, bool done); static void initialize_change_context(ChangeContext *chgcxt, Relation relation, + Relation src_relation, Oid ident_index_id); static void release_change_context(ChangeContext *chgcxt); static void rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, @@ -2688,12 +2692,10 @@ apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt) bool have_old_tuple = false; MemoryContext oldcxt; - spilled_tuple = MakeSingleTupleTableSlot(RelationGetDescr(rel), - &TTSOpsVirtual); + spilled_tuple = MakeSingleTupleTableSlot(chgcxt->cc_tupdesc, &TTSOpsVirtual); ondisk_tuple = MakeSingleTupleTableSlot(RelationGetDescr(rel), table_slot_callbacks(rel)); - old_update_tuple = MakeSingleTupleTableSlot(RelationGetDescr(rel), - &TTSOpsVirtual); + old_update_tuple = MakeSingleTupleTableSlot(chgcxt->cc_tupdesc, &TTSOpsVirtual); oldcxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(chgcxt->cc_estate)); @@ -3156,10 +3158,19 @@ process_concurrent_changes(XLogRecPtr end_of_wal, ChangeContext *chgcxt, bool do */ static void initialize_change_context(ChangeContext *chgcxt, - Relation relation, Oid ident_index_id) + Relation relation, Relation src_relation, + Oid ident_index_id) { chgcxt->cc_rel = relation; + /* + * Use the descriptor of the source relation as the one to deform the + * decoded tuples with; in particular, this descriptor contains all the + * missing attributes. Tuples formed with it are also valid for the + * target relation, as the attributes are otherwise identical. + */ + chgcxt->cc_tupdesc = RelationGetDescr(src_relation); + /* Only initialize fields needed by ExecInsertIndexTuples(). */ chgcxt->cc_estate = CreateExecutorState(); @@ -3377,7 +3388,7 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap, get_rel_name(identIdx)); /* Gather information to apply concurrent changes. */ - initialize_change_context(&chgcxt, NewHeap, ident_idx_new); + initialize_change_context(&chgcxt, NewHeap, OldHeap, ident_idx_new); /* * During testing, wait for another backend to perform concurrent data diff --git a/src/test/modules/injection_points/Makefile b/src/test/modules/injection_points/Makefile index 1c680abf7dd..136f0f77951 100644 --- a/src/test/modules/injection_points/Makefile +++ b/src/test/modules/injection_points/Makefile @@ -20,6 +20,7 @@ ISOLATION = basic \ repack \ repack_commit_race \ repack_decode \ + repack_missingval \ repack_temporal \ repack_temporal_multirange \ repack_toast \ diff --git a/src/test/modules/injection_points/expected/repack_missingval.out b/src/test/modules/injection_points/expected/repack_missingval.out new file mode 100644 index 00000000000..351d76b3cbc --- /dev/null +++ b/src/test/modules/injection_points/expected/repack_missingval.out @@ -0,0 +1,38 @@ +Parsed test spec with 2 sessions + +starting permutation: s1_wait_before_lock s2_update s2_wakeup_before_lock s1_check +injection_points_attach +----------------------- + +(1 row) + +step s1_wait_before_lock: + REPACK (CONCURRENTLY) repack_test; + <waiting ...> +step s2_update: + UPDATE repack_test SET j = j WHERE i IN (1, 2); + +step s2_wakeup_before_lock: + SELECT injection_points_wakeup('repack-concurrently-before-lock'); + +injection_points_wakeup +----------------------- + +(1 row) + +step s1_wait_before_lock: <... completed> +step s1_check: + SELECT i, j, c FROM repack_test ORDER BY i; + +i|j|c +-+-+--- +1|1|xyz +2|2|xyz +3|3|xyz +(3 rows) + +injection_points_detach +----------------------- + +(1 row) + diff --git a/src/test/modules/injection_points/meson.build b/src/test/modules/injection_points/meson.build index 45117b6ffec..db6b93a8115 100644 --- a/src/test/modules/injection_points/meson.build +++ b/src/test/modules/injection_points/meson.build @@ -49,6 +49,7 @@ tests += { 'repack', 'repack_commit_race', 'repack_decode', + 'repack_missingval', 'repack_temporal', 'repack_temporal_multirange', 'repack_toast', diff --git a/src/test/modules/injection_points/specs/repack_missingval.spec b/src/test/modules/injection_points/specs/repack_missingval.spec new file mode 100644 index 00000000000..95995a2bd97 --- /dev/null +++ b/src/test/modules/injection_points/specs/repack_missingval.spec @@ -0,0 +1,83 @@ +# REPACK (CONCURRENTLY) +# +# Test columns whose values are "missing" from the existing tuples, because +# ALTER TABLE ... ADD COLUMN did not have to rewrite the table. +setup +{ + CREATE EXTENSION IF NOT EXISTS injection_points; + + CREATE TABLE repack_test(i int PRIMARY KEY, j int); + INSERT INTO repack_test(i, j) VALUES (1, 1), (2, 2), (3, 3); + + -- A constant default does not rewrite the table, so the rows above keep + -- their shorter tuples and the value of "c" is only stored in + -- pg_attribute.attmissingval. + ALTER TABLE repack_test ADD COLUMN c text NOT NULL DEFAULT 'xyz'; + + -- With "c" in the replica identity, a missing value is also used as the key + -- to find the target tuple, not only to form the new row version. Use a + -- pass-by-reference type, because a NULL key of that kind can crash the + -- comparison function. + CREATE UNIQUE INDEX repack_test_ident_idx ON repack_test (i, c); + ALTER TABLE repack_test REPLICA IDENTITY USING INDEX repack_test_ident_idx; + + CREATE FUNCTION repack_return_old() RETURNS trigger + LANGUAGE plpgsql AS $$ + BEGIN + RETURN OLD; + END; + $$; + + -- By returning OLD, the trigger makes the new row version reuse the + -- shorter tuple, which is then what logical decoding sees. + CREATE TRIGGER return_old BEFORE UPDATE ON repack_test + FOR EACH ROW EXECUTE FUNCTION repack_return_old(); +} + +teardown +{ + DROP TABLE repack_test; + DROP FUNCTION repack_return_old(); + DROP EXTENSION injection_points; +} + +session s1 +setup +{ + SELECT injection_points_set_local(); + SELECT injection_points_attach('repack-concurrently-before-lock', 'wait'); +} + +# Perform the initial load and wait for s2 to change the data. +step s1_wait_before_lock +{ + REPACK (CONCURRENTLY) repack_test; +} + +# The missing values must have survived the concurrent changes. +step s1_check +{ + SELECT i, j, c FROM repack_test ORDER BY i; +} +teardown +{ + SELECT injection_points_detach('repack-concurrently-before-lock'); +} + +session s2 + +# Update two of the three rows, without changing the data. +step s2_update +{ + UPDATE repack_test SET j = j WHERE i IN (1, 2); +} +step s2_wakeup_before_lock +{ + SELECT injection_points_wakeup('repack-concurrently-before-lock'); +} + +permutation + s1_wait_before_lock + s2_update + s2_wakeup_before_lock + s1_check -- 2.50.1
^ permalink raw reply [nested|flat] 9+ messages in thread

* Re: REPACK (CONCURRENTLY) loses missing values of columns added without a rewrite
@ 2026-09-25 12:13  Álvaro Herrera <alvherre@kurilemu.de>
  parent: Sami Imseih <samimseih.pg@gmail.com>
  0 siblings, 0 replies; 9+ messages in thread

From: Álvaro Herrera @ 2026-09-25 12:13 UTC (permalink / raw)
  To: Sami Imseih <samimseih.pg@gmail.com>; +Cc: Postgres hackers <pgsql-hackers@lists.postgresql.org>

Thank you!  I have pushed this with some other cosmetic changes --
in particular I added comments in a bunch of places to clarify the role
of the Relation entries being used and which descriptors we use for
each.

-- 
Álvaro Herrera         PostgreSQL Developer  —  https://www.EnterpriseDB.com/
"La virtud es el justo medio entre dos defectos" (Aristóteles)






^ permalink  raw  reply  [nested|flat] 9+ messages in thread


end of thread, other threads:[~2026-09-25 12:13 UTC | newest]

Thread overview: 9+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2026-09-22 18:01 REPACK (CONCURRENTLY) loses missing values of columns added without a rewrite Sami Imseih <samimseih.pg@gmail.com>
2026-09-22 18:41 ` Sami Imseih <samimseih.pg@gmail.com>
2026-09-23 04:37   ` shihao zhong <zhong950419@gmail.com>
2026-09-23 18:41     ` Sami Imseih <samimseih.pg@gmail.com>
2026-09-24 00:52       ` shihao zhong <zhong950419@gmail.com>
2026-09-24 12:03       ` Kirill Reshke <reshkekirill@gmail.com>
2026-09-24 12:18 ` Álvaro Herrera <alvherre@kurilemu.de>
2026-09-24 14:43   ` Sami Imseih <samimseih.pg@gmail.com>
2026-09-25 12:13     ` Álvaro Herrera <alvherre@kurilemu.de>

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