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

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

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

От:
Mihail 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].

HISTORY

In 2021 Álvaro proposed [1] and committed [2] 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]. As a result, the feature was reverted [4].

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] - 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] and [7]).

- 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] (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]: https://www.postgresql.org/message-id/flat/CAEze2Wg6d2M8hop4uwdQXeH-YkOmEHyqp83%2BaE7vEzKdmu7w-A%40mail.gmail.com#b5dbefccc537167bc8c1efe0ad063491
[1]: https://www.postgresql.org/message-id/flat/20210115142926.GA19300%40alvherre.pgsql#0988173cb0cf4b8eb710a6cdaa88fcac
[2]: https://github.com/postgres/postgres/commit/d9d076222f5b94a85e0e318339cfc44b8f26022d
[3]: https://www.postgresql.org/message-id/flat/20220524190133.j6ee7zh4f5edt5je%40alap3.anarazel.de#1781408f40034c414ad6738140c118ef
[4]: https://github.com/postgres/postgres/commit/e28bb885196916b0a3d898ae4f2be0e38108d81b
[5]: https://www.postgresql.org/message-id/flat/CAEze2WgW6pj48xJhG_YLUE1QS%2Bn9Yv0AZQwaWeb-r%2BX%3DHAxU_g%40mail.gmail.com#b3809c158de4481bb1b29894aaa63fae

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

От:
Mihail Nikalayeu <mihailnikalayeu@gmail.com>
Дата:

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

От:
Mihail Nikalayeu <mihailnikalayeu@gmail.com>
Дата:
Вложения:
Hello, everyone!

Rebased.

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

От:
Mihail Nikalayeu <mihailnikalayeu@gmail.com>
Дата:
Вложения:
Rebased.

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

От:
Álvaro Herrera <alvherre@kurilemu.de>
Дата:
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/


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

От:
Mihail Nikalayeu <mihailnikalayeu@gmail.com>
Дата:
Вложения:
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.

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

От:
Mihail Nikalayeu <mihailnikalayeu@gmail.com>
Дата:
Вложения:
Hello!

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

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

От:
Mihail Nikalayeu <mihailnikalayeu@gmail.com>
Дата:
Вложения:
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.

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

От:
Mihail Nikalayeu <mihailnikalayeu@gmail.com>
Дата:
Вложения:
Some small fixes around.

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

От:
Mihail Nikalayeu <mihailnikalayeu@gmail.com>
Дата:
Вложения:
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.

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

От:
Mihail Nikalayeu <mihailnikalayeu@gmail.com>
Дата:
Вложения:
Hello!

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

Best regards,
Mikhail.

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

От:
Álvaro Herrera <alvherre@kurilemu.de>
Дата:
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
https://postgr.es/m/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


FAQ