Resetting snapshots during the first phase of [CREATE |RE]INDEX CONCURRENTLY

Started by Mihail Nikalayeu11 months ago14 messageshackers

Thread notes

1 note#performance#major#enhancement
hackorum-bot#performance#major#enhancement
hackorum-bot
2 days ago

@global #performance #major #enhancement

#performance#major#enhancement
Jump to latest
#1Mihail Nikalayeu
mihailnikalayeu@gmail.com

Hello, everyone!

(added to CC involved persons based on history part and previous thread
activity)

This thread is an extraction of part of
https://commitfest.postgresql.org/patch/4971/ (STIR) into a separate
commitfest entry as was agreed in [0]/messages/by-id/CAEze2Wg6d2M8hop4uwdQXeH-YkOmEHyqp83+aE7vEzKdmu7w-A@mail.gmail.com.

HISTORY

In 2021 Álvaro proposed [1]/messages/by-id/20210115142926.GA19300@alvherre.pgsql and committed [2]https://github.com/postgres/postgres/commit/d9d076222f5b94a85e0e318339cfc44b8f26022d the feature: VACUUM ignores
snapshots involved in concurrent indexing operations. This was a great
feature in PG14.

But in 2022 a bug related to the tuples missing in indexes was detected,
and a little bit later explained by Andres [3]/messages/by-id/20220524190133.j6ee7zh4f5edt5je@alap3.anarazel.de. As a result, the feature
was reverted [4]https://github.com/postgres/postgres/commit/e28bb885196916b0a3d898ae4f2be0e38108d81b.

This patch set brings back part of it (first phase of CIC) using
snapshot resetting technique.
For the second phase - another solution is available in entry mentioned
above.

STRUCTURE

It is based on Matthias' idea [5]/messages/by-id/CAEze2WgW6pj48xJhG_YLUE1QS+n9Yv0AZQwaWeb-r+X=HAxU_g@mail.gmail.com - to just reset snapshots every so often
during a concurrent index build. It may work only during the first scan
(because we'll miss some tuples during validation scan with such an
approach).
Logic is simple – since the index built by the first scan already misses a
lot of tuples – we may not worry to miss a few more – the validation phase
is going to fix it anyway. Of course, it is not so simple in case of unique
indexes, but still possible.

Commits are:

- Add stress tests for concurrent index builds

This is a set of stress tests to ensure concurrent index operations are
worked correctly.
It easily detects the bug from 2022 (and other different things I met
during the development, some were in master and already fixed - [6]https://commitfest.postgresql.org/patch/5438/ and
[7]: https://commitfest.postgresql.org/patch/5160/

- Reset snapshots periodically in non-unique non-parallel concurrent index
builds

Apply this technique to the simplest case – non-unique and non-parallel.
Snapshot is changed "between" pages.
One possible place here to worry about – to ensure xmin advanced we need to
call InvalidateCatalogSnapshot during each snapshot switch.
So, theoretically it may cause some issues, but the table is locked to
changes during the process. At least commit [2]https://github.com/postgres/postgres/commit/d9d076222f5b94a85e0e318339cfc44b8f26022d (which ignored xmin of
CIC backend) did the same thing in essence, actually. Another more "clear"
option here - we may just extract a separate catalog snapshot horizon (one
more field near xmin specially only for catalog snapshot), it seems to be a
pretty straightforward change.

- Support snapshot resets in parallel concurrent index builds

Extend that technique to parallel builds. It is mostly about ensuring
workers have an initial snapshot restored from the leader before the leader
goes to reset it.

- Support snapshot resets in concurrent builds of unique indexes

The most tricky commit in the patch set – apply that to unique indexes.
Changing of snapshots may cause issues with validation of unique
constraints. Currently, validation is done during the sorting of tuples,
but that doesn't work with tuples read with different snapshots (some of
them are dead already).

To deal with it:
- in case we see two identical tuples during tuplesort – ignore if some of
them are dead according to SnapshotSelf, but fail if two are alive. It is
not a required part, it is just mechanics for fail-fast behavior and may be
removed or limited in spent resources.
- to provide the guarantee – during _bt_load compare the inserted index
value with previously inserted. If they are equal – make sure only a single
SnapshotSelf alive tuple exists in the whole equal "group" (it may include
more than two tuples in general).

Theoretically it may affect performance of _bt_load because of
_bt_keep_natts(_fast) call for each tuple, but I was unable to notice any
significant difference here.

Best regards,
Mikhail.

[0]: /messages/by-id/CAEze2Wg6d2M8hop4uwdQXeH-YkOmEHyqp83+aE7vEzKdmu7w-A@mail.gmail.com
/messages/by-id/CAEze2Wg6d2M8hop4uwdQXeH-YkOmEHyqp83+aE7vEzKdmu7w-A@mail.gmail.com
[1]: /messages/by-id/20210115142926.GA19300@alvherre.pgsql
/messages/by-id/20210115142926.GA19300@alvherre.pgsql
[2]: https://github.com/postgres/postgres/commit/d9d076222f5b94a85e0e318339cfc44b8f26022d
https://github.com/postgres/postgres/commit/d9d076222f5b94a85e0e318339cfc44b8f26022d
[3]: /messages/by-id/20220524190133.j6ee7zh4f5edt5je@alap3.anarazel.de
/messages/by-id/20220524190133.j6ee7zh4f5edt5je@alap3.anarazel.de
[4]: https://github.com/postgres/postgres/commit/e28bb885196916b0a3d898ae4f2be0e38108d81b
https://github.com/postgres/postgres/commit/e28bb885196916b0a3d898ae4f2be0e38108d81b
[5]: /messages/by-id/CAEze2WgW6pj48xJhG_YLUE1QS+n9Yv0AZQwaWeb-r+X=HAxU_g@mail.gmail.com
/messages/by-id/CAEze2WgW6pj48xJhG_YLUE1QS+n9Yv0AZQwaWeb-r+X=HAxU_g@mail.gmail.com
[6]: https://commitfest.postgresql.org/patch/5438/
[7]: https://commitfest.postgresql.org/patch/5160/

Attachments:

v1-0001-Add-stress-tests-for-concurrent-index-builds.patchapplication/x-patch; name=v1-0001-Add-stress-tests-for-concurrent-index-builds.patchDownload+226-6
v1-0004-Support-snapshot-resets-in-concurrent-builds-of-u.patchapplication/x-patch; name=v1-0004-Support-snapshot-resets-in-concurrent-builds-of-u.patchDownload+290-99
v1-0002-Reset-snapshots-periodically-in-non-unique.patchapplication/x-patch; name=v1-0002-Reset-snapshots-periodically-in-non-unique.patchDownload+473-41
v1-0003-Support-snapshot-resets-in-parallel-concurrent-in.patchapplication/x-patch; name=v1-0003-Support-snapshot-resets-in-parallel-concurrent-in.patchDownload+208-90
#2Mihail Nikalayeu
mihailnikalayeu@gmail.com
In reply to: Mihail Nikalayeu (#1)
Re: Resetting snapshots during the first phase of [CREATE |RE]INDEX CONCURRENTLY
#3Mihail Nikalayeu
mihailnikalayeu@gmail.com
In reply to: Mihail Nikalayeu (#2)
Re: Resetting snapshots during the first phase of [CREATE |RE]INDEX CONCURRENTLY

Hello, everyone!

Rebased.

Attachments:

v2-0004-Support-snapshot-resets-in-concurrent-builds-of-u.patchapplication/x-patch; name=v2-0004-Support-snapshot-resets-in-concurrent-builds-of-u.patchDownload+290-99
v2-0002-Reset-snapshots-periodically-in-non-unique-non-pa.patchapplication/x-patch; name=v2-0002-Reset-snapshots-periodically-in-non-unique-non-pa.patchDownload+474-41
v2-0001-Add-stress-tests-for-concurrent-index-builds.patchapplication/x-patch; name=v2-0001-Add-stress-tests-for-concurrent-index-builds.patchDownload+226-6
v2-0003-Support-snapshot-resets-in-parallel-concurrent-in.patchapplication/x-patch; name=v2-0003-Support-snapshot-resets-in-parallel-concurrent-in.patchDownload+208-90
#4Mihail Nikalayeu
mihailnikalayeu@gmail.com
In reply to: Mihail Nikalayeu (#3)
Re: Resetting snapshots during the first phase of [CREATE |RE]INDEX CONCURRENTLY

Rebased.

Attachments:

v3-0001-Add-stress-tests-for-concurrent-index-builds.patchapplication/octet-stream; name=v3-0001-Add-stress-tests-for-concurrent-index-builds.patchDownload+226-6
v3-0003-Support-snapshot-resets-in-parallel-concurrent-in.patchapplication/octet-stream; name=v3-0003-Support-snapshot-resets-in-parallel-concurrent-in.patchDownload+208-90
v3-0002-Reset-snapshots-periodically-in-non-unique-non-pa.patchapplication/octet-stream; name=v3-0002-Reset-snapshots-periodically-in-non-unique-non-pa.patchDownload+474-41
v3-0004-Support-snapshot-resets-in-concurrent-builds-of-u.patchapplication/octet-stream; name=v3-0004-Support-snapshot-resets-in-concurrent-builds-of-u.patchDownload+290-99
#5Alvaro Herrera
alvherre@kurilemu.de
In reply to: Mihail Nikalayeu (#4)
Re: Resetting snapshots during the first phase of [CREATE |RE]INDEX CONCURRENTLY

On 2026-Mar-20, Mihail Nikalayeu wrote:

Rebased.

Thanks. The test in 0001 is a bit on the slow side; should we make it
optional with PG_TEST_EXTRA? It's even slower than the slowest test in
pg_amcheck, which is already somewhat too long.

1/9 postgresql:setup / tmp_install OK 0.84s
2/9 postgresql:setup / install_test_files OK 0.05s
3/9 postgresql:setup / initdb_cache OK 1.26s
4/9 postgresql:pg_amcheck / pg_amcheck/001_basic OK 0.20s 9 subtests passed
5/9 postgresql:pg_amcheck / pg_amcheck/005_opclass_damage OK 4.53s 10 subtests passed
6/9 postgresql:pg_amcheck / pg_amcheck/002_nonesuch OK 5.00s 107 subtests passed
7/9 postgresql:pg_amcheck / pg_amcheck/004_verify_heapam OK 8.59s 32 subtests passed
8/9 postgresql:pg_amcheck / pg_amcheck/003_check OK 19.14s 75 subtests passed
9/9 postgresql:pg_amcheck / pg_amcheck/006_cic OK 26.74s 12 subtests passed

The last pgbench subtest mentions GIN in the test name but doesn't
actually run it. Do we care? Would it be good to make the table be
unlogged?

These 10ms sleeps look suspicious. Should they be shorter? Longer? Is
it better if they are longer, because they help provide better coverage;
or how did you choose that value? I think all-but-one backends will
complete all the 999 transactions in the first 10ms sleep that the one
backend running the CIC does. Am I right about this? Would it work to
have no sleeps at all? Maybe instead of doing 1000 transactions, we
should run pgbench for 5 second or so; this would run several thousand
transactions.

Or should we just consider the test as not-for-commit, and only a
development aid?

--
Álvaro Herrera 48°01'N 7°57'E — https://www.EnterpriseDB.com/

#6Mihail Nikalayeu
mihailnikalayeu@gmail.com
In reply to: Alvaro Herrera (#5)
Re: Resetting snapshots during the first phase of [CREATE |RE]INDEX CONCURRENTLY

Hello, Álvaro!

Thanks for looking into it.

Or should we just consider the test as not-for-commit, and only a
development aid?

Initially I thought so, but looks like it is possible to make it committable.

The test in 0001 is a bit on the slow side; should we make it
optional with PG_TEST_EXTRA?

I made *parameters* to be depended on PG_TEST_EXTRA ~= stress. It is
possible to apply the same pattern for other stress tests too.

The last pgbench subtest mentions GIN in the test name but doesn't
actually run it. Do we care? Would it be good to make the table be
unlogged?

Fixed, it has its own pgbench because it has its own gin_index_check.

Would it be good to make the table be unlogged?

Good idea, done.

I think all-but-one backends will
complete all the 999 transactions in the first 10ms sleep that the one
backend running the CIC does. Am I right about this?

It actually has enough time to do multiple CIC (I see it from the
log). I updated the test to random delay, for non-stress variants -
from 0 to 1, for stress - up to 10.

Also, fixed a few small styling issues + added additional fixes for
waiting for a snapshot to be restored by a parallel worker.

Best regards,
Mikhail.

Attachments:

v4-0002-Reset-snapshots-periodically-in-non-unique-non-pa.patchapplication/octet-stream; name=v4-0002-Reset-snapshots-periodically-in-non-unique-non-pa.patchDownload+474-41
v4-0001-Add-stress-tests-for-concurrent-index-builds.patchapplication/octet-stream; name=v4-0001-Add-stress-tests-for-concurrent-index-builds.patchDownload+274-6
v4-0004-Support-snapshot-resets-in-concurrent-builds-of-u.patchapplication/octet-stream; name=v4-0004-Support-snapshot-resets-in-concurrent-builds-of-u.patchDownload+274-103
v4-0003-Support-snapshot-resets-in-parallel-concurrent-in.patchapplication/octet-stream; name=v4-0003-Support-snapshot-resets-in-parallel-concurrent-in.patchDownload+244-92
#7Mihail Nikalayeu
mihailnikalayeu@gmail.com
In reply to: Mihail Nikalayeu (#6)
Re: Resetting snapshots during the first phase of [CREATE |RE]INDEX CONCURRENTLY

Hello!

0) Rebased
1) Added REPEATABLE READ isolation level
2) Some GUGs for developers
3) Some small refactorings

Attachments:

v5-0001-Add-stress-tests-for-concurrent-index-builds.patchapplication/octet-stream; name=v5-0001-Add-stress-tests-for-concurrent-index-builds.patchDownload+294-6
v5-0004-Support-snapshot-resets-in-concurrent-builds-of-u.patchapplication/octet-stream; name=v5-0004-Support-snapshot-resets-in-concurrent-builds-of-u.patchDownload+274-85
v5-0003-Support-snapshot-resets-in-parallel-concurrent-in.patchapplication/octet-stream; name=v5-0003-Support-snapshot-resets-in-parallel-concurrent-in.patchDownload+259-65
v5-0002-Reset-snapshots-periodically-in-non-unique-non-pa.patchapplication/octet-stream; name=v5-0002-Reset-snapshots-periodically-in-non-unique-non-pa.patchDownload+509-43
#8Mihail Nikalayeu
mihailnikalayeu@gmail.com
In reply to: Mihail Nikalayeu (#7)
Re: Resetting snapshots during the first phase of [CREATE |RE]INDEX CONCURRENTLY

Rebased +

1) extract duplicate key error reporting into _bt_report_duplicate()
2) limit heap fetches in the tuplesort fail-fast duplicate check to a
configurable percentage

Best regards,
Mikhail.

Attachments:

v5-0001-Add-stress-tests-for-concurrent-index-builds.patchapplication/octet-stream; name=v5-0001-Add-stress-tests-for-concurrent-index-builds.patchDownload+294-7
v5-0003-Support-snapshot-resets-in-parallel-concurrent-in.patchapplication/octet-stream; name=v5-0003-Support-snapshot-resets-in-parallel-concurrent-in.patchDownload+259-65
v5-0002-Reset-snapshots-periodically-in-non-unique-non-pa.patchapplication/octet-stream; name=v5-0002-Reset-snapshots-periodically-in-non-unique-non-pa.patchDownload+509-43
v5-0004-Support-snapshot-resets-in-concurrent-builds-of-u.patchapplication/octet-stream; name=v5-0004-Support-snapshot-resets-in-concurrent-builds-of-u.patchDownload+320-89
#9Mihail Nikalayeu
mihailnikalayeu@gmail.com
In reply to: Mihail Nikalayeu (#8)
Re: Resetting snapshots during the first phase of [CREATE |RE]INDEX CONCURRENTLY

Some small fixes around.

Attachments:

t53098_9
v6-0002-Reset-snapshots-periodically-in-non-unique-non-pa.patchapplication/octet-stream; name=v6-0002-Reset-snapshots-periodically-in-non-unique-non-pa.patchDownload+509-43
v6-0003-Support-snapshot-resets-in-parallel-concurrent-in.patchapplication/octet-stream; name=v6-0003-Support-snapshot-resets-in-parallel-concurrent-in.patchDownload+257-65
v6-0004-Support-snapshot-resets-in-concurrent-builds-of-u.patchapplication/octet-stream; name=v6-0004-Support-snapshot-resets-in-concurrent-builds-of-u.patchDownload+320-89
v6-0001-Add-stress-tests-for-concurrent-index-builds.patchapplication/octet-stream; name=v6-0001-Add-stress-tests-for-concurrent-index-builds.patchDownload+294-7
#10Matthias van de Meent
boekewurm+postgres@gmail.com
In reply to: Mihail Nikalayeu (#9)
Re: Resetting snapshots during the first phase of [CREATE |RE]INDEX CONCURRENTLY

On Sat, 18 Apr 2026 at 15:34, Mihail Nikalayeu
<mihailnikalayeu@gmail.com> wrote:

Some small fixes around.

Here's my long-overdue review of this patchset. I've reviewed all but
patch 0001, as I assume that patch to not get committed.

------

0002:

The patch title and description could use some love. The title is too
long (whole paragraph), and the remainder could use some manual
wrapping

+++ b/src/include/catalog/index.h
+ * Snapshot resetting is only applicable when all of:
+ * - the build is concurrent (ii_Concurrent)
[...]
+ * - isolation level is not REPEATABLE READ/SERIALIZABLE (those keep a
+ *   registered transaction snapshot)

This seems strange to me - with R/CIC we know we're a top-level
command that outlives every transaction that touches the index's
table, so why do we suddenly care about serializability?

+++ b/contrib/amcheck/verify_nbtree.c
-                                     true); /* syncscan OK? */
+                                     true, /* syncscan OK? */
+                                     false);

Please add the comment indicating what the flag indicates, e.g. /*
reset_snapshot OK? */

+++ b/src/backend/access/brin/brin.c

[...]

+    {
snapshot = RegisterSnapshot(GetTransactionSnapshot());
+        PushActiveSnapshot(GetTransactionSnapshot());
+    }

The snapshot management in _brin_begin_parallel here seems wasteful;
It does both RegisterSnapshot() and PushActiveSnapshot() on the output
of GetTransactionSnapshot(). This usually causes the same snapshot to
be allocated and copied twice. Why not call PushActiveSnapshot() with
the result of RegisterSnapshot(), like what _bt_begin_parallel does?
I.e.

+    {
         snapshot = RegisterSnapshot(GetTransactionSnapshot());
+        PushActiveSnapshot(snapshot);
+    }

The same comment applies for _gin_begin_parallel.

+ InvalidateCatalogSnapshot();

I see this sprinkled around in various places that don't directly do
any other snapshot management -related things, nor do they seem to
handle much related to catalog content management. Why are they
sprinkled around those places, and not as part of the main scan
snapshot management? It's not just in brin.c, but also other AMs,
like access/hash/hash.c, which doesn't have *any* other modifications.

+++ b/src/backend/access/heap/heapam.c
+/*
+ * Reset the active snapshot during a scan.
+ * This ensures the xmin horizon can advance while maintaining safe tuple visibility.
+ * Note: No other snapshot should be active during this operation.
+ */
+static inline void
+heap_reset_scan_snapshot(TableScanDesc sscan)
+{
+    /* Make sure no other snapshot was set as active. */
+    Assert(GetActiveSnapshot() == sscan->rs_snapshot);
+    /* And make sure active snapshot is not registered. */
+    Assert(GetActiveSnapshot()->regd_count == 0);

Snapshots MUST be registered before you can use them. It is inherently
unsafe to not register snapshots you're going to use, so please use
UnregisterSnapshot here, and RegisterSnapshot plus
PushActiveSnapshot().

Note that UnregisterSnapshot() also updates MyProc->xmin through
SnapshotResetXmin, so that should be one less concern about correcting
xmin invalidations.

+    PopActiveSnapshot();
+
+    sscan->rs_snapshot = InvalidSnapshot; /* just to be tidy */
+    Assert(!HaveRegisteredOrActiveSnapshot());
+    InvalidateCatalogSnapshot();
+
+    /* The goal of snapshot reset is to allow horizon to advance. */
+    Assert(!TransactionIdIsValid(MyProc->xmin));
+#if USE_INJECTION_POINTS
+    /* In some cases it is still not possible due xid assign. */
+    if (!TransactionIdIsValid(MyProc->xid))
+        INJECTION_POINT("heap_reset_scan_snapshot_effective", NULL);
+#endif
+
+    PushActiveSnapshot(GetLatestSnapshot());
+    sscan->rs_snapshot = GetActiveSnapshot();

I think it's safer to do things in this order:

old_snap = sscan->rs_snapshot;
new_snap = RegisterSnapshot(GetLatestSnapshot());
PopActiveSnapshot();
PushActiveSnapshot(new_snap);
sscan->rs_snapshot = new_snap;
UnregisterSnapshot(old_snap);

This avoids clearing MyProc->xmin, it only increases it if the value
actually changes.

The "no registered snapshots" issue extends to various other pieces of
code, that'll all need to be updated accordingly to make sure they
actually register their snapshots, so that other code which does
correctly handle snapshots doesn't accidentally lose track of the
backend's xmins.

+ heap_reset_scan_snapshot((TableScanDesc) scan);

I don't think this part makes much sense. HeapTableScanDesc contains a
TableScanDesc at offset 0, so the cast itself is safe, but either
heap_reset_* should be table_reset_* (and live in tableam.c), or
accept a HeapTableScanDesc.

+++ b/src/backend/optimizer/plan/planner.c
+    /* Set ActiveSnapshot since functions in the indexes may need it */
+    if (!ActiveSnapshotSet())
+    {
+        PushActiveSnapshot(GetTransactionSnapshot());
+        need_pop_active_snapshot = true;
+    }

Shouldn't this be called exclusively from inside CREATE INDEX
commands, which should have an active snapshot when it starts calling
into index operations? The whole need_pop_active_snapshot idea seems
like it fixes the wrong issue.

+++ b/src/backend/utils/misc/guc_parameters.dat
+  variable => 'concurrent_index_reset_snapshot_every_n_pages',

I'm not fully convinced that this is the right way to do this.
Some pages may take much longer to process than others (e.g. TOAST
pages are not accounted for, a huge gin pending list, ...), so I think
a timer will make more sense. You can test if your snapshot has aged
with xactCompletionCount (currently not an atomic integer, so requires
ProcArrayLock, but a little bit of effort would fix that [0]/messages/by-id/CAEze2Wjj5LPNpuq6fNy-wv552wbk61dGRJ52NdV+Wddq0Uf33A@mail.gmail.com), and
reset your baseline time if it hasn't changed yet to avoid resetting
snapshots if no transaction has committed since you first acquired the
snapshot. Then you can reset the snapshot every X milliseconds after
we need to update the snapshot, rather than assuming that page counts
are a good (and safe) approximation of snapshot xmin holdback delay.

+++ b/src/backend/catalog/index.c
-    /* This had better make sure that a snapshot is active */
-    Assert(ActiveSnapshotSet());
+    Assert(!TransactionIdIsValid(MyProc->xmin));
+    Assert(!TransactionIdIsValid(MyProc->xid));

I think you'll have to find a better solution than "don't hold a
snapshot, unless". We should always be holding a snapshot in this scan
phase, and just change out which snapshot that is every once in a
while. The invalidations of snapshots, and the assertion of a lack of
snapshots, at arbitrary points in the code seems extremely fragile,
and doesn't feel like a well thought-through design. If all index AMs
are required to implement changes to support this (like how all
builtin AMs have changed, except contrib/bloom), then I don't think
this will be a viable approach.

------

Comments on 0003:

+++ b/src/backend/access/brin/brin.c
+    reset_snapshot = isconcurrent && !IsolationUsesXactSnapshot();

(etc., across various AMs)

Why are index AMs so deeply involved in what should be
TableScan-internal behaviour? It seems like it shows it's the wrong
abstraction.

WaitForParallelWorkersToAttach

I don't like this getting shoe-horned into the generic
WaitForParallelWorkersToAttach. It doesn't make much sense to me to
modify this here, shouldn't a ConditionVariable and a shared counter
(number of successfully initialized backends), controlled by the
shared table scan infrastructure, be sufficient for this? Then the
primary can wait on that CV until the shared counter reaches
nworkers_launched, without changing the API for parallel contexts.

------

Comments on 0004:

I think this patch needs a lot more effort. I don't think that it
won't work, but it changes things around that it probably shouldn't
change (e.g. _bt_keep_natts()/_fast()), and there are various code
style issues, like the following:

+++ b/src/backend/access/nbtree/nbtsort.c
[...]
+            _bt_buildadd(wstate, state, itup, 0);
+            if (prev) pfree(prev);
+            prev = CopyIndexTuple(itup);

I'm also not super happy about the inconsistent use of
IndexBuildResetsSnapshots().

E.g., heapam_handler.c disables reset_snapshots when
is_system_catalog, but no index AM code that tests
IndexBuildResetsSnapshots agrees with that. BtSpool now has
unique_dead_ignored, and _bt_leafbuild() gets a new effectively-unused
parameter reset_snapshots that approximately mirrors the value of the
field.

Either way, I don't like what happened in this patch. I think it'll at
least need a better solution to schedule the required IO - random IOs
shouldn't be the solution, and reduce its changes on hot paths like
_bt_keep_natts()/_fast().

Kind regards,

Matthias van de Meent
Databricks (https://www.databricks.com)

[0]: /messages/by-id/CAEze2Wjj5LPNpuq6fNy-wv552wbk61dGRJ52NdV+Wddq0Uf33A@mail.gmail.com

#11Mihail Nikalayeu
mihailnikalayeu@gmail.com
In reply to: Matthias van de Meent (#10)
Re: Resetting snapshots during the first phase of [CREATE |RE]INDEX CONCURRENTLY

Hello!

Here's my long-overdue review of this patchset. I've reviewed all but
patch 0001, as I assume that patch to not get committed.

Thanks for the review! Sorry for the late reply. I have reworked much
of the patch.

+ * - isolation level is not REPEATABLE READ/SERIALIZABLE (those keep a
+ *   registered transaction snapshot)

This seems strange to me - with R/CIC we know we're a top-level
command that outlives every transaction that touches the index's
table, so why do we suddenly care about serializability?

REPEATABLE READ and SERIALIZABLE keep a registered transaction snapshot.
That snapshot keeps xmin from advancing, even if we replace the active
snapshot. SnapshotRotationDue() now skips rotation in these modes.

+ InvalidateCatalogSnapshot();

I see this sprinkled around in various places that don't directly do
any other snapshot management -related things, nor do they seem to
handle much related to catalog content management. Why are they
sprinkled around those places, and not as part of the main scan
snapshot management? It's not just in brin.c, but also other AMs,
like access/hash/hash.c, which doesn't have *any* other modifications.

Moved this into RotateSnapshot(). The cached catalog snapshot can also
keep xmin from advancing. We release it when we replace the scan snapshot.

Snapshots MUST be registered before you can use them. It is inherently
unsafe to not register snapshots you're going to use, so please use
UnregisterSnapshot here, and RegisterSnapshot plus
PushActiveSnapshot().

The "no registered snapshots" issue extends to various other pieces of
code, that'll all need to be updated accordingly to make sure they
actually register their snapshots, so that other code which does
correctly handle snapshots doesn't accidentally lose track of the
backend's xmins.

Fixed as you suggested. RotateSnapshot() first registers the new
snapshot. It then pops the old snapshot, pushes the new one, and removes
the extra registration. xmin stays valid through all these steps.

Shouldn't this be called exclusively from inside CREATE INDEX
commands, which should have an active snapshot when it starts calling
into index operations? The whole need_pop_active_snapshot idea seems
like it fixes the wrong issue.

Agreed, removed need_pop_active_snapshot.

+++ b/src/backend/utils/misc/guc_parameters.dat
+  variable => 'concurrent_index_reset_snapshot_every_n_pages',

I'm not fully convinced that this is the right way to do this.
Some pages may take much longer to process than others (e.g. TOAST
pages are not accounted for, a huge gin pending list, ...), so I think
a timer will make more sense.

Changed to concurrent_index_reset_snapshot_interval, default 100ms.
The code checks the time at safe points. It resets the snapshot when
the interval has passed. A reset can therefore happen later than 100ms.

I think you'll have to find a better solution than "don't hold a
snapshot, unless". We should always be holding a snapshot in this scan
phase, and just change out which snapshot that is every once in a
while. The invalidations of snapshots, and the assertion of a lack of
snapshots, at arbitrary points in the code seems extremely fragile,
and doesn't feel like a well thought-through design.

The build now holds an active snapshot at all times. Snapshot replacement
and its checks are in snapmgr.c.

If all index AMs are required to implement changes to support this
(like how all builtin AMs have changed, except contrib/bloom), then
I don't think this will be a viable approach.

An AM enables this feature by setting amcanresetsnapshot. AMs that do
not set this flag keep the old behavior. bloom now sets this flag too.

GIN and BRIN need extra changes. They now fetch external TOAST data
before keeping values in memory for later use. Those values remain
valid after a snapshot reset.

AMs can also call index_build_rotate_snapshot() after the heap scan.
They call it at safe points, mostly near CHECK_FOR_INTERRUPTS().
It uses the same time interval.

Sorting and intermediate merges inside tuplesort still do not rotate
snapshots.

WaitForParallelWorkersToAttach

I don't like this getting shoe-horned into the generic
WaitForParallelWorkersToAttach. It doesn't make much sense to me to
modify this here, shouldn't a ConditionVariable and a shared counter
(number of successfully initialized backends), controlled by the
shared table scan infrastructure, be sufficient for this? Then the
primary can wait on that CV until the shared counter reaches
nworkers_launched, without changing the API for parallel contexts.

Done that way. The condition variable and counter are now in the shared
scan descriptor. The leader keeps its initial snapshot until all workers
have restored theirs. The WaitForParallelWorkersToAttach() API is unchanged.

Either way, I don't like what happened in this patch.

Reworked this part.

I think it'll at
least need a better solution to schedule the required IO

It now works like this:

1) Sorting has a heap-fetch budget. These fetches let us report some
duplicate keys early.

2) _bt_load() has a separate heap-fetch budget. When no budget remains,
further entries with the same key are left out of the index.
Validation inserts any surviving tuples and checks uniqueness.

Both budgets use index_build_duplicate_check_scale_factor, default
0.05 (not measure).

An entry is also left for validation if a conflicting row is being
deleted or updated to avoid waiting for a transaction (to avoid a
false positive conflict).

One possible next step is to collect duplicate candidates in batches
and prefetch their heap pages using ReadStream
(or better leave them for STIR scan in the future - it uses ReadStream
over sorted tids).

Most tests were written with AI assistance. I have not reviewed them
closely yet.
Also, the latest commit is not fully reviewed, as it mostly shows the concept.

Best regards,
Mikhail.

Attachments:

t53098_11
v7-0007-Reset-snapshots-after-the-heap-scan-in-concurrent.patchapplication/octet-stream; name=v7-0007-Reset-snapshots-after-the-heap-scan-in-concurrent.patchDownload+318-40
v7-0004-Allow-snapshot-resets-in-concurrent-BRIN-builds.patchapplication/octet-stream; name=v7-0004-Allow-snapshot-resets-in-concurrent-BRIN-builds.patchDownload+242-8
v7-0005-Allow-snapshot-resets-in-parallel-concurrent-inde.patchapplication/octet-stream; name=v7-0005-Allow-snapshot-resets-in-parallel-concurrent-inde.patchDownload+228-83
v7-0003-Allow-snapshot-resets-in-concurrent-GIN-builds.patchapplication/octet-stream; name=v7-0003-Allow-snapshot-resets-in-concurrent-GIN-builds.patchDownload+16-6
v7-0006-Allow-snapshot-resets-in-concurrent-unique-index-.patchapplication/octet-stream; name=v7-0006-Allow-snapshot-resets-in-concurrent-unique-index-.patchDownload+1251-94
v7-0002-Periodically-reset-snapshots-in-concurrent-index-.patchapplication/octet-stream; name=v7-0002-Periodically-reset-snapshots-in-concurrent-index-.patchDownload+737-39
v7-0001-Add-stress-tests-for-concurrent-index-builds.patchapplication/octet-stream; name=v7-0001-Add-stress-tests-for-concurrent-index-builds.patchDownload+429-1
#12Mihail Nikalayeu
mihailnikalayeu@gmail.com
In reply to: Mihail Nikalayeu (#11)
Re: Resetting snapshots during the first phase of [CREATE |RE]INDEX CONCURRENTLY

Hello!

Just a minor fix: the budget for IO for uniqueness checks is set to a
minimum of 1000.

Best regards,
Mikhail.

Attachments:

t53098_12
v8-0001-Add-stress-tests-for-concurrent-index-builds.patchtext/x-patch; charset=US-ASCII; name=v8-0001-Add-stress-tests-for-concurrent-index-builds.patchDownload+429-1
v8-0005-Allow-snapshot-resets-in-parallel-concurrent-inde.patchtext/x-patch; charset=US-ASCII; name=v8-0005-Allow-snapshot-resets-in-parallel-concurrent-inde.patchDownload+228-83
v8-0002-Periodically-reset-snapshots-in-concurrent-index-.patchtext/x-patch; charset=US-ASCII; name=v8-0002-Periodically-reset-snapshots-in-concurrent-index-.patchDownload+737-39
v8-0004-Allow-snapshot-resets-in-concurrent-BRIN-builds.patchtext/x-patch; charset=US-ASCII; name=v8-0004-Allow-snapshot-resets-in-concurrent-BRIN-builds.patchDownload+242-8
v8-0003-Allow-snapshot-resets-in-concurrent-GIN-builds.patchtext/x-patch; charset=US-ASCII; name=v8-0003-Allow-snapshot-resets-in-concurrent-GIN-builds.patchDownload+16-6
v8-0006-Allow-snapshot-resets-in-concurrent-unique-index-.patchtext/x-patch; charset=US-ASCII; name=v8-0006-Allow-snapshot-resets-in-concurrent-unique-index-.patchDownload+1260-88
v8-0007-Reset-snapshots-after-the-heap-scan-in-concurrent.patchtext/x-patch; charset=US-ASCII; name=v8-0007-Reset-snapshots-after-the-heap-scan-in-concurrent.patchDownload+318-40
#13Alvaro Herrera
alvherre@kurilemu.de
In reply to: Matthias van de Meent (#10)
Re: Resetting snapshots during the first phase of [CREATE |RE]INDEX CONCURRENTLY

On 2026-Aug-03, Matthias van de Meent wrote:

Here's my long-overdue review of this patchset. I've reviewed all but
patch 0001, as I assume that patch to not get committed.

See
/messages/by-id/af3oWkvS9K83UqmK@alvherre.pgsql
wherein I proposed to add a PG_TEST_EXTRA variable that would be
something like
stress_concurrently=1
which runs the test for a short time (I used 6 seconds), or
stress_concurrently=0 to disable the test completely, or larger positive
integers to scale the test up in duration and number of tuples.

With that setup, we could have tests of this nature for all the
CONCURRENTLY operations, all controllable via the same mechanism.

I'm not really sure of the wisdom of this, but having a test that runs
in pretty much every buildfarm animal and on every test run makes sense
to me, with an easy mechanism to disable it when it gets bothersome
(valgrind, cache clobber, etc). We could have one or two specific
buildfarm members that would run them for longer.

--
Álvaro Herrera Breisgau, Deutschland — https://www.EnterpriseDB.com/
[…] indem ich in meinem Leben oft an euch gedacht, euch glücklich zu machen. Seyd es!
A menudo he pensado en vosotros, en haceros felices. ¡Sedlo, pues!
Heiligenstädter Testament, L. v. Beethoven, 1802
https://de.wikisource.org/wiki/Heiligenstädter_Testament

#14Alvaro Herrera
alvherre@kurilemu.de
In reply to: Mihail Nikalayeu (#12)
Re: Resetting snapshots during the first phase of [CREATE |RE]INDEX CONCURRENTLY

Hello,

I'm not really sure that we want need to have a setting for how
frequently to reset the snapshot. For testing I agree that it's okay to
make it very frequent, but otherwise I think we'd rather the user not
have to be concerned with a setting for this. Just make it happen on a
regular enough basis, so that the user can forget it.

100ms sounds a bit too frequent for my taste. But why do we need to
measure it in wall-clock time? In the REPACK proposed patches, Antonin
does it every 1024 pages (the value to be tuned, per the XXX comment in
the patch). I think a page-measured operation is good enough, and maybe
something like once every 128 MB (so every 16k pages?)

Thanks

--
Álvaro Herrera Breisgau, Deutschland — https://www.EnterpriseDB.com/
"We have labored long to build a heaven, only (Prof. Milton Glass)
to find it populated with horrors" (Watchmen, Alan Moore)