pg_repack.git / summary / log / commit / refs

commit    f5aa3884a655fc0e8fa20ab25cbf91aba228fcdf
Author:   Masahiko Sawada <sawada.mshk@gmail.com>
Date:     Mon May 20 01:22:30 2024 +0000

    Fix possible two vacuums concurrently processing the same relfilenode.
    
    Previously, while swapping the target table and its temp table, we
    used to acquire an AccessExclusiveLock on only the target table but
    not on its temp table. So the following scenario could happen:
    
    1. Run (auto) vacuum on the temp table.
    2. Swap the target table's relfile node and the temp table's
    relfilenode, and commit.
    3. Run (auto) vacuum on the target table.
    
    1 and 3 run concurrently on different tables but these tables use the
    same relfilenode. In the reported case, since concurrent
    changes (INSERT/UPDATE/DELETE) can also run concurrently, the second
    vacuum ended up removing newly added tuples.
    
    To fix the issue, this commit changes the pg_repack command so that it
    acquires an AcessExclusiveLock also on the temp table before swapping
    these tables.
    
    Issue: #399


bin/pg_repack.c | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/bin/pg_repack.c b/bin/pg_repack.c index a64383c..2d8d588 100644 --- a/bin/pg_repack.c +++ b/bin/pg_repack.c @@ -189,6 +189,7 @@ typedef struct repack_table Oid target_tidx; /* target: toast index OID */ Oid pkid; /* target: PK OID */ Oid ckid; /* target: CK OID */ + Oid temp_oid; /* temp: OID */ const char *create_pktype; /* CREATE TYPE pk */ const char *create_log; /* CREATE TABLE log */ const char *create_trigger; /* CREATE TRIGGER repack_trigger */ @@ -1537,6 +1538,14 @@ repack_one_table(repack_table *table, const char *orderby) command(sql.data, 0, NULL); command("COMMIT", 0, NULL); + /* Get OID of the temp table */ + printfStringInfo(&sql, "SELECT 'repack.table_%u'::regclass::oid", + table->target_oid); + res = execute(sql.data, 0, NULL); + table->temp_oid = getoid(res, 0, 0); + Assert(OidIsValid(table->temp_oid)); + CLEARPGRES(res); + /* * 3. Create indexes on temp table. */ @@ -1612,6 +1621,20 @@ repack_one_table(repack_table *table, const char *orderby) goto cleanup; } + /* + * Acquire AccessExclusiveLock on the temp table to prevent concurrent + * operations during swapping relations. + */ + printfStringInfo(&sql, "LOCK TABLE repack.table_%u IN ACCESS EXCLUSIVE MODE", + table->target_oid); + if (!(lock_exclusive(conn2, utoa(table->temp_oid, buffer), + sql.data, false))) + { + elog(WARNING, "lock_exclusive() failed in conn2 for table_%u", + table->target_oid); + goto cleanup; + } + apply_log(conn2, table, 0); params[0] = utoa(table->target_oid, buffer); pgut_command(conn2, "SELECT repack.repack_swap($1)", 1, params); [parent: b583237d740c]