REPACK (CONCURRENTLY) can silently lose updates when the toast table is rewritten

Поиск
Список
Период
Сортировка
Искать

REPACK (CONCURRENTLY) can silently lose updates when the toast table is rewritten

От:
Thom Brown <thom@linux.com>
Дата:
Hi,

Whilst stress-testing REPACK (CONCURRENTLY) I managed to get it to silently
throw away committed updates to a TOASTed column.  There's no error, and both
verify_heapam() and bt_index_check() seem to think everything is fine.

I had claude analyse what's going on and:
-------
It happens at the very start of REPACK. The decoding worker grabs the
toast relation's relfilenode in repack_setup_logical_decoding() and immediately
lets go of the lock, but the backend doesn't lock the toast table until
copy_table_data(). In between sits get_initial_snapshot(), which waits for all
running XIDs to finish, so an open transaction widens the gap nicely.  During
that gap you can rewrite the toast table by name (VACUUM FULL / REPACK /
CLUSTER of it) and give it a fresh relfilenode - the parent is only held with
ShareUpdateExclusiveLock, so that's allowed.
-------

Reproducible steps:

-- session A: hold a transaction open so REPACK blocks building its snapshot
BEGIN;
SELECT pg_current_xact_id();

-- session B: set up, arm the one stock injection point, then REPACK (blocks)
CREATE TABLE test (id int PRIMARY KEY, big text);
ALTER TABLE test ALTER COLUMN big SET STORAGE EXTERNAL;
INSERT INTO test SELECT g, repeat('old', 3000) FROM generate_series(1,3) g;
SELECT injection_points_attach('repack-concurrently-before-lock', 'wait');
REPACK (CONCURRENTLY) test;

-- session C: rewrite the toast table in the gap, then let A commit
VACUUM FULL pg_toast.pg_toast_;

-- session A:
COMMIT;

-- session C: update the toasted rows
UPDATE test SET big = repeat('NEW', 4000) WHERE id IN (1,2,3);

SELECT id, left(big,9) AS val, length(big) FROM test ORDER BY id;
 id |    val    | length
----+-----------+--------
  1 | NEWNEWNEW |  12000
  2 | NEWNEWNEW |  12000
  3 | NEWNEWNEW |  12000

-- session C: let REPACK finish, then look again
SELECT injection_points_wakeup('repack-concurrently-before-lock');

SELECT id, left(big,9) AS val, length(big) FROM test ORDER BY id;
 id |    val    | length
----+-----------+--------
  1 | oldoldold |   9000
  2 | oldoldold |   9000
  3 | oldoldold |   9000

SELECT * FROM verify_heapam('t', check_toast => true);   -- 0 rows
SELECT bt_index_check('t_pkey', heapallindexed => true); -- passes

So three committed updates have quietly reverted to their old values.

Regards

Thom


Re: REPACK (CONCURRENTLY) can silently lose updates when the toast table is rewritten

От:
Manu <manuelreyesbravo@gmail.com>
Дата:
Вложения:
Hi Thom,

Reproduced here on master (07c73f45063), Linux, following your recipe
exactly: the three rows read NEWNEWNEW/12000 before REPACK finishes and
oldoldold/9000 after it, no error anywhere.

One thing worth adding, because it changes how this reads: the
injection point is not needed.

It makes the race deterministic, but the window your analysis describes
- between repack_setup_logical_decoding() taking the toast relfilenode
and copy_table_data() locking the toast table - is wide enough on its
own, because get_initial_snapshot() sits in it waiting for running
XIDs. An ordinary open transaction is enough to hold it open. Without
any injection point:

  session A   BEGIN; SELECT pg_current_xact_id(); (sleeps 3s, commits)
  session B   REPACK (CONCURRENTLY) test;   -- waits for A
  session C   VACUUM FULL pg_toast.pg_toast_;   -- inside the gap
  session C   UPDATE test SET big = ... ;   -- right after A commits

  5 of 5 runs lost the update.

Script attached; it builds and drops the table on each iteration so the
result is not an artifact of one particular relfilenode.

So this does not need a debug build or a test-only feature to happen.
It needs a long-running transaction, a REPACK (CONCURRENTLY), and
someone rewriting that table's toast relation in the meantime - which
is an odd thing to do by hand, but it is allowed, the parent is only
held with ShareUpdateExclusiveLock as you say, and "run VACUUM FULL on
the biggest toast tables" is the kind of thing maintenance scripts do.

I have not looked for a fix yet. From your description the obvious
question is whether repack_setup_logical_decoding() should hold the
toast lock until copy_table_data() takes it, or whether the relfilenode
should be re-checked after the snapshot is built; the second sounds
cheaper but I have not read enough of that path to have an opinion
worth posting.

Regards,
Manu

Re: REPACK (CONCURRENTLY) can silently lose updates when the toast table is rewritten

От:
shihao zhong <zhong950419@gmail.com>
Дата:
Вложения:
> or whether the relfilenode should be re-checked after the snapshot is built

Holding the toast lock from the start deadlocks. A session that asks for
AccessExclusiveLock gets an XID before it waits, and the decoding worker
waits for all XIDs while it sets up.

So the attached patch re-checks instead. Once the worker is set up it no
longer waits for anyone, so the backend locks the toast table there and
compares its relfilenode with the one the worker uses. If they differ, it
starts a new worker. Nothing has been copied yet, so REPACK just carries on.

0002 adds a test to repack_toast.spec that fails without 0001. 

optional.
Thanks,
Shihao

Re: REPACK (CONCURRENTLY) can silently lose updates when the toast table is rewritten

От:
Thom Brown <thom@linux.com>
Дата:
On Wed, 23 Sept 2026 at 06:10, shihao zhong  wrote:
>
> > or whether the relfilenode should be re-checked after the snapshot is built
>
> Holding the toast lock from the start deadlocks. A session that asks for
> AccessExclusiveLock gets an XID before it waits, and the decoding worker
> waits for all XIDs while it sets up.
>
> So the attached patch re-checks instead. Once the worker is set up it no
> longer waits for anyone, so the backend locks the toast table there and
> compares its relfilenode with the one the worker uses. If they differ, it
> starts a new worker. Nothing has been copied yet, so REPACK just carries on.
>
> 0002 adds a test to repack_toast.spec that fails without 0001.

Thanks guys.

I've tested your patches, and I can't reproduce the issue with them
applied. The test on its own fails successfully.

I do have a question relating to this:

+ UnlockRelationOid(toastrelid, ShareUpdateExclusiveLock);
+ stop_repack_decoding_worker();

Is there any opportunity for another rewrite to sneak in between these two?

Thom


Re: REPACK (CONCURRENTLY) can silently lose updates when the toast table is rewritten

От:
shihao zhong <zhong950419@gmail.com>
Дата:
> + UnlockRelationOid(toastrelid, ShareUpdateExclusiveLock);
> + stop_repack_decoding_worker();
>
> Is there any opportunity for another rewrite to sneak in between these two?

Yes, but it doesn't matter. The old worker is thrown away and nothing has
been copied yet. The new worker reads the relfilenode itself when it
starts, so a rewrite before that is simply what it sees. A rewrite after
that is caught by the next check, which is made under the lock again.

The unlock has to come before starting the new worker anyway, or we are back to the deadlock.

Thanks,
Shihao

Re: REPACK (CONCURRENTLY) can silently lose updates when the toast table is rewritten

От:
Manu <manuelreyesbravo@gmail.com>
Дата:
Вложения:
Hi Shihao,

I tested v1-0001 and v1-0002 on master (cff329240ba), two builds from
the same commit with --enable-cassert --enable-injection-points: one
with only 0002 applied (control) and one with both.  0001 builds with
no new warnings.

1. The race

The script I posted earlier wins the race without an injection point,
so it is a fair before/after check.  Same script, same parameters,
against both builds:

  master, 0002 only:   5 of 5 runs lost the update
  master + 0001:       0 of 5 runs lost the update

2. The test

Thom already reported that the test fails without the fix; this only
adds that it fails for the right reason and nothing else moved:

  control:  repack_toast FAILS (results differ from expected)
  0001:     repack_toast passes, 499 ms

The other tests of the injection_points module pass in both builds, so
0002 fails only for the reason it is meant to.

3. The window Thom asked about

> > Is there any opportunity for another rewrite to sneak in between
> > these two?
>
> Yes, but it doesn't matter. The old worker is thrown away and nothing
> has been copied yet. The new worker reads the relfilenode itself when
> it starts, so a rewrite before that is simply what it sees. A rewrite
> after that is caught by the next check, which is made under the lock
> again.

That is the claim I could put under load instead of taking it on
trust.  A loop of VACUUM FULL on the toast relation runs for the whole
startup of REPACK, so it lands inside that window many times over,
while an open transaction keeps the worker waiting during setup and an
UPDATE of the TOASTed columns commits right after.  With
log_min_messages=debug1 the patch's own DEBUG1 counts the restarts:

  hammer 0s:    REPACK ended in ~4s,   0 restarts,   value correct
  hammer 8s:    REPACK ended in ~4s,   33 restarts,  value correct
  hammer 20s:   REPACK ended in ~20s,  166 restarts, value correct
  hammer 40s:   REPACK ended in ~40s,  342 restarts, value correct
  master, 20s:  REPACK ended in ~5s,   n/a,          UPDATE LOST

So it holds up under continuous pressure: the value is never wrong, no
deadlock, and the run with no rewrites at all costs nothing (4s, zero
restarts), so the retry loop does not show up on the normal path.

4. One thing worth deciding, not a correctness issue

The numbers above also say that REPACK can be held up for as long as
the rewriting lasts.  It is not a hard livelock - with the 8s hammer
it got through in 4s - but with the 20s and the 40s one it finished
only about when the hammer stopped, at roughly 8 restarts per second.
Whether it gets through is a matter of winning the window; the loop
has no cap and no backoff, and each turn starts a worker that waits
for all running transactions again.

I would not call this a bug: correct-but-waiting beats fast-and-wrong,
and a VACUUM FULL loop on a toast relation is not a real workload.  But
it is unbounded, and the caller gets no hint of why nothing is
happening.  Since 0001 already has the DEBUG1, would it be worth
raising it, or capping the retries and erroring out after N?  Your
call - I mention it because the measurement was there.

Script attached (.txt, so the cfbot keeps testing your patches).

Regards,
Manu

Re: REPACK (CONCURRENTLY) can silently lose updates when the toast table is rewritten

От:
Melanie Plageman <melanieplageman@gmail.com>
Дата:
On Tue, Sep 22, 2026 at 8:23 PM Thom Brown  wrote:
>
> Whilst stress-testing REPACK (CONCURRENTLY) I managed to get it to silently
> throw away committed updates to a TOASTed column.  There's no error, and both
> verify_heapam() and bt_index_check() seem to think everything is fine.

Should this be added as an open item? [1]

- Melanie

[1] https://wiki.postgresql.org/wiki/PostgreSQL_19_Open_Items


Re: REPACK (CONCURRENTLY) can silently lose updates when the toast table is rewritten

От:
Antonin Houska <ah@cybertec.at>
Дата:
shihao zhong  wrote:

> > or whether the relfilenode should be re-checked after the snapshot is built
> 
> Holding the toast lock from the start deadlocks. A session that asks for
> AccessExclusiveLock gets an XID before it waits, and the decoding worker
> waits for all XIDs while it sets up.

The same (supposedly low) deadlock risk already exists for the main table, see
this comment in rebuild_relation():

    /*
     * Start the worker that decodes data changes applied while we're
     * copying the table contents.
     *
     * Note that the worker has to wait for all transactions with XID
     * already assigned to finish. If some of those transactions is
     * waiting for a lock conflicting with ShareUpdateExclusiveLock on our
     * table (e.g.  it runs CREATE INDEX), we can end up in a deadlock.
     * Not sure this risk is worth unlocking/locking the table (and its
     * clustering index) and checking again if it's still eligible for
     * REPACK CONCURRENTLY.
     */
    start_repack_decoding_worker(tableOid);

I'm not sure if locking the TOAST relation earlier would make the situation
worse.

The reason TOAST relation is not locked until copy_table_data() does so is
that CLUSTER / VACUUM FULL in v18 did it this way (not sure what the reason
for such design was). I haven't changed that for REPACK exactly because I
failed to envision this stale relfilenode issue.

-- 
Antonin Houska
Web: https://www.cybertec-postgresql.com


Re: REPACK (CONCURRENTLY) can silently lose updates when the toast table is rewritten

От:
Thom Brown <thom@linux.com>
Дата:
On Wed, 23 Sept 2026 at 16:07, Melanie Plageman
 wrote:
>
> On Tue, Sep 22, 2026 at 8:23 PM Thom Brown  wrote:
> >
> > Whilst stress-testing REPACK (CONCURRENTLY) I managed to get it to silently
> > throw away committed updates to a TOASTed column.  There's no error, and both
> > verify_heapam() and bt_index_check() seem to think everything is fine.
>
> Should this be added as an open item? [1]

Yes. I've now added it.

Thanks.

Thom


Re: REPACK (CONCURRENTLY) can silently lose updates when the toast table is rewritten

От:
Thom Brown <thom@linux.com>
Дата:
On Wed, 23 Sept 2026 at 17:22, Antonin Houska  wrote:
>
> shihao zhong  wrote:
>
> > > or whether the relfilenode should be re-checked after the snapshot is built
> >
> > Holding the toast lock from the start deadlocks. A session that asks for
> > AccessExclusiveLock gets an XID before it waits, and the decoding worker
> > waits for all XIDs while it sets up.
>
> The same (supposedly low) deadlock risk already exists for the main table, see
> this comment in rebuild_relation():
>
>     /*
>      * Start the worker that decodes data changes applied while we're
>      * copying the table contents.
>      *
>      * Note that the worker has to wait for all transactions with XID
>      * already assigned to finish. If some of those transactions is
>      * waiting for a lock conflicting with ShareUpdateExclusiveLock on our
>      * table (e.g.  it runs CREATE INDEX), we can end up in a deadlock.
>      * Not sure this risk is worth unlocking/locking the table (and its
>      * clustering index) and checking again if it's still eligible for
>      * REPACK CONCURRENTLY.
>      */
>     start_repack_decoding_worker(tableOid);
>
> I'm not sure if locking the TOAST relation earlier would make the situation
> worse.
>
> The reason TOAST relation is not locked until copy_table_data() does so is
> that CLUSTER / VACUUM FULL in v18 did it this way (not sure what the reason
> for such design was). I haven't changed that for REPACK exactly because I
> failed to envision this stale relfilenode issue.

I gave that a try, and it does. It just swaps the lost update for a deadlock.

If you lock the toast up front and something rewrites it at the same
time (which is the thing that triggers this in the first place, e.g. a
REPACK of the toast table), REPACK falls over:

Session 1:
BEGIN;
INSERT INTO test VALUES (999999, 'x');

Session 2:
REPACK (CONCURRENTLY) test;

Session 1:
CREATE INDEX ON test (big);

ERROR:  deadlock detected
DETAIL:  Process 214534 waits for ShareLock on transaction 1774005;
blocked by process 214579.
Process 214579 waits for AccessExclusiveLock on relation 3672470 of
database 5; blocked by process 214534.
CONTEXT:  REPACK decoding worker

The rewrite already has an XID by the time it waits, and the worker
waits for that XID whilst it sets up, so the two just sit on each
other.  It doesn't matter which lock we take either because anything
that would stop the rewrite conflicts with it.

Thom


Re: REPACK (CONCURRENTLY) can silently lose updates when the toast table is rewritten

От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
On Wed, Sep 23, 2026 at 9:23 AM Antonin Houska  wrote:
>
> shihao zhong  wrote:
>
> > > or whether the relfilenode should be re-checked after the snapshot is built
> >
> > Holding the toast lock from the start deadlocks. A session that asks for
> > AccessExclusiveLock gets an XID before it waits, and the decoding worker
> > waits for all XIDs while it sets up.
>
> The same (supposedly low) deadlock risk already exists for the main table, see
> this comment in rebuild_relation():
>
>     /*
>      * Start the worker that decodes data changes applied while we're
>      * copying the table contents.
>      *
>      * Note that the worker has to wait for all transactions with XID
>      * already assigned to finish. If some of those transactions is
>      * waiting for a lock conflicting with ShareUpdateExclusiveLock on our
>      * table (e.g.  it runs CREATE INDEX), we can end up in a deadlock.
>      * Not sure this risk is worth unlocking/locking the table (and its
>      * clustering index) and checking again if it's still eligible for
>      * REPACK CONCURRENTLY.
>      */
>     start_repack_decoding_worker(tableOid);
>
> I'm not sure if locking the TOAST relation earlier would make the situation
> worse.

Agreed.

So I think the simplest fix would be to acquire a lock on the TOAST
table before starting the repack worker. It would make the case in
question fail with a deadlock, instead of silently losing updates.

The proposed patch also fixes the problem, but I'm concerned that it
repeatedly starts and stops the repack worker without any limit. I
think we could error out if we detect a concurrent rewrite, so that
users can re-run REPACK CONCURRENTLY. This check could also be done on
the repack worker side: after getting the relfilelocator of the TOAST
table and initializing the logical decoding, the repack worker
rechecks the relfilelocator. If they don't match, it raises an error.

Regards,

-- 
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com


Re: REPACK (CONCURRENTLY) can silently lose updates when the toast table is rewritten

От:
shihao zhong <zhong950419@gmail.com>
Дата:
Вложения:
Hi Masahiko,

Thanks for reviewing it.

> I think we could error out if we detect a concurrent rewrite, so that
> users can re-run REPACK CONCURRENTLY. This check could also be done on
> the repack worker side

Agreed. v2 attached. REPACK now fails if the TOAST table was rewritten,
and the user can run it again.

The check stays in the backend, under the lock, though. If the worker
checks, a rewrite can still come after that check and before
copy_table_data() locks the TOAST table, and the update is lost the same
way. The backend takes the lock right after the worker is set up and
keeps it. Locking first would also work, but then the same race ends in
a deadlock instead of a clear error.

With the loop gone, the window Thom asked about is gone too. 0002 is the
test and is optional.

Shihao

On Wed, Sep 23, 2026 at 2:27 PM Masahiko Sawada <sawada.mshk@gmail.com> wrote:
On Wed, Sep 23, 2026 at 9:23 AM Antonin Houska <ah@cybertec.at> wrote:
>
> shihao zhong <zhong950419@gmail.com> wrote:
>
> > > or whether the relfilenode should be re-checked after the snapshot is built
> >
> > Holding the toast lock from the start deadlocks. A session that asks for
> > AccessExclusiveLock gets an XID before it waits, and the decoding worker
> > waits for all XIDs while it sets up.
>
> The same (supposedly low) deadlock risk already exists for the main table, see
> this comment in rebuild_relation():
>
>     /*
>      * Start the worker that decodes data changes applied while we're
>      * copying the table contents.
>      *
>      * Note that the worker has to wait for all transactions with XID
>      * already assigned to finish. If some of those transactions is
>      * waiting for a lock conflicting with ShareUpdateExclusiveLock on our
>      * table (e.g.  it runs CREATE INDEX), we can end up in a deadlock.
>      * Not sure this risk is worth unlocking/locking the table (and its
>      * clustering index) and checking again if it's still eligible for
>      * REPACK CONCURRENTLY.
>      */
>     start_repack_decoding_worker(tableOid);
>
> I'm not sure if locking the TOAST relation earlier would make the situation
> worse.

Agreed.

So I think the simplest fix would be to acquire a lock on the TOAST
table before starting the repack worker. It would make the case in
question fail with a deadlock, instead of silently losing updates.

The proposed patch also fixes the problem, but I'm concerned that it
repeatedly starts and stops the repack worker without any limit. I
think we could error out if we detect a concurrent rewrite, so that
users can re-run REPACK CONCURRENTLY. This check could also be done on
the repack worker side: after getting the relfilelocator of the TOAST
table and initializing the logical decoding, the repack worker
rechecks the relfilelocator. If they don't match, it raises an error.

Regards,

--
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com

Re: REPACK (CONCURRENTLY) can silently lose updates when the toast table is rewritten

От:
Manu <manuelreyesbravo@gmail.com>
Дата:
Вложения:
Hi Shihao,

> Agreed. v2 attached. REPACK now fails if the TOAST table was
> rewritten, and the user can run it again.

I ran the same checks as for v1 against v2, on cff329240ba with
--enable-cassert --enable-injection-points, next to a control build
with only v2-0002.  Both patches apply cleanly and build with no
warnings.

1. The race without an injection point (VACUUM FULL of the TOAST
relation while the worker waits, UPDATE right after), 5 runs each:

  control:  REPACK succeeds, update lost in 5 of 5
  v2:       REPACK fails in 5 of 5, update kept in 5 of 5

  ERROR:  could not execute REPACK (CONCURRENTLY) on relation "test"
  DETAIL:  The TOAST relation was rewritten concurrently.
  HINT:  The transaction might succeed if retried.

2. VACUUM FULL of the TOAST relation in a loop for 20 s, over the
whole startup: v2 fails after 3.6 s with the same error, and the
update is kept.  With v1 the same run took about 20 s and 166 worker
restarts, so the unbounded wait I mentioned for v1 is gone.

3. No rewrite at all: REPACK succeeds in 3 of 3, 2.5-2.6 s, the same
as the control.

4. Thom's deadlock case, where a transaction that already has an XID
locks the TOAST relation while the worker waits for it:

  REINDEX TABLE of the TOAST relation (lock, no rewrite)
    v2:       REPACK succeeds, no deadlock, update kept
  CLUSTER of the TOAST relation (lock and rewrite)
    control:  REPACK succeeds, update lost
    v2:       REPACK fails with the error above, update kept

So taking the lock after the worker's setup does what the commit
message says: no deadlock, and a clear error when the rewrite does
happen.

5. Tests: repack_toast fails on the control and passes with v2.  With
v2 all injection_points tests pass (4 regress, 14 isolation), and so
do make check (239) and src/test/isolation (133).

The script is attached (.txt, so the cfbot keeps testing your
patches).

Regards,
Manu

Re: REPACK (CONCURRENTLY) can silently lose updates when the toast table is rewritten

От:
Robert Treat <rob@xzilla.net>
Дата:
On Wed, Sep 23, 2026 at 2:28 PM Masahiko Sawada  wrote:
>
> On Wed, Sep 23, 2026 at 9:23 AM Antonin Houska  wrote:
> >
> > shihao zhong  wrote:
> >
> > > > or whether the relfilenode should be re-checked after the snapshot is built
> > >
> > > Holding the toast lock from the start deadlocks. A session that asks for
> > > AccessExclusiveLock gets an XID before it waits, and the decoding worker
> > > waits for all XIDs while it sets up.
> >
> > The same (supposedly low) deadlock risk already exists for the main table, see
> > this comment in rebuild_relation():
> >
> >     /*
> >      * Start the worker that decodes data changes applied while we're
> >      * copying the table contents.
> >      *
> >      * Note that the worker has to wait for all transactions with XID
> >      * already assigned to finish. If some of those transactions is
> >      * waiting for a lock conflicting with ShareUpdateExclusiveLock on our
> >      * table (e.g.  it runs CREATE INDEX), we can end up in a deadlock.
> >      * Not sure this risk is worth unlocking/locking the table (and its
> >      * clustering index) and checking again if it's still eligible for
> >      * REPACK CONCURRENTLY.
> >      */
> >     start_repack_decoding_worker(tableOid);
> >
> > I'm not sure if locking the TOAST relation earlier would make the situation
> > worse.
>
> Agreed.
>
> So I think the simplest fix would be to acquire a lock on the TOAST
> table before starting the repack worker. It would make the case in
> question fail with a deadlock, instead of silently losing updates.
>
> The proposed patch also fixes the problem, but I'm concerned that it
> repeatedly starts and stops the repack worker without any limit. I
> think we could error out if we detect a concurrent rewrite, so that
> users can re-run REPACK CONCURRENTLY. This check could also be done on
> the repack worker side: after getting the relfilelocator of the TOAST
> table and initializing the logical decoding, the repack worker
> rechecks the relfilelocator. If they don't match, it raises an error.
>

It feels a little off to me that if I am trying to REPACKCC, and
someone (maybe even myself, but certainly not Postgres) comes along
and runs a command the conflicts with my existing REPACKCC, that my
REPACKCC is canceled rather than having the other command either wait
or error out. That's a little more complicated a fix, with likely
heavier and/or longer held locks, but feels like it would be less
surprising for users.

Robert Treat
https://xzilla.net


Re: REPACK (CONCURRENTLY) can silently lose updates when the toast table is rewritten

От:
Antonin Houska <ah@cybertec.at>
Дата:
Thom Brown  wrote:

> On Wed, 23 Sept 2026 at 17:22, Antonin Houska  wrote:
> >
> > shihao zhong  wrote:
> >
> > > > or whether the relfilenode should be re-checked after the snapshot is built
> > >
> > > Holding the toast lock from the start deadlocks. A session that asks for
> > > AccessExclusiveLock gets an XID before it waits, and the decoding worker
> > > waits for all XIDs while it sets up.
> >
> > The same (supposedly low) deadlock risk already exists for the main table, see
> > this comment in rebuild_relation():
> >
> >     /*
> >      * Start the worker that decodes data changes applied while we're
> >      * copying the table contents.
> >      *
> >      * Note that the worker has to wait for all transactions with XID
> >      * already assigned to finish. If some of those transactions is
> >      * waiting for a lock conflicting with ShareUpdateExclusiveLock on our
> >      * table (e.g.  it runs CREATE INDEX), we can end up in a deadlock.
> >      * Not sure this risk is worth unlocking/locking the table (and its
> >      * clustering index) and checking again if it's still eligible for
> >      * REPACK CONCURRENTLY.
> >      */
> >     start_repack_decoding_worker(tableOid);
> >
> > I'm not sure if locking the TOAST relation earlier would make the situation
> > worse.
> >
> > The reason TOAST relation is not locked until copy_table_data() does so is
> > that CLUSTER / VACUUM FULL in v18 did it this way (not sure what the reason
> > for such design was). I haven't changed that for REPACK exactly because I
> > failed to envision this stale relfilenode issue.
> 
> I gave that a try, and it does. It just swaps the lost update for a deadlock.
> 
> If you lock the toast up front and something rewrites it at the same
> time (which is the thing that triggers this in the first place, e.g. a
> REPACK of the toast table), REPACK falls over:
> 
> Session 1:
> BEGIN;
> INSERT INTO test VALUES (999999, 'x');
> 
> Session 2:
> REPACK (CONCURRENTLY) test;
> 
> Session 1:
> CREATE INDEX ON test (big);
> 
> ERROR:  deadlock detected
> DETAIL:  Process 214534 waits for ShareLock on transaction 1774005;
> blocked by process 214579.
> Process 214579 waits for AccessExclusiveLock on relation 3672470 of
> database 5; blocked by process 214534.
> CONTEXT:  REPACK decoding worker
> 
> The rewrite already has an XID by the time it waits, and the worker
> waits for that XID whilst it sets up, so the two just sit on each
> other.  It doesn't matter which lock we take either because anything
> that would stop the rewrite conflicts with it.

IMO this example does not exactly demonstrate the problem described in the
comment above: if REPACK (CONCURRENTLY) waits for AccessExclusiveLock, it's
going to perform the relation swap, so the worker should already be gone.

On the other hand, the message

"Process ... waits for ShareLock on transaction ..."

is what the deadlock detector would report for the decoding worker. However,
where would the request for AccessExclusiveLock come from in that case? CREATE
INDEX only uses it to lock the new index relation, however that cannot be
locked by other backends until the transaction has committed (because it's not
visible before commit).

What exactly have you changed in the code?

-- 
Antonin Houska
Web: https://www.cybertec-postgresql.com


Re: REPACK (CONCURRENTLY) can silently lose updates when the toast table is rewritten

От:
Thom Brown <thom@linux.com>
Дата:
On Thu, 24 Sept 2026 at 08:57, Antonin Houska  wrote:
>
> Thom Brown  wrote:
>
> > On Wed, 23 Sept 2026 at 17:22, Antonin Houska  wrote:
> > >
> > > shihao zhong  wrote:
> > >
> > > > > or whether the relfilenode should be re-checked after the snapshot is built
> > > >
> > > > Holding the toast lock from the start deadlocks. A session that asks for
> > > > AccessExclusiveLock gets an XID before it waits, and the decoding worker
> > > > waits for all XIDs while it sets up.
> > >
> > > The same (supposedly low) deadlock risk already exists for the main table, see
> > > this comment in rebuild_relation():
> > >
> > >     /*
> > >      * Start the worker that decodes data changes applied while we're
> > >      * copying the table contents.
> > >      *
> > >      * Note that the worker has to wait for all transactions with XID
> > >      * already assigned to finish. If some of those transactions is
> > >      * waiting for a lock conflicting with ShareUpdateExclusiveLock on our
> > >      * table (e.g.  it runs CREATE INDEX), we can end up in a deadlock.
> > >      * Not sure this risk is worth unlocking/locking the table (and its
> > >      * clustering index) and checking again if it's still eligible for
> > >      * REPACK CONCURRENTLY.
> > >      */
> > >     start_repack_decoding_worker(tableOid);
> > >
> > > I'm not sure if locking the TOAST relation earlier would make the situation
> > > worse.
> > >
> > > The reason TOAST relation is not locked until copy_table_data() does so is
> > > that CLUSTER / VACUUM FULL in v18 did it this way (not sure what the reason
> > > for such design was). I haven't changed that for REPACK exactly because I
> > > failed to envision this stale relfilenode issue.
> >
> > I gave that a try, and it does. It just swaps the lost update for a deadlock.
> >
> > If you lock the toast up front and something rewrites it at the same
> > time (which is the thing that triggers this in the first place, e.g. a
> > REPACK of the toast table), REPACK falls over:
> >
> > Session 1:
> > BEGIN;
> > INSERT INTO test VALUES (999999, 'x');
> >
> > Session 2:
> > REPACK (CONCURRENTLY) test;
> >
> > Session 1:
> > CREATE INDEX ON test (big);
> >
> > ERROR:  deadlock detected
> > DETAIL:  Process 214534 waits for ShareLock on transaction 1774005;
> > blocked by process 214579.
> > Process 214579 waits for AccessExclusiveLock on relation 3672470 of
> > database 5; blocked by process 214534.
> > CONTEXT:  REPACK decoding worker
> >
> > The rewrite already has an XID by the time it waits, and the worker
> > waits for that XID whilst it sets up, so the two just sit on each
> > other.  It doesn't matter which lock we take either because anything
> > that would stop the rewrite conflicts with it.
>
> IMO this example does not exactly demonstrate the problem described in the
> comment above: if REPACK (CONCURRENTLY) waits for AccessExclusiveLock, it's
> going to perform the relation swap, so the worker should already be gone.
>
> On the other hand, the message
>
> "Process ... waits for ShareLock on transaction ..."
>
> is what the deadlock detector would report for the decoding worker. However,
> where would the request for AccessExclusiveLock come from in that case? CREATE
> INDEX only uses it to lock the new index relation, however that cannot be
> locked by other backends until the transaction has committed (because it's not
> visible before commit).
>
> What exactly have you changed in the code?

Apologies, I seem to have incorrectly paired tests with different
results during my copy and pasting.

I'll see if I can untangle it later today.

Thom


Re: REPACK (CONCURRENTLY) can silently lose updates when the toast table is rewritten

От:
Antonin Houska <ah@cybertec.at>
Дата:
Robert Treat  wrote:

> On Wed, Sep 23, 2026 at 2:28 PM Masahiko Sawada  wrote:
> >
> > On Wed, Sep 23, 2026 at 9:23 AM Antonin Houska  wrote:
> > >
> > > shihao zhong  wrote:
> > >
> > > > > or whether the relfilenode should be re-checked after the snapshot is built
> > > >
> > > > Holding the toast lock from the start deadlocks. A session that asks for
> > > > AccessExclusiveLock gets an XID before it waits, and the decoding worker
> > > > waits for all XIDs while it sets up.
> > >
> > > The same (supposedly low) deadlock risk already exists for the main table, see
> > > this comment in rebuild_relation():
> > >
> > >     /*
> > >      * Start the worker that decodes data changes applied while we're
> > >      * copying the table contents.
> > >      *
> > >      * Note that the worker has to wait for all transactions with XID
> > >      * already assigned to finish. If some of those transactions is
> > >      * waiting for a lock conflicting with ShareUpdateExclusiveLock on our
> > >      * table (e.g.  it runs CREATE INDEX), we can end up in a deadlock.
> > >      * Not sure this risk is worth unlocking/locking the table (and its
> > >      * clustering index) and checking again if it's still eligible for
> > >      * REPACK CONCURRENTLY.
> > >      */
> > >     start_repack_decoding_worker(tableOid);
> > >
> > > I'm not sure if locking the TOAST relation earlier would make the situation
> > > worse.
> >
> > Agreed.
> >
> > So I think the simplest fix would be to acquire a lock on the TOAST
> > table before starting the repack worker. It would make the case in
> > question fail with a deadlock, instead of silently losing updates.
> >
> > The proposed patch also fixes the problem, but I'm concerned that it
> > repeatedly starts and stops the repack worker without any limit. I
> > think we could error out if we detect a concurrent rewrite, so that
> > users can re-run REPACK CONCURRENTLY. This check could also be done on
> > the repack worker side: after getting the relfilelocator of the TOAST
> > table and initializing the logical decoding, the repack worker
> > rechecks the relfilelocator. If they don't match, it raises an error.
> >
> 
> It feels a little off to me that if I am trying to REPACKCC, and
> someone (maybe even myself, but certainly not Postgres) comes along
> and runs a command the conflicts with my existing REPACKCC, that my
> REPACKCC is canceled rather than having the other command either wait
> or error out.

pg_squeeze gives up as soon as it notices a "disrupting" catalog
change. Although I haven't heard complaints about this behavior (it's probably
not common to run conflicting DDL commands during maintenance window), I admit
it's not the ideal approach.

For REPACK (CONCURRENTLY), we decided to not give up voluntarily. Even if
REPACK ends up in a deadlock, it still has some chance to win. The direction
we took here is to adjust the deadlock detector (in future versions) so that
REPACK always wins. Raising ERROR on REPACK's side in case of specific
conflict would be against that strategy.

(What I said does not mean that I'm in favor of restarting the decoding worker
either. I still prefer locking the TOAST relation early, as I noted elsewhere
in the thread.)

-- 
Antonin Houska
Web: https://www.cybertec-postgresql.com


Re: REPACK (CONCURRENTLY) can silently lose updates when the toast table is rewritten

От:
shihao zhong <zhong950419@gmail.com>
Дата:
Вложения:
> (What I said does not mean that I'm in favor of restarting the decoding worker
> either. I still prefer locking the TOAST relation early, as I noted elsewhere
> in the thread.)

OK. v3 locks the TOAST relation before the worker starts, as Sawada-san
first suggested. A rewrite of the TOAST relation now waits for REPACK,
which I think is also what Robert asked for.

The deadlock I mentioned only happens if the rewrite starts while the
worker still waits for older transactions. The rewrite gets the error if
those finish within deadlock_timeout, otherwise REPACK does. Nothing is
lost either way. ALTER TABLE on the table itself hits the same deadlock
on master today.

0002 is the test. The rewrite there uses lock_timeout,
so the result does not depend on which side the deadlock detector picks.

Thanks,
Shihao

Re: REPACK (CONCURRENTLY) can silently lose updates when the toast table is rewritten

От:
Manu <manuelreyesbravo@gmail.com>
Дата:
Вложения:
Hi Shihao,

shihao zhong  wrote:
> The rewrite gets the error if those finish within deadlock_timeout,
> otherwise REPACK does.

That matches what I see with v3 on master (e27f3b2cad7), using the
same checks as for v2.  With Thom's sequence (a transaction open for
3 s, VACUUM FULL of the TOAST relation meanwhile) and the default
deadlock_timeout of 1 s, REPACK got "deadlock detected" in all 6 runs.
With deadlock_timeout = 5s, REPACK finished and the VACUUM FULL got
the error in all 3.  No update was lost in any run; master loses it
every time.

One case differs from v2: a transaction that already has an XID runs
REINDEX on the TOAST relation, with no rewrite, during the startup.
On master and with v2, REPACK completes; with v3 it gets "deadlock
detected", at both timeouts.  ALTER TABLE on the table itself
deadlocks the same way on master, as you said.

repack_toast fails without 0001 and passed 20 of 20 runs with it;
check and the isolation suite pass.  The script and output are
attached.

Regards,
Manu

Re: REPACK (CONCURRENTLY) can silently lose updates when the toast table is rewritten

От:
Antonin Houska <ah@cybertec.at>
Дата:
shihao zhong  wrote:

> > (What I said does not mean that I'm in favor of restarting the decoding worker
> > either. I still prefer locking the TOAST relation early, as I noted elsewhere
> > in the thread.)
> 
> OK. v3 locks the TOAST relation before the worker starts, as Sawada-san
> first suggested. A rewrite of the TOAST relation now waits for REPACK,
> which I think is also what Robert asked for.

Thanks for the patch. I'm just not sure this is the best place to lock the
TOAST table: note that copy_table_data() locks it again.

I'd prefer locking it close to the place we lock the main table (perhaps in
cluster_rel(), after all the checks have been done?) and replace the locking
statements (both in the copy_table_data() and in your patch) with
Assert(CheckRelationLockedByMe(...)).

-- 
Antonin Houska
Web: https://www.cybertec-postgresql.com


Re: REPACK (CONCURRENTLY) can silently lose updates when the toast table is rewritten

От:
Thom Brown <thom@linux.com>
Дата:
On Thu, 24 Sept 2026 at 09:32, Thom Brown  wrote:
>
> On Thu, 24 Sept 2026 at 08:57, Antonin Houska  wrote:
> >
> > Thom Brown  wrote:
> >
> > > On Wed, 23 Sept 2026 at 17:22, Antonin Houska  wrote:
> > > >
> > > > shihao zhong  wrote:
> > > >
> > > > > > or whether the relfilenode should be re-checked after the snapshot is built
> > > > >
> > > > > Holding the toast lock from the start deadlocks. A session that asks for
> > > > > AccessExclusiveLock gets an XID before it waits, and the decoding worker
> > > > > waits for all XIDs while it sets up.
> > > >
> > > > The same (supposedly low) deadlock risk already exists for the main table, see
> > > > this comment in rebuild_relation():
> > > >
> > > >     /*
> > > >      * Start the worker that decodes data changes applied while we're
> > > >      * copying the table contents.
> > > >      *
> > > >      * Note that the worker has to wait for all transactions with XID
> > > >      * already assigned to finish. If some of those transactions is
> > > >      * waiting for a lock conflicting with ShareUpdateExclusiveLock on our
> > > >      * table (e.g.  it runs CREATE INDEX), we can end up in a deadlock.
> > > >      * Not sure this risk is worth unlocking/locking the table (and its
> > > >      * clustering index) and checking again if it's still eligible for
> > > >      * REPACK CONCURRENTLY.
> > > >      */
> > > >     start_repack_decoding_worker(tableOid);
> > > >
> > > > I'm not sure if locking the TOAST relation earlier would make the situation
> > > > worse.
> > > >
> > > > The reason TOAST relation is not locked until copy_table_data() does so is
> > > > that CLUSTER / VACUUM FULL in v18 did it this way (not sure what the reason
> > > > for such design was). I haven't changed that for REPACK exactly because I
> > > > failed to envision this stale relfilenode issue.
> > >
> > > I gave that a try, and it does. It just swaps the lost update for a deadlock.
> > >
> > > If you lock the toast up front and something rewrites it at the same
> > > time (which is the thing that triggers this in the first place, e.g. a
> > > REPACK of the toast table), REPACK falls over:
> > >
> > > Session 1:
> > > BEGIN;
> > > INSERT INTO test VALUES (999999, 'x');
> > >
> > > Session 2:
> > > REPACK (CONCURRENTLY) test;
> > >
> > > Session 1:
> > > CREATE INDEX ON test (big);
> > >
> > > ERROR:  deadlock detected
> > > DETAIL:  Process 214534 waits for ShareLock on transaction 1774005;
> > > blocked by process 214579.
> > > Process 214579 waits for AccessExclusiveLock on relation 3672470 of
> > > database 5; blocked by process 214534.
> > > CONTEXT:  REPACK decoding worker
> > >
> > > The rewrite already has an XID by the time it waits, and the worker
> > > waits for that XID whilst it sets up, so the two just sit on each
> > > other.  It doesn't matter which lock we take either because anything
> > > that would stop the rewrite conflicts with it.
> >
> > IMO this example does not exactly demonstrate the problem described in the
> > comment above: if REPACK (CONCURRENTLY) waits for AccessExclusiveLock, it's
> > going to perform the relation swap, so the worker should already be gone.
> >
> > On the other hand, the message
> >
> > "Process ... waits for ShareLock on transaction ..."
> >
> > is what the deadlock detector would report for the decoding worker. However,
> > where would the request for AccessExclusiveLock come from in that case? CREATE
> > INDEX only uses it to lock the new index relation, however that cannot be
> > locked by other backends until the transaction has committed (because it's not
> > visible before commit).
> >
> > What exactly have you changed in the code?
>
> Apologies, I seem to have incorrectly paired tests with different
> results during my copy and pasting.
>
> I'll see if I can untangle it later today.

I'd run two separate tests and pasted the error from one under the
steps of the other.

Okay, if I start from scratch:

Session 1:
CREATE TABLE test (id int PRIMARY KEY, big text);

BEGIN;
INSERT INTO test VALUES (999999, 'x');

Session 2:
REPACK (CONCURRENTLY) test;

Session 1:
CREATE INDEX ON test (big);

ERROR:  deadlock detected
DETAIL:  Process 1172013 waits for ShareLock on relation 3672610 of
database 5; blocked by process 1172091.
Process 1172091 waits for ShareLock on transaction 1774055; blocked by
process 1172013.

Regards

Thom


Re: REPACK (CONCURRENTLY) can silently lose updates when the toast table is rewritten

От:
Thom Brown <thom@linux.com>
Дата:
On Fri, 25 Sept 2026 at 07:24, Antonin Houska  wrote:
>
> shihao zhong  wrote:
>
> > > (What I said does not mean that I'm in favor of restarting the decoding worker
> > > either. I still prefer locking the TOAST relation early, as I noted elsewhere
> > > in the thread.)
> >
> > OK. v3 locks the TOAST relation before the worker starts, as Sawada-san
> > first suggested. A rewrite of the TOAST relation now waits for REPACK,
> > which I think is also what Robert asked for.
>
> Thanks for the patch. I'm just not sure this is the best place to lock the
> TOAST table: note that copy_table_data() locks it again.
>
> I'd prefer locking it close to the place we lock the main table (perhaps in
> cluster_rel(), after all the checks have been done?) and replace the locking
> statements (both in the copy_table_data() and in your patch) with
> Assert(CheckRelationLockedByMe(...)).

Moving it into cluster_rel() makes sense, but does it need to be the
full ShareUpdateExclusiveLock there?

If I've understood it right, all that matters before the worker starts
is that nobody can rewrite the TOAST relation, and a rewrite needs
AccessExclusiveLock.  So would an AccessShareLock be enough at that
point, at least in the concurrent case?  If so, I guess it would also
avoid the case Manu found, where a REINDEX of the TOAST relation from
a transaction that already has an XID deadlocks during startup, as
REINDEX doesn't need a lock that strong.

The stronger lock could presumably still be taken later, where it is
now, once the worker has finished waiting for other transactions, so
waiting for it there couldn't turn into a deadlock.  But I may well be
missing a reason it has to be the stronger one from the start.

Thom


Re: REPACK (CONCURRENTLY) can silently lose updates when the toast table is rewritten

От:
shihao zhong <zhong950419@gmail.com>
Дата:
Вложения:
Hi Thom,

> If I've understood it right, all that matters before the worker starts
> is that nobody can rewrite the TOAST relation, and a rewrite needs
> AccessExclusiveLock.  So would an AccessShareLock be enough at that
> point, at least in the concurrent case?

Yes. v4 does it that way.

cluster_rel() now locks the TOAST relation after the checks, as Antonin
suggested. It takes AccessShareLock in the concurrent case and
AccessExclusiveLock otherwise. rebuild_relation() upgrades to
ShareUpdateExclusiveLock once the worker has returned the initial
snapshot, when it no longer waits for other transactions.
copy_table_data() only has the Assert now.

The upgrade does not deadlock with a VACUUM FULL of the TOAST relation
that queued in between. The lock manager puts us ahead of a waiter that
conflicts with a lock we already hold. I checked this with REPACK
stopped in a debugger right before the upgrade.

Manu's REINDEX case passes now, at 1s and 5s deadlock_timeout. 0002 also
runs that REINDEX now, from the transaction the worker waits for. With
v3 it gets "deadlock detected".

Thanks,
Shihao

Re: REPACK (CONCURRENTLY) can silently lose updates when the toast table is rewritten

От:
Álvaro Herrera <alvherre@kurilemu.de>
Дата:
Вложения:
On 2026-Sep-25, Thom Brown wrote:

> Moving it into cluster_rel() makes sense, but does it need to be the
> full ShareUpdateExclusiveLock there?

Yeah, it's better to acquire the lock you want upfront, because
otherwise you introduce more risk of deadlock caused by lock upgrades
(admittedly the user would have to be doing something really stupid in
order for this to be a real problem, but still.)  It's only AEL that we
don't want to hold for long.

Maybe the patch could be somewhat like this, then?  I didn't review the
test carefully other than running without the code fix to verify that it
fails, and then passes with the fix; and I didn't read the commit
messages either, which I think are LLM-written and not really correct.
(Also, I would push both things as a single commit.)

I think changing the lock as obtained by copy_table_data is not very
nice, because that one is unconditional, and here we only want it in
concurrent mode.  BTW I noticed that the comment for copy_table_data
mentions decoding_ctx as an argument, which doesn't exist.

-- 
Álvaro Herrera               48°01'N 7°57'E  —  https://www.EnterpriseDB.com/
"Nunca se desea ardientemente lo que solo se desea por razón" (F. Alexandre)

Re: REPACK (CONCURRENTLY) can silently lose updates when the toast table is rewritten

От:
shihao zhong <zhong950419@gmail.com>
Дата:
> (Also, I would push both things as a single commit.)

Fine with me. I kept the test separate only because committers sometimes
push the fix without the test.

Taking the full lock upfront brings back the deadlock Manu found, where
a transaction the worker waits for runs REINDEX on the TOAST relation.

That is the same kind of case as DDL on the table itself, so I'm fine
with it.

Thanks,
Shihao

Re: REPACK (CONCURRENTLY) can silently lose updates when the toast table is rewritten

От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
On Fri, Sep 25, 2026 at 7:57 AM Álvaro Herrera  wrote:
>
> On 2026-Sep-25, Thom Brown wrote:
>
> > Moving it into cluster_rel() makes sense, but does it need to be the
> > full ShareUpdateExclusiveLock there?
>
> Yeah, it's better to acquire the lock you want upfront, because
> otherwise you introduce more risk of deadlock caused by lock upgrades
> (admittedly the user would have to be doing something really stupid in
> order for this to be a real problem, but still.)  It's only AEL that we
> don't want to hold for long.

+1

> Maybe the patch could be somewhat like this, then?  I didn't review the
> test carefully other than running without the code fix to verify that it
> fails, and then passes with the fix; and I didn't read the commit
> messages either, which I think are LLM-written and not really correct.
> (Also, I would push both things as a single commit.)

The patch looks good to me. How about updating the comment in
repack_setup_logical_decoding() to explain that the backend holds the
lock on both relations so the worker doesn't need to keep the locks on
them? For example:

@@ -253,7 +253,9 @@ repack_setup_logical_decoding(Oid relid)

    /*
     * Set up repacked_rel_locator and repacked_rel_toast_locator, which we
-    * use to skip decoding of unrelated relations.
+    * use to skip decoding of unrelated relations. We need not keep the
+    * locks as the backend holds a lock on both the table and its TOAST
+    * relation that prevents them from being rewritten until REPACK finishes.
     */
    rel = table_open(relid, AccessShareLock);
    repacked_rel_locator = rel->rd_locator;

> I think changing the lock as obtained by copy_table_data is not very
> nice, because that one is unconditional, and here we only want it in
> concurrent mode.  BTW I noticed that the comment for copy_table_data
> mentions decoding_ctx as an argument, which doesn't exist.

True.

Regards,

-- 
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com


Re: REPACK (CONCURRENTLY) can silently lose updates when the toast table is rewritten

От:
shihao zhong <zhong950419@gmail.com>
Дата:
Вложения:
Done in v5. 0001 is Álvaro's version as one commit, with that comment
added and a shorter commit message. 0002 fixes the decoding_ctx comment
in copy_table_data().

Thanks,
Shihao

Re: REPACK (CONCURRENTLY) can silently lose updates when the toast table is rewritten

От:
Manu <manuelreyesbravo@gmail.com>
Дата:
Вложения:
Hi,

shihao zhong  wrote:
> Done in v5. 0001 is Álvaro's version as one commit, with that comment
> added and a shorter commit message. 0002 fixes the decoding_ctx comment
> in copy_table_data().

I ran v5 through the same checks as v3, on master and on
REL_19_STABLE, where it applies cleanly.

With the test but without the code change, repack_toast fails in
s1_check: 10 rows of s2's updates are missing, not just the lock
timeout line.  With v5 it passed 30 of 30 runs, and 30 of 30 with the
run pinned to one CPU, since the new permutation depends on
lock_timeout and the (*) marker.

The core regression and isolation suites pass on both branches.  In
the behaviour checks no update was lost.  A rewrite or REINDEX of the
TOAST relation from a transaction the worker waits for now ends in a
deadlock error, as discussed: REPACK is the one cancelled at a 1s
deadlock_timeout, the other session at 5s.

The output and scripts are attached.

Regards,
Manu

Re: REPACK (CONCURRENTLY) can silently lose updates when the toast table is rewritten

От:
Álvaro Herrera <alvherre@kurilemu.de>
Дата:
On 2026-Sep-25, Manu wrote:

> Hi,
> 
> shihao zhong  wrote:
> > Done in v5. 0001 is Álvaro's version as one commit, with that comment
> > added and a shorter commit message. 0002 fixes the decoding_ctx comment
> > in copy_table_data().
> 
> I ran v5 through the same checks as v3, on master and on
> REL_19_STABLE, where it applies cleanly.

Thanks!  I have pushed this.  I apologize for forgetting to list
reviewers in the commit message :-(  But I also failed to remember in
time that doing CheckRelationOidLockedByMe() doesn't actually check
anything, and that it needs to be used in conjunction with Assert().  I
have pushed a fix for that and wrote the "Reviewed-by" trailers there.

Anyway, regarding the patch, I changed some comments a little bit more.
The only change of actual significance is that I revisited my earlier
idea of not touching copy_table_data: I did change the lock acquisition
into an assert, when in concurrent mode.  This is what Antonin had
suggested back in [1], and I thought would be "not very nice", but I
think I was mistaken.

[1] https://postgr.es/m/4324.1790317455@localhost

Regarding the deadlock when a conflicting lock on the toast table is
acquired during the initial steps, I'm not too worried about it; I think
it's on the spirit of "play stupid games, win you-know-what-kind-of-
prizes", and it hopefully won't be too bad in practice.


-- 
Álvaro Herrera        Breisgau, Deutschland  —  https://www.EnterpriseDB.com/
"No necesitamos banderas
 No reconocemos fronteras"                  (Jorge González)


FAQ