Repository navigation
fix(storage-postgres): serve each table in turn in the GSI queue workers - #542
LeeroyHannigan wants to merge 20 commits into
Conversation
bb9b1da to
ce1ccaa
Compare
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
ce1ccaa to
fa8290f
Compare
.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
left a comment
There was a problem hiding this comment.
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.
- 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). 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( |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
"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.
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| 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. |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
|
||
| **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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
|
||
| --- Checking catalog migrations... | ||
| OK: Current: the catalog is at migration 12 | ||
| OK: Current: the catalog is at migration 13 |
There was a problem hiding this comment.
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).
There was a problem hiding this comment.
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.
|
On the two items of the review summary that have no inline thread:
|
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
left a comment
There was a problem hiding this comment.
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 testa_small_tables_claim_reads_no_row_another_table_queued_aheadreads 8gsi_pending_pkeyentries. 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 scansgsi_pending_pkeyand 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.
Changes since the last review
Five commits follow cc02460, the head that hitesh96db reviewed on 23 Nov:
origin/mainat a417b2f, feat(wasm): [Add WebAssembly browser support for ExtendDB #1009 included. The merge has no conflict.tests/common/stream_disable_fixture.rsand deletes the copy of it fromtests/gsi_queue_support/mod.rs. WithEXTENDDB_TEST_PG_REQUIREDset and no connection string, the four GSI queue tests now fail instead of reporting a skip..persistent(false)). It addsa_small_tables_claim_reads_no_row_another_table_queued_ahead, which counts the reads ofgsi_pending_pkey, and fixes the plan comment of migration 13.v1.1.0: PostgreSQL: the GSI propagation queue serves tables in turn, above the v1.0.0 entries.origin/mainat d3b2a41. fix(metrics): bound latency segment memory by summing into fixed time buckets #398 added its v1.1.0 entry todocs/manuals/07-upgrade-manual.mdwhere 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. TheDescribeTablebullet 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 inidorder, 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 thanBATCH_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_rowsran 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.rstogsi_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-
idrow is ready. The enqueue floorsready_atat the partition's current maximum. So within a partitionready_atdoes not decrease withid, and a table's first row carries its earliestready_at. Only two writers that read the floor before either one commits can land a lateridwith an earlierready_at. That delays a table's listing by at most one jitter when one delay is in force. If an operator sets a per-indexpropagation_delay_msabove 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), addsidx_gsi_pending_table_claimongsi_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 walkedgsi_pending_pkeyfrom the lowestid, 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) sampledpg_stat_activityand per-tablegsi_pendingcounts every 2 s.The issue's own shape does not stall on
main.UpdateTablebuilds 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 onmain(d61f8af2, which includes #401) and on this branch.On
main, a backlog stalls another table's rows. With 50,000BatchWriteItemputs to table A queued, 21 puts to table B apply 9 to 11 s after the last write. Each worker claimsORDER BY id LIMIT 1over 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.migratebuilds the index with the servers stopped, at about 1.7 s per million queued rows (3.45 s at 2,000,000 rows). It runsCREATE INDEX IF NOT EXISTS, which takesSHAREongsi_pendingfor 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. AfterANALYZE, one session ran B's claim 7 times, and the table shows the 7th:plan_cache_mode = force_custom_planidx_gsi_pending_table_claimforce_generic_plangsi_pending_pkey, 1,000,000 rows removed by filterauto(the default), 5 custom plans then genericgsi_pending_pkey, 1,000,000 rows removed by filter.persistent(false)sends it,autoidx_gsi_pending_table_claimThe figures below are from before b297123, with the claim prepared. Single
pgvector/pgvector:pg16container on one host,index_propagation_delay_ms = 2000, release binaries, from the last write on table B to its rows applied:mainUpdateTablebuild shapeWith 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
WALWriteandWALSyncwaits 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
ready_atfloor 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-indexpropagation_delay_mscolumn today. Scoping the floor to(table_id, worker_partition)needs an index leading ontable_idfor theMAX.mainthe same rows wait for the whole backlog.next_ready_waitkeeps the correlated hold anti-join (13 ms on a 40,000-row queue, once per empty batch).breakofmainpasses 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
maindoes 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.mdanddocs/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'sSET LOCAL lock_timeoutstatement insqlx::AssertSqlSafe, and this branch moves that loop togsi_rotation.rs. The resolution keeps the move and puts the wrap on the statement ingsi_rotation.rs, in whichever PR merges second. sqlx 0.9.1 also refuses aformat!string insqlx::queryandsqlx::query_scalar, soenqueue_rowsandindex_rowsintests/gsi_queue_support/mod.rsneed the same wrap, with no textual conflict to show it.QueryAs::persistentexists in sqlx 0.9.1.Testing done
tests/gsi_queue_fairness.rs(3 tests):another_tables_backlog_does_not_delay_this_tables_rowsputs a 20,000-row backlog for table A (whosetable_idsorts 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 thevector_index_holdsrow, 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 runsANALYZE. 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 readsidx_tup_readofgsi_pending_pkeyfrompg_stat_user_indexesbefore 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_rotationunit 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.rsuses the fixture'sScratch,base_conn,scratchandtable_input. It keeps what the queue tests need beyond the fixture. Itsscratchstarts the engine's queue workers,table_with_gsiadds a GSI to the fixture's table, andputwrites an item with the GSI key.set_delay_mssets the propagation delay,template_rowandenqueue_rowsseed the queue directly, andpending,pending_inandindex_rowscount queue and index rows. WithEXTENDDB_TEST_PG_REQUIRED=1and 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_itemholds the older queue row withFOR KEY SHAREfrom 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-idrow is due, so the newer row alone was never claimed. The changed test passes on the code ofmainas well.mainrun migration 13.migrations_runs.rsapplies the latest id again afterforget, andmigrations_released.rscompares each upgraded released catalog with a fresh install. The CI schema step checks a fresh install againstdocs/schema/postgres.txt, which lists the index. The MongoDB tests that pin the migration set expect 13 migrations.gsi_rotation.rswith the tests kept. At cc02460, the claim withoutAND table_id = $2and the cursor ignored each failed the test written for it. In an earlier round, before a merge withmain,served()as a no-op and the hold predicate removed did the same. At 6cc0293, the claim kept prepared failsa_small_tables_claim_reads_no_row_another_table_queued_ahead(2 of 2 runs).--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, withEXTENDDB_TEST_PG_REQUIRED=1andEXTENDDB_EXPECT_VECTORS=1as 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 therun-postgres-storage-testsjob, which CI builds with--release: 42 targets, 491 passed, 2 ignored, 5 failed. The five are threestore_identitytests inbackup_restore.rsand two tests incatalog_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 duringtable_snapshot, sotable_snapshot,twi_conflictandvector_control_planeran 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, andcargo +1.91.1 check -p extenddb-storage-postgres --all-targets: clean.cargo +1.97.0 clippy -p extenddb-storage-postgres --all-targets -- -W clippy::pedanticwarns on lines this branch adds, for example theworker_id as i32binds ingsi_rotation.rsand theusizetoi64casts in the tests. So the Clippy box is unticked.python3 -m pytest --collect-only -qcollects 6660 tests intests/and 672 intests/python, with no error.gsi_rotation.rs394,gsi_queue.rs569 (the claim loop moved out),gsi_queue_fairness.rs291,gsi_queue_support/mod.rs211,gsi_queue_many_tables.rs130.lib.rs(1,061 lines),gsi_online_build.rs(1,274) and the upgrade manual (1,315) were over 600 lines onmainand grew by 1, 7 and 28 lines. No dependency change.Checklist
cargo test --workspace)cargo fmt --check)cargo clippy -- -W clippy::pedantic)Storagetrait, auth model, on-diskformat, 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
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 runsextenddb migrate --config extenddb.toml --yeswith 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.idacross its partition, so the rows of all tables in a partition applied inidorder. 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.