Skip to content

fix(storage-postgres): serve each table in turn in the GSI queue workers - #542

Open
LeeroyHannigan wants to merge 20 commits into
mainfrom
fix/476-pg-gsi-queue-cross-table-stall
Open

LeeroyHannigan wants to merge 20 commits into
mainfrom
fix/476-pg-gsi-queue-cross-table-stall

Conversation

@LeeroyHannigan

@LeeroyHannigan LeeroyHannigan commented Oct 25, 2026 •

Copy link
Copy Markdown
Collaborator

Changes since the last review

Five commits follow cc02460, the head that hitesh96db reviewed on 23 Nov:

  • 59a7a88 merges origin/main at a417b2f, feat(wasm): [Add WebAssembly browser support for ExtendDB #1009 included. The merge has no conflict.
  • 95e68ae builds the GSI queue tests on the scratch fixture in tests/common/stream_disable_fixture.rs and deletes the copy of it from tests/gsi_queue_support/mod.rs. With EXTENDDB_TEST_PG_REQUIRED set and no connection string, the four GSI queue tests now fail instead of reporting a skip.
  • b297123 sends the per-table claim unprepared (.persistent(false)). It adds a_small_tables_claim_reads_no_row_another_table_queued_ahead, which counts the reads of gsi_pending_pkey, and fixes the plan comment of migration 13.
  • 6cc0293 puts the 1.0.0 text of the upgrade manual and seven sample outputs back to migration 12. The queue entry of the manual is now v1.1.0: PostgreSQL: the GSI propagation queue serves tables in turn, above the v1.0.0 entries.
  • 9bee8d9 merges origin/main at d3b2a41. fix(metrics): bound latency segment memory by summing into fixed time buckets #398 added its v1.1.0 entry to docs/manuals/07-upgrade-manual.md where this branch adds its own. The merge keeps both entries, main's first.

This description now says Refs #476. It states the one-batch bound and the plan condition of the claim figures, and it gives the counts at 6cc0293. The DescribeTable bullet and the notes on the rebase onto #401 are gone, and it fixes the list of PRs that claim migration 13.

The message of fa8290f still ends with Closes #476, and the squash message lists the commit messages. A squash merge by hand can delete that line from the squash message. A merge through the queue, a merge commit or a rebase merge puts the line on main, and #476 then closes and needs reopening.

What

Each batch of a GSI queue worker now lists the tables with a ready row in the worker's partition. Then it claims each table's oldest ready row in turn (gsi_rotation.rs, TableRotation). Within a table the claims stay in id order, so per-key FIFO holds (a key's rows are in one table and one partition). The worker carries the table it served last from batch to batch. With more than BATCH_SIZE (100) tables that have ready rows in one partition, the worker serves each one once per pass. The tail does not wait for the head to empty. The partition hash is unchanged, so no drain or operator step follows from the claim order.

The worker lists the tables once per batch. When a table's first row becomes ready after a batch's listing, the table waits for the rest of that batch (at most 100 applies). The next listing serves it. another_tables_backlog_does_not_delay_this_tables_rows ran twice at 6cc0293, in a dev build on PostgreSQL 16.15, at a host load average of about 40 on 16 cores. With a 300 ms propagation delay, table B's 8 rows applied 2.2 s and 3.9 s after the writes. hitesh96db measured 0.55 to 0.62 s on a quiet host.

The claim loop moved from gsi_queue.rs to gsi_rotation::process_batch, and it keeps the parking of #401. When a writer holds the base row of a secondary index row, the worker skips that row for a while (PARK_FOR). The next claims of that table exclude its id.

The listing returns only tables whose lowest-id row is ready. The enqueue floors ready_at at the partition's current maximum. So within a partition ready_at does not decrease with id, and a table's first row carries its earliest ready_at. Only two writers that read the floor before either one commits can land a later id with an earlier ready_at. That delays a table's listing by at most one jitter when one delay is in force. If an operator sets a per-index propagation_delay_ms above the default, it delays the listing by the difference between the two rows' delays instead. Nothing writes that column today. Without this filter, a partition that held N tables inside their delay cost N claim transactions per wakeup.

Catalog migration 13, gsi_pending_table_claim (data_migrations/0013_gsi_pending_table_claim.sql), adds idx_gsi_pending_table_claim on gsi_pending (worker_partition, table_id, id). The per-table claim walks it to the first ready row. The listing is a recursive probe over it, one index entry per table with rows. Planned with its table id, the claim takes 0.02 to 0.04 ms whatever the backlog. The worker sends the claim unprepared (.persistent(false)), so PostgreSQL plans it with the table id every time. Kept prepared, the claim switched to a generic plan from a connection's sixth execution. That plan walked gsi_pending_pkey from the lowest id, so a small table's claim behind 1,000,000 queued rows of another table took 168 ms on PostgreSQL 16.15. Without the index the per-table claim sorted the partition's ready rows (drain fell from about 1,600 to about 240 rows/s in the first measurement). The hold check is bound to the claimed table (NOT EXISTS ... WHERE h.table_id = $2), evaluated once per claim in the same snapshot.

Why

#476 reports that, on the PostgreSQL backend, another table's GSI build left a table's 21 queued index rows unapplied for 38 s. It names two candidate causes: queue partitions shared across tables, and connection pool occupancy. The reproduction on main (744ea291) sampled pg_stat_activity and per-table gsi_pending counts every 2 s.

The issue's own shape does not stall on main. UpdateTable builds the GSI inside the request and enqueues nothing. The build holds one of the pool's twenty connections. So the 21 rows apply 1.96 s after the last write with the build running, and 2.14 s after it with nothing else running. What held the issue's rows on #401's head is not established. That head's build queues rows only for writes to the table it builds, and the run wrote none. hitesh96db measured the issue's shape at 2.0 s on main (d61f8af2, which includes #401) and on this branch.

On main, a backlog stalls another table's rows. With 50,000 BatchWriteItem puts to table A queued, 21 puts to table B apply 9 to 11 s after the last write. Each worker claims ORDER BY id LIMIT 1 over its whole partition, and all tables share the partitions. So the worker applies every row A enqueued earlier before B's first row. B's latency is A's backlog divided by the drain rate (about 1,500 rows/s, so 50,000 rows is about 34 s, the magnitude the issue measured). The samples show zero ungranted locks, twenty idle connections and no batch error. Everything applies when the other table's work ends, as in the issue.

This PR fixes the backlog shape. #476 stays open for the original report.

Refs #476

Operator step

Stop the servers, run extenddb migrate --config extenddb.toml --yes, start the servers. Migration 13 applies on PostgreSQL only, and SQLite, Cassandra and MongoDB record it as not applicable. migrate builds the index with the servers stopped, at about 1.7 s per million queued rows (3.45 s at 2,000,000 rows). It runs CREATE INDEX IF NOT EXISTS, which takes SHARE on gsi_pending for the build. A server of this release refuses a catalog while migration 13 is pending, as it does for every pending migration. The upgrade manual carries the entry, v1.1.0: PostgreSQL: the GSI propagation queue serves tables in turn.

Measurements

This table gives the claim plan on PostgreSQL 16.15 (pgvector/pgvector:pg16), with this branch's migrations. The queue held 1,000,000 ready rows of table A and 20 of table B in partition 0. After ANALYZE, one session ran B's claim 7 times, and the table shows the 7th:

How the claim is sent Plan for B's claim Time
prepared, plan_cache_mode = force_custom_plan idx_gsi_pending_table_claim 0.025 ms
prepared, force_generic_plan gsi_pending_pkey, 1,000,000 rows removed by filter 166.5 ms
prepared, auto (the default), 5 custom plans then generic gsi_pending_pkey, 1,000,000 rows removed by filter 167.8 ms
unnamed, as .persistent(false) sends it, auto idx_gsi_pending_table_claim 0.034 ms

The figures below are from before b297123, with the claim prepared. Single pgvector/pgvector:pg16 container on one host, index_propagation_delay_ms = 2000, release binaries, from the last write on table B to its rows applied:

shape main this branch
nothing else running 2.13 to 2.14 s 1.83 to 2.14 s
A's 50,000-row backlog queued 9.13 to 10.97 s 2.46 to 3.11 s
the issue's UpdateTable build shape 1.96 s (no stall) 2.32 s, build time 8.9 s to 9.8 s

With tables inside their delay, a batch runs one listing statement and no claims. That cost 0.49 ms for 10 tables, 1.26 ms for 100 and 4.5 ms for 500. On main, a batch makes one claim, and that claim takes 0.3 to 0.4 ms each time. Before the ready-only listing, the same shapes cost 4.8, 29.7 and 164 ms (one claim transaction per idle table).

Ten runs in the same hour alternated the binaries on isolated 36,000 to 40,000 row backlogs. The drain rate was 770 to 2,000 rows/s with the change and 938 to 1,902 without. The two ranges are the same within the run-to-run spread. The apply is one transaction per row and WAL-bound, with WALWrite and WALSync waits in every sample. Planned with its parameters, the claim took 0.02 to 0.04 ms with both binaries in every run. Every index count equalled its table in every run, in two-, three- and fifty-table shapes.

Not in this PR

  • The ready_at floor is still partition-wide across tables. With one global delay its effect is bounded by one delay. It becomes a stall only if rows carry different delays, and nothing sets the per-index propagation_delay_ms column today. Scoping the floor to (table_id, worker_partition) needs an index leading on table_id for the MAX.
  • The worker lists the tables once per batch, so a table that becomes ready during a batch waits up to 100 applies (see What). A second listing when the rotation wraps, or a time cap on a batch, would be a second change to the worker loop. On main the same rows wait for the whole backlog.
  • The idle path's next_ready_wait keeps the correlated hold anti-join (13 ms on a 40,000-row queue, once per empty batch).
  • The drain rate is bounded by one transaction per row (about 400 rows/s per worker here). A burst of writes still queues at write speed and drains at that rate.
  • Replacing "a table whose claim finds nothing leaves the rotation" with the break of main passes every test. It changes only the drain rate while a held table or a concurrently drained table is listed. The test module comment records it as an accepted gap.

Merging with main and other PRs

Main replaced the PostgreSQL migration lists with the migration runner and its registry of numbered migrations, so the claim index is migration 13. Main's server refuses to serve while a migration is pending, so the branch has no startup check for the index. The queue test helpers upsert the two delay settings, which the baseline of main does not seed.

Release 1.0.0 shipped from c2e9a32 without this branch, and it carries migrations 1 to 12. The 1.0.0 text of the upgrade manual and the sample outputs stay at 12. The queue entry says what migration 13 changes for a rollback to 1.0.0.

Open PRs #368 and #874 also claim migration 13, and #934 claims 10. Whichever merges later renumbers. Against #368 and against #874, this branch adds conflicts in crates/storage/src/migrations/registry.rs, the four backends' migrations/mod.rs, CONTRIBUTING.md and docs/manuals/07-upgrade-manual.md.

#1166 (sqlx 0.9.1) gets one new conflict from this branch, in crates/storage-postgres/src/gsi_queue.rs. #1166 wraps the claim loop's SET LOCAL lock_timeout statement in sqlx::AssertSqlSafe, and this branch moves that loop to gsi_rotation.rs. The resolution keeps the move and puts the wrap on the statement in gsi_rotation.rs, in whichever PR merges second. sqlx 0.9.1 also refuses a format! string in sqlx::query and sqlx::query_scalar, so enqueue_rows and index_rows in tests/gsi_queue_support/mod.rs need the same wrap, with no textual conflict to show it. QueryAs::persistent exists in sqlx 0.9.1.

Testing done

  • tests/gsi_queue_fairness.rs (3 tests):
    • another_tables_backlog_does_not_delay_this_tables_rows puts a 20,000-row backlog for table A (whose table_id sorts first) and eight writes to table B on the queue. B's rows apply while more than three quarters of A's backlog is still queued. At 6cc0293, 19,576 and 19,586 of 20,000 were still queued, and 0 under the old claim.
    • a_held_tables_rows_stay_queued_until_the_hold_is_removed: a held table's rows stay queued with zero index rows until the test removes the vector_index_holds row, and then apply.
    • a_small_tables_claim_reads_no_row_another_table_queued_ahead (new): A's 20,000 rows fill partition 0, and the test runs ANALYZE. 300 of A's rows apply first, so a prepared claim reaches its generic plan on the pool's connections. Then the test holds A, and 8 rows of table B apply behind A's rows. The test reads idx_tup_read of gsi_pending_pkey from pg_stat_user_indexes before and after, and requires the growth to be under a quarter of A's held rows. With the claim sent unprepared, it counted 8 (B's deletes) in 3 runs. With the claim kept prepared, it counted 177,254, 177,271 and 177,299 behind 19,692 to 19,697 held rows, and failed.
  • tests/gsi_queue_many_tables.rs (1 test): 104 tables have rows in one partition. Each of the hundred that sort first has 100 rows, and each of the four that sort last has 5. The tail tables' rows apply while more than three quarters of the head rows are still queued (9,499 of 10,000 at 6cc0293).
  • gsi_rotation unit tests (9) cover the ring order, the cursor placement and wrap, and a cursor that names a table no longer listed. One runs six tables in batches of four over three batches.
  • tests/gsi_queue_support/mod.rs uses the fixture's Scratch, base_conn, scratch and table_input. It keeps what the queue tests need beyond the fixture. Its scratch starts the engine's queue workers, table_with_gsi adds a GSI to the fixture's table, and put writes an item with the GSI key. set_delay_ms sets the propagation delay, template_row and enqueue_rows seed the queue directly, and pending, pending_in and index_rows count queue and index rows. With EXTENDDB_TEST_PG_REQUIRED=1 and no connection string, each of the four GSI queue tests fails with the fixture's message.
  • gsi_online_build::queue_rows_applied_out_of_order_converge_to_the_item holds the older queue row with FOR KEY SHARE from an outside transaction and makes both rows due, in place of making only the newer row due. This branch lists a table only when its lowest-id row is due, so the newer row alone was never claimed. The changed test passes on the code of main as well.
  • The migration tests of main run migration 13. migrations_runs.rs applies the latest id again after forget, and migrations_released.rs compares each upgraded released catalog with a fresh install. The CI schema step checks a fresh install against docs/schema/postgres.txt, which lists the index. The MongoDB tests that pin the migration set expect 13 migrations.
  • Controls, each a change to gsi_rotation.rs with the tests kept. At cc02460, the claim without AND table_id = $2 and the cursor ignored each failed the test written for it. In an earlier round, before a merge with main, served() as a no-op and the hold predicate removed did the same. At 6cc0293, the claim kept prepared fails a_small_tables_claim_reads_no_row_another_table_queued_ahead (2 of 2 runs).
  • The PostgreSQL storage-level CI job runs every test target of the crate (--tests), so it runs the new test with no workflow change.

Counts at 6cc0293, against PostgreSQL 16.15 (pgvector/pgvector:pg16, the image of CI's job) on 127.0.0.1, with EXTENDDB_TEST_PG_REQUIRED=1 and EXTENDDB_EXPECT_VECTORS=1 as in CI's job, in the dev profile:

  • cargo test -p extenddb-storage-postgres --lib, with no connection string: 96 passed.
  • cargo test -p extenddb-storage-postgres --tests --no-fail-fast, the command of the run-postgres-storage-tests job, which CI builds with --release: 42 targets, 491 passed, 2 ignored, 5 failed. The five are three store_identity tests in backup_restore.rs and two tests in catalog_nul_backup_jobs.rs, files this branch does not change. Each fails because the filesystem backup store refuses a root whose parent directory another user owns. Every temporary directory on the test host has such a parent. The first invocation stopped during table_snapshot, so table_snapshot, twi_conflict and vector_control_plane ran in a second invocation of the same command with --test.
  • cargo +1.97.0 fmt --all -- --check, cargo +1.97.0 clippy -p extenddb-storage-postgres --all-targets -- -D warnings, the same with --features extenddb-engine/backup-test-hooks, and cargo +1.91.1 check -p extenddb-storage-postgres --all-targets: clean. cargo +1.97.0 clippy -p extenddb-storage-postgres --all-targets -- -W clippy::pedantic warns on lines this branch adds, for example the worker_id as i32 binds in gsi_rotation.rs and the usize to i64 casts in the tests. So the Clippy box is unticked.
  • python3 -m pytest --collect-only -q collects 6660 tests in tests/ and 672 in tests/python, with no error.
  • Files added or grown stay under 600 lines: gsi_rotation.rs 394, gsi_queue.rs 569 (the claim loop moved out), gsi_queue_fairness.rs 291, gsi_queue_support/mod.rs 211, gsi_queue_many_tables.rs 130. lib.rs (1,061 lines), gsi_online_build.rs (1,274) and the upgrade manual (1,315) were over 600 lines on main and grew by 1, 7 and 28 lines. No dependency change.

Checklist

  • I have read CONTRIBUTING.md
  • All tests pass (cargo test --workspace)
  • Code is formatted (cargo fmt --check)
  • Clippy is clean (cargo clippy -- -W clippy::pedantic)
  • I have added or updated tests for new functionality
  • I have updated documentation if behavior changed
  • Breaking changes are noted below (if any)
  • If this changes the wire protocol, Storage trait, auth model, on-disk
    format, or public CLI surface, an RFC has been accepted or is linked
    below. Otherwise, an ADR captures the decision (link below).

ADR / RFC: n/a. Migration 13 adds an index to the PostgreSQL data database and changes no stored row.

Breaking changes

  • Migration 13, gsi_pending_table_claim, is breaking on PostgreSQL. A server of this release refuses a PostgreSQL catalog while migration 13 is pending, so an upgrade runs extenddb migrate --config extenddb.toml --yes with the servers stopped. After the migration, a 1.0.0 server refuses the catalog, so a rollback to 1.0.0 restores both databases from the backups taken before the upgrade. SQLite, MongoDB and Cassandra record the migration as not applicable, and 1.0.0 serves their migrated catalogs with a warning.
  • The order of the PostgreSQL GSI propagation queue changes. A worker claimed the lowest id across its partition, so the rows of all tables in a partition applied in id order. It now claims each table's oldest ready row in turn, so a table's rows can apply before rows that another table queued earlier. Within a table the order is unchanged.

By submitting this pull request, I confirm that my contribution is made under
the terms of the Apache License 2.0 and I agree to the Developer Certificate of
Origin (DCO). See CONTRIBUTING.md for details.

A queue worker claimed the lowest id across its whole partition. Partitions
are shared by every table, so a table's rows waited behind every row another
table had enqueued earlier: a 50,000 item bulk write to one table with an
asynchronous GSI put 21 writes to another table 9 to 11 s behind their 2 s
propagation delay, and the wait scales with the backlog. Pool occupancy,
the issue's other candidate, does not occur: a GSI build holds one of the
pool's twenty connections.

Each batch now lists the tables with a ready row in the partition and claims
each table's oldest ready row in turn, so a table's latency depends on its
own backlog. Within a table the claims stay in id order, which is what
per-key FIFO needs. The worker carries the table it served last from batch
to batch, so more than 100 tables with ready rows in one partition are all
served once per pass. The partition hash is unchanged.

Data migration 005 adds idx_gsi_pending_table_claim on (worker_partition,
table_id, id): the per-table claim walks it to the first ready row instead
of sorting the partition's ready rows, and the per-batch table listing is a
recursive probe over it that lists only the tables whose first row is ready
(4.5 ms per batch at 500 tables inside their delay; 0.3 ms with none). The
drain rate is the same as before within run-to-run spread on the test host
(ten runs: 770 to 2,000 rows/s with the change, 938 to 1,902 without; the
claim plan costs 0.02 to 0.04 ms on both). Apply with
extenddb migrate --yes; a server started without it logs a warning naming
the two slower plans and serves. The catalog version is unchanged.

Storage-level tests: a 20,000 row backlog for one table with eight writes to
a second table applying while more than three quarters of the backlog is
still queued; 104 tables' rows in one partition with the four sorting last
applied while more than three quarters of the others' rows are still queued;
a held table's rows staying queued until the hold is removed; and the
migration reported, applied and its index present on a database one
migration behind.

Closes #476
@LeeroyHannigan
LeeroyHannigan force-pushed the fix/476-pg-gsi-queue-cross-table-stall branch from ce1ccaa to fa8290f Compare October 30, 2026 09:51
@navareamol navareamol added the v1 Needed for the 1.0 release label Nov 3, 2026
@navareamol navareamol added this to the 1.0 milestone Nov 3, 2026
.github/workflows/integration.yml keeps the run-postgres-storage-tests job from main, which runs every test target. It adds the reasons from this branch why the GSI queue tests and the data migration test need direct access.

crates/storage-postgres/src/gsi_queue.rs keeps the catalog_json import from main and the gsi_rotation import from this branch.

The merge deletes crates/storage-postgres/src/migrations.rs, as main does: main replaced the migration lists with the migration runner. A later commit registers the claim index from this branch as migration 13.

crates/storage-postgres/tests/backup_restore.rs keeps the scratch setup from main, which migrates through the runner and so applies every registered migration.

The merge deletes crates/storage-postgres/tests/catalog_converge.rs, as main does. This branch only added its claim index file to the migration list of that test.

docs/manuals/07-upgrade-manual.md keeps the new entries from main and the GSI propagation queue entry from this branch.
…n 13

Main replaced the PostgreSQL migration lists with the migration runner and its registry of numbered migrations. This branch added the claim index as data migration 005 to the removed list, so the index had no migration to apply it.

The index is now migration 13, gsi_pending_table_claim, by the procedure in CONTRIBUTING.md:

- registry.rs gets the id. The PostgreSQL table applies it with a data body, kind Breaking and convergent, in the runner's transaction. SQLite, Cassandra and MongoDB record it as not applicable.
- The file is now data_migrations/0013_gsi_pending_table_claim.sql, without BEGIN and COMMIT, because the runner owns the transaction.
- docs/schema/postgres.txt lists the index.
- The places that name the latest migration now name 13. They are the MongoDB test that pins LATEST, the registry comment, the upgrade manual, the admin guide example and the sample outputs. The example in CONTRIBUTING.md moves to migration 14.
- The upgrade manual entry for the queue names migration 13. A server of this release refuses a deployment where a migration is pending, so the entry now says that for a skipped migrate step.
This branch logged a warning at startup when gsi_pending had no idx_gsi_pending_table_claim. The legacy runner let a server serve with a data migration not applied. On main a server refuses a deployment with a pending migration and prints the migrate command.

The commit removes claim_index_present, warn_if_claim_index_missing and its call in GsiQueue::spawn. The serve gate on main reports a skipped migrate step.

It also removes tests/data_migrations.rs. That test built a data database one migration behind through the legacy runner. It used the schema_history ledger, the legacy migration files, the catalog version and two bootstrapper calls, pending_data_migrations and run_data_migrations. Main has none of these. On main the runner applies migration 13 like every other file body. The integration job checks docs/schema/postgres.txt against a fresh install, and that file lists the index.
Main's migration 1 seeds no control_plane_delay_seconds row and no index_propagation_delay_ms row, so the UPDATE statements in gsi_queue_support changed nothing. CreateTable then inserted each table as CREATING under the default delay, and set_delay_ms left the propagation delay at its default. Both helpers now upsert the row, as the other storage-level tests on main do.
Migration 13 does not apply on MongoDB. The runner still records it. A fresh store gets a catalog ledger row for it with the outcome not_applicable. Each run reports a step (13, catalog) for it. These tests pin the migration set:

- migrations_fresh.rs, a_fresh_store_gets_every_migration_and_the_expected_definitions: the applied steps end with (13, catalog). The ids that do not apply are 3, 4, 7, 8, 9, 11 and 13. The catalog ledger outcomes end with (13, NotApplicable).
- migrations_fresh.rs, a_second_run_applies_nothing_and_reconverge_keeps_the_rows: the comment lists 13 among the ids that do not apply on MongoDB. The asserted list does not change, because a reconverge runs no migration that does not apply.
- migrations_fresh.rs, a_changed_checksum_a_newer_catalog_and_an_older_release_are_reported: the ledger row that stands for a later binary's migration moves from id 13 to 14. A fresh store now holds a row with id 13, so inserting another row with that id fails on the duplicate key.
- migrations_released.rs, every_released_catalog_upgrades_to_the_definitions_of_a_fresh_install: a released catalog has 14 pending steps, one for each of the 13 ids and one for the data store of migration 1.
- migrations_locks.rs, two_migrators_started_together_apply_once_and_the_other_finds_nothing: the migrator that runs applies the same 14 steps to the 0.1.12 fixture.
… support

GsiInput gained warm_throughput on main. The global secondary index literal in table_with_gsi sets it to None.
…ntry

The Current Status section of the upgrade manual already states that a server of this release refuses a catalog with pending migrations. The entries for migrations 9 to 12 do not repeat it. The GSI queue entry now follows them and ends after its operator step.
docs/manuals/07-upgrade-manual.md keeps the GSI propagation queue entry from this branch and the Cassandra replication warning entry from main (#909).
docs/manuals/07-upgrade-manual.md keeps the release names 0.1.14 and 0.1.15 from main in two paragraphs. It also keeps the text about migration 13 from this branch in the same paragraphs. That text gives the count of migrations as 1 to 13 and names the index that migration 13 adds.
crates/storage/src/migrations/registry.rs takes main's RELEASED_THROUGH of 12 and its comment, from the 0.1.15 release (#1069). Migration 13 of this branch is not released, so the bound stays at 12. docs/getting-started.md and docs/manuals/04-quickstart-setup-guide.md take version 0.1.15 from main and catalog migration 13 from this branch in the sample output.
docs/getting-started.md and docs/manuals/04-quickstart-setup-guide.md keep release 1.0.0 from main (#1107) and catalog migration 13 from this branch in their sample output. docs/manuals/07-upgrade-manual.md keeps the 1.0.0 paragraph and the two v1.0.0 entries that main adds. It also keeps the migration count of this branch in the next paragraph and its GSI queue entry after the v1.0.0 entries.
Main (#1107) wrote the 1.0.0 text of the upgrade manual for a release with no new catalog migration. This branch adds migration 13, gsi_pending_table_claim. Four sentences of main were then wrong in this tree:

- Current Status
- the opening of the General Upgrade Procedure
- the opening of the Rollback Procedure
- the rollback paragraph of the v1.0.0 key entry

They now say that an upgrade from 0.1.15 runs migrate --yes for migration 13. On SQLite, MongoDB and Cassandra the ledger records the migration as not applicable. That counts as additive, so 0.1.15 still starts on the migrated catalog with a warning. On PostgreSQL the migration is breaking. 0.1.15 refuses the catalog with exit status 4, and a rollback restores both databases from the backups.
docs/manuals/07-upgrade-manual.md keeps the migration 13 text of this branch in Current Status. Its Cassandra sentence takes the "many of its rows" correction of main (#1133). The General Upgrade Procedure keeps the migration 13 sentence of this branch in place of the "Up to date" sentence of main. On this branch an upgrade from 0.1.15 applies migration 13.
Release 1.0.0 shipped from main (#1133) without this branch. The four sentences that 2fc23a2 changed for migration 13 describe 1.0.0, which carries migrations 1 to 12. They are again the text of main:

- Current Status
- the opening of the General Upgrade Procedure
- the opening of the Rollback Procedure
- the rollback paragraph of the v1.0.0 key entry

The GSI queue entry of this branch now says what migration 13 changes for a rollback to 1.0.0. On PostgreSQL the migration is breaking, so 1.0.0 refuses the migrated catalog, and a rollback restores both databases. SQLite, MongoDB and Cassandra record it as not applicable, and 1.0.0 serves those catalogs with a warning.

@hitesh96db hitesh96db left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two changes are needed before approval, and I will approve once they are in. Both are about what the change claims, not about wrong results: nothing I ran shows a regression against main.

  1. The per-table claim scans the other table's rows under the default plan cache mode (Experiments 1 and 2, inline on gsi_rotation.rs).
  2. Closes #476: the issue's own shape does not stall on main or on this branch (Experiment 3).

Smaller items are inline: the batch boundary (Experiment 4), the upgrade manual's release labelling, the sample outputs, and the DescribeTable clause in "Not in this PR".

Setup. Measured 2026-11-20 at cc02460df (merges cleanly onto main d61f8af2), PostgreSQL 17.11 on macOS, debug build, default plan_cache_mode. The storage tests use this PR's gsi_queue_support helpers. Timings on a busy host vary; each figure below is a run I did, with repeats where noted. The probes are small test files built on those helpers, with the parameters stated; I can attach them.

Experiment 1 [Difference]: the claim plan for a small table in a partition another table dominates

psql -d postgres -c "CREATE DATABASE plan_probe"
for f in crates/storage-postgres/migrations/*.sql crates/storage-postgres/data_migrations/*.sql; do psql -d plan_probe -q -f "$f"; done
psql -d plan_probe -q <<'SQL'
INSERT INTO gsi_pending (table_id, worker_partition, old_item, new_item, index_context, ready_at)
SELECT 'aaaaaaaa-0000-4000-8000-000000000001', 0, NULL, '{"pk":{"S":"x"}}', '{}', now() - interval '10 s' FROM generate_series(1, 1000000);
INSERT INTO gsi_pending (table_id, worker_partition, old_item, new_item, index_context, ready_at)
SELECT 'bbbbbbbb-0000-4000-8000-000000000002', 0, NULL, '{"pk":{"S":"y"}}', '{}', now() - interval '1 s' FROM generate_series(1, 20);
ANALYZE gsi_pending;
SQL
psql -d plan_probe <<'SQL'
BEGIN;
SET LOCAL plan_cache_mode = force_custom_plan;   -- then force_generic_plan, then auto
PREPARE c(int, text, bigint[]) AS
  SELECT id, table_id, old_item, new_item, index_context FROM gsi_pending
  WHERE worker_partition = $1 AND table_id = $2 AND ready_at <= NOW() AND NOT (id = ANY($3))
  AND NOT EXISTS (SELECT 1 FROM vector_index_holds h WHERE h.table_id = $2)
  ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED;
EXECUTE c(0, 'bbbbbbbb-0000-4000-8000-000000000002', '{}');   -- six times
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF) EXECUTE c(0, 'bbbbbbbb-0000-4000-8000-000000000002', '{}');
ROLLBACK;
SQL
plan_cache_mode Plan for table B's claim Time
force_custom_plan Index Scan using idx_gsi_pending_table_claim 0.029 ms
force_generic_plan Index Scan using gsi_pending_pkey, Rows Removed by Filter: 1000000, 18,119 buffers 133.6 ms
auto (after five executions) Index Scan using gsi_pending_pkey, Rows Removed by Filter: 1000000 126.0 ms

sqlx prepares the claim per connection, so a worker's connection is on the generic plan from its sixth claim.

Experiment 2 [Difference]: the same shape through the workers

Scratch database with the shipped migrations and the four workers, tables t_one and t_two with one GSI each, A the table whose id sorts first. enqueue_rows puts 1,000,000 rows for A and 40 rows for B, all worker_partition 0, ready at insert, with their base items; index_propagation_delay_ms 300; ANALYZE gsi_pending; then time until B has no pending rows.

Claim B's 40 rows applied after A rows applied meanwhile
default 6.16 s, 5.91 s, 5.88 s 260, 41, 41
ALTER DATABASE ... SET plan_cache_mode = force_custom_plan 1.36 s 701
.persistent(false) before .fetch_optional in process_batch 1.76 s 602

Suggestion: plan the claim with its parameters (.persistent(false), or SET LOCAL plan_cache_mode = force_custom_plan in the claim transaction) and add a test with a backlog near 1,000,000 rows in one partition. The cost per claim is the other table's remaining rows, so B's latency still grows with A's backlog, which is the property the change sets out to remove. Main is much worse for B (it waits for the whole backlog).

Experiment 3 [Same]: the shape reported in #476

t_a (hash key pk, no index) and t_b (one GSI on g). 50,000 items inserted into t_a with SQL. index_propagation_delay_ms 2000. UpdateTable on t_a adds GSI gidx on g; 2 s later 21 PutItem calls to t_b; gsi_pending sampled every 500 ms.

Code Build time t_a queue rows when the puts ended t_b rows applied after the last put
main d61f8af2 (includes #401) 11.6 s 0 2.0 s
this PR 11.3 s 0 2.0 s

Neither stalls, and the build enqueued nothing for t_a, so the explanation that the issue's measurement came from a build that enqueues does not hold on merged code. The 38 s in the issue is not explained by this change. Suggestion: Refs #476, or keep the issue open for the original report. I did not have the #401 head the issue was measured on.

Experiment 4: a table that becomes ready during a batch

Delay 300 ms, A backlog queued, 8 puts to B. B applied 0.55 s, 0.57 s and 0.62 s after the puts on a quiet host. On a loaded host it took 23.5 s, and the PR's own another_tables_backlog_does_not_delay_this_tables_rows printed 39.8 s with 19,587 of 20,000 backlog rows still queued. I did not run a control that changes BATCH_SIZE.

Not measured here: PostgreSQL 16 with pgvector, release builds, more than one server on one database.

// commits before the index it guards is published. Bound to the table rather
// than correlated, so the planner evaluates it once and walks
// `idx_gsi_pending_table_claim` in `id` order to the first ready row.
let row: Option<ClaimedRow> = sqlx::query_as(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This statement is prepared once per connection. From the sixth execution PostgreSQL plans it without the table id and chooses an ordered scan of gsi_pending_pkey with a filter. For a small table whose rows sit behind a large table's rows, each claim then reads and discards all of the large table's rows: 126 to 133 ms at 1,000,000 rows, against 0.029 ms for the index plan (Experiments 1 and 2 in the summary).

Planning the claim with its parameters fixes it. With .persistent(false) on this query, B's 40 rows applied in 1.76 s where the default took 5.9 to 6.2 s.

The existing tests use 20,000 to 50,000 row backlogs. The scan grows linearly with the backlog, so by that rate it is about 6 ms per claim at 50,000 rows, and the tests cannot tell the two plans apart. A test with a backlog near 1,000,000 rows in one partition would.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right, and it reproduces on PostgreSQL 16.15. I queued 1,000,000 rows of one table and 20 of another in partition 0, then ran ANALYZE. The 7th execution of the prepared claim took 168 ms: it used gsi_pending_pkey and read and discarded 1,000,000 rows. Sent unnamed, the same claim used idx_gsi_pending_table_claim and took 0.03 ms.

Fixed in b297123: the claim now has .persistent(false), so PostgreSQL plans it with the table id every time. The new test a_small_tables_claim_reads_no_row_another_table_queued_ahead counts the gsi_pending_pkey reads in pg_stat_user_indexes while 8 rows of a second table apply behind about 19,700 held rows of a 20,000 row backlog. It counts 8 with the fix, one for each delete. With the claim kept prepared it counts about 177,000 and fails, so the test needs no 1,000,000 row backlog to tell the two plans apart.

-- With statistics present the planner serves the dominant table's claim from
-- gsi_pending_pkey (its rows are at the head of the id order); this index is
-- the plan for a small table in a partition another table dominates, and for a
-- table before its first ANALYZE. Both plans are under 0.05 ms.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"Both plans are under 0.05 ms" holds for a custom plan. With the default plan_cache_mode the claim for a small table in a dominated partition uses gsi_pending_pkey from a connection's sixth claim, and costs 126 to 133 ms at 1,000,000 rows (Experiment 1). This comment, and the PR body's "0.02 to 0.04 ms whatever the backlog", need to change with the fix.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changed in b297123. The comment now says that the 0.05 ms figure is for a plan made with the claim's parameters. It also says that a generic plan scans gsi_pending_pkey for the small table and reads every row queued ahead of its first one. For that reason the worker sends the claim unprepared. Lines 11 to 12 carry the same condition. The description's 0.02 to 0.04 ms sentence now states it too, with the 168 ms figure for the generic plan.

/// rows the order does not matter: the apply writes the item's state at apply
/// time, whatever the row carried. Distinct partitions run concurrently. Only
/// rows whose `ready_at` has elapsed are eligible. A table that enqueued rows
/// after the listing is served from the next batch; a table whose claim finds

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tables are listed once per batch, so a table whose rows become ready after the listing waits for the rest of the batch, up to 100 applies. With a 300 ms delay and a backlog behind it, 8 rows applied 0.55 to 0.62 s after the puts on a quiet host and 23.5 s on a loaded one (39.8 s in another_tables_backlog_does_not_delay_this_tables_rows). Listing again when the rotation wraps, or bounding a batch by time, would cap it. The PR body's "within the delay plus one wakeup" holds when an apply takes about 2 ms.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The bound is one batch, as you say. A table that becomes ready after the listing waits for the rest of that batch, at most 100 applies, before the next listing serves it. The description now states that bound under What, with a figure measured here. Here, at a load average of about 40, B's 8 rows applied 2.2 s and 3.9 s after the writes, with a 300 ms delay. The row "within the delay plus one wakeup" is gone.

I'd keep the batch as it is in this PR. On main the same rows wait for the whole backlog. A second listing at the wrap, or a time cap on the batch, would be a second change to the worker loop.

Comment thread docs/manuals/07-upgrade-manual.md Outdated
1.0.0 carries the same catalog migrations as 0.1.15, 1 to 12. A catalog that 0.1.15 migrated is Current under 1.0.0, so a deployment on 0.1.15 stops its servers and starts the 1.0.0 binary with no `migrate` step, and a rollback to 0.1.15 starts the 0.1.15 binary on the same catalog and configuration while the deployment has not run `extenddb encryption-key switch`. 1.0.0 also refuses to start on a catalog key that is not 32 bytes in base64 (0.1.15 started on one and failed every signed request), keeps the key in locked memory, and adds an optional KEK file outside the catalog (see [the v1.0.0 entry](#v100-the-catalog-key-is-checked-at-startup-and-kept-in-locked-memory-a-kek-file-is-optional)). On Cassandra, 1.0.0 reads and writes at `LOCAL_QUORUM` where 0.1.15 read many of its rows at `ONE`, so a request fails while fewer than a quorum of its keyspace's replicas are up, which at a replication factor of 2 means one replica down: use a replication factor of 3 before the upgrade (see [the v1.0.0 entry](#v100-cassandra-reads-and-writes-at-local_quorum)). The paragraphs below on catalog migrations 1 to 12, and on a rollback to 0.1.14 or an earlier release, are for a deployment on 0.1.14 or an earlier release. The notes on `[backup.store]` and on backups taken by 0.1.14 and earlier releases apply to every deployment.

This release versions the PostgreSQL, SQLite, Cassandra and MongoDB catalogs by a migration ledger and carries catalog migrations 1 to 12, which `extenddb migrate --list` prints. **Every deployment created by 0.1.14 or an earlier release runs `extenddb migrate --yes` once** before a server of this release starts on it: the server refuses a catalog with pending migrations. Migration 1 brings the catalog of every earlier release to migration 1's schema, migration 5 drops `continuous_backups`, a table and on MongoDB a collection (see [Catalog 0.0.5](#catalog-005)), and migration 6 adds the backup catalog index and the restore job records ([below](#migration-6-the-backup-catalog-index)). Migration 7 adds the `stream_pending` table to the PostgreSQL data database, where a write stores its stream record until the record gets its sequence number after the write commits; it does not apply to the other backends. Migration 8 adds the `restore_progress` table to the PostgreSQL data database, where a store-backed restore records each data file it applied; it does not apply on the other backends either.
This release versions the PostgreSQL, SQLite, Cassandra and MongoDB catalogs by a migration ledger and carries catalog migrations 1 to 13, which `extenddb migrate --list` prints. **Every deployment created by 0.1.14 or an earlier release runs `extenddb migrate --yes` once** before a server of this release starts on it: the server refuses a catalog with pending migrations. Migration 1 brings the catalog of every earlier release to migration 1's schema, migration 5 drops `continuous_backups`, a table and on MongoDB a collection (see [Catalog 0.0.5](#catalog-005)), and migration 6 adds the backup catalog index and the restore job records ([below](#migration-6-the-backup-catalog-index)). Migration 7 adds the `stream_pending` table to the PostgreSQL data database, where a write stores its stream record until the record gets its sequence number after the write commits; it does not apply to the other backends. Migration 8 adds the `restore_progress` table to the PostgreSQL data database, where a store-backed restore records each data file it applied; it does not apply on the other backends either.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The first paragraph of this section says 1.0.0 carries migrations 1 to 12. This paragraph now says "this release" carries 1 to 13. Name the release that carries migration 13 here, or leave this paragraph at 1 to 12 and describe 13 only in its own entry.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 6cc0293. The paragraph is back to migrations 1 to 12, which is what 1.0.0 carries, and Current Status no longer has a paragraph on migration 13. Its own entry, v1.1.0: PostgreSQL: the GSI propagation queue serves tables in turn, describes migration 13.

Comment thread docs/manuals/07-upgrade-manual.md Outdated

**Rollback.** Without a switch, 0.1.15 starts on the same catalog: a configuration that sets `key_file` makes 0.1.15 exit 1 with ``unknown field `encryption` ``, so delete the `[auth.encryption]` section. After `encryption-key switch`, follow [The switch to a KEK file: rollback](#the-switch-to-a-kek-file-rollback).

### PostgreSQL: the GSI propagation queue serves tables in turn

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Every neighbouring entry names its release (### v1.0.0: ..., ### v0.1.15: ...). This one does not, so the manual never says which release carries migration 13.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 6cc0293. The entry is now ### v1.1.0: PostgreSQL: the GSI propagation queue serves tables in turn, above the two v1.0.0 entries, so the manual says which release carries migration 13.

Comment thread docs/getting-started.md Outdated

--- Checking catalog migrations...
OK: Current: the catalog is at migration 12
OK: Current: the catalog is at migration 13

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These sample outputs now print extenddb 1.0.0 (catalog migration 13) and the catalog is at migration 13. 1.0.0 shipped with migration 12. The same lines changed in docs/getting-started.md (292, 1397), 04-quickstart-setup-guide.md (133, 178), 08-install-linux.md (121) and 09-install-macos.md (99).

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 6cc0293. The seven sample lines print migration 12 again, the number that 1.0.0 has, next to the 1.0.0 version they show.

…ch fixture

tests/gsi_queue_support/mod.rs copied the scratch database of tests/common/stream_disable_fixture.rs: Scratch, cleanup, base_conn, shipped_migrations and scratch. Its base_conn ignored EXTENDDB_TEST_PG_REQUIRED, so a job without a connection string passed gsi_queue_fairness and gsi_queue_many_tables as skipped.

The support module now uses the fixture's Scratch, base_conn and scratch, and builds its tables on the fixture's table_input. With EXTENDDB_TEST_PG_REQUIRED set and no connection string, the fixture's base_conn fails each test. The scratch databases are now named eddb_sdis_*.

The module keeps what the queue tests need beyond the fixture. Its scratch starts the engine's queue workers, and table_with_gsi adds the GSI. The other helpers set the propagation delay, seed and count the queue, and count index rows.
The per-table claim was a prepared statement. From its sixth execution on a connection, PostgreSQL ran it on a generic plan, made without the table id. Once statistics showed one table filling a partition, that plan read gsi_pending_pkey from the lowest id and filtered on table_id. Each claim for a small table then read every row that another table queued ahead of it. On PostgreSQL 16.15, one table had 1,000,000 rows queued and another had 20. The seventh execution of the second table's claim took 168 ms, and its plan read and discarded 1,000,000 rows. The same claim sent unnamed used idx_gsi_pending_table_claim and took 0.03 ms.

The claim is now sent with persistent(false), so PostgreSQL plans it with the table id every time.

The new test a_small_tables_claim_reads_no_row_another_table_queued_ahead holds a 20,000 row backlog of one table. It counts the reads of gsi_pending_pkey while 8 rows of a second table apply behind it. With the prepared claim it counted 177,254 reads behind 19,692 held rows. With the fix it counted 8, one for each delete.

The comment of migration 13 now says that its 0.05 ms figure is for a plan made with the claim's parameters.
…y v1.1.0

Release 1.0.0 carries catalog migrations 1 to 12. The Current Status of the upgrade manual, and seven sample outputs in getting-started.md, 04-quickstart-setup-guide.md, 08-install-linux.md and 09-install-macos.md, said 13 next to 1.0.0. They are again the text of main, and Current Status no longer describes migration 13.

The GSI propagation queue entry describes migration 13. Its heading is now "v1.1.0: PostgreSQL: the GSI propagation queue serves tables in turn", and it sits above the v1.0.0 entries.
@LeeroyHannigan

Copy link
Copy Markdown
Collaborator Author

On the two items of the review summary that have no inline thread:

Closes #476: agreed. The issue's shape doesn't stall on main or on this branch. The build on #401's head queues rows only for writes to the table it builds, so it doesn't explain the 38 s either. The description now says Refs #476, and the issue stays open for the original report. The message of fa8290f still ends with "Closes #476". The squash message lists the commit messages, so a squash merge by hand has to delete that line. A merge through the queue, a merge commit or a rebase merge puts it on main, and #476 then needs reopening. The description says so too.

DescribeTable: the bullet is out of "Not in this PR". It was about the in-request build of UpdateTable, which this PR doesn't change, and #401 merged on 26 Oct.

docs/manuals/07-upgrade-manual.md conflicted. Main added the v1.1.0 entry
of #398 at the top of Behavior Changes by Release, where this branch adds
its own v1.1.0 entry. Both entries stay, main's first. No other file
conflicted, and main changed no other file that this branch changes.

@hitesh96db hitesh96db left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All eight items from my first review are fixed, or answered with a bound that held when measured. Checked at 9bee8d97 on PostgreSQL 17.11.

  • .persistent(false) on the claim holds. The new test a_small_tables_claim_reads_no_row_another_table_queued_ahead reads 8 gsi_pending_pkey entries. With that line removed it reads 177,240 and fails (run twice).
  • EXPLAIN matches each clause of the 0013 comment. Planned with its parameters, the small table's claim uses idx_gsi_pending_table_claim (0.013 to 0.119 ms). The generic plan scans gsi_pending_pkey and removes 1,000,000 rows (195 to 295 ms).
  • Batch bound: with the tables listed again after every apply, B's rows applied in 545 to 579 ms, against 551 to 557 ms with the bound of 100, at 250 ms sampling. The bound adds no wait I could see.
  • The #476 shape gives the same result on main and on this head: t_b applies 2.0 s after the last put, twice each. That matches the body.
  • The migration numbers next to 1.0.0 read 12 again, and the entry is headed v1.1.0, as main labels unreleased entries.

One item remains for merge time, and the body already states it: the message of fa8290ff still ends with Closes #476. The repo squash-merges with the commit messages, so a default squash closes #476. Delete that line from the squash message.

With EXTENDDB_TEST_PG_REQUIRED=1 and no connection string, the queue test binaries now fail (3 and 1 failures) where they skipped before the shared fixture change. That reads as intended for a required run. Say so if it is not.

CI: only wasm fails, on an extenddb-core compile error. It fails the same way on the last six commits of main, and this PR does not touch crates/core. The branch merges cleanly onto current main.

Not measured: PostgreSQL 16.15, a force_generic_plan set by an operator, release builds.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

v1 Needed for the 1.0 release

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants