Skip to content

fix(postgres): keep a deleted table DELETING until its data tables drop - #504

Merged
hitesh96db merged 2 commits into
mainfrom
fix/449-pg-delete-table-orphans
Nov 10, 2026
Merged

hitesh96db merged 2 commits into
mainfrom
fix/449-pg-delete-table-orphans

Conversation

@LeeroyHannigan

@LeeroyHannigan LeeroyHannigan commented Oct 24, 2026 •

Copy link
Copy Markdown
Collaborator

What #449 reports

On PostgreSQL, DeleteTable committed the catalog row removal first and dropped
the table's data tables afterwards. If the request was interrupted between the
two, the base and index data tables (_ddb_<id>) were left in the data
database with no catalog row, and nothing removed them later. DescribeTable
then reports the table gone, a same-name CreateTable gets a new table id, and
the data tables hold the deleted table's items until an operator finds them.

What main does after #395

#395 reworked DeleteTable. On one shared database the data drops run in the
catalog transaction, behind a savepoint, so the row and its data tables go in
one commit and an interrupted request rolls back whole. The table stays ACTIVE
with its data, and no data table is left without its row.

With a separate data database no single transaction covers both, so the drops
are held uncommitted in a data transaction, the catalog row is removed and
committed, and the data commit follows. A process that dies between the
catalog commit and the data commit, or a data database unreachable for the
whole 60 second retry window, leaves the data tables with no catalog row. This
is the case #449 reports. On main at 1d0d8f4 both cases end with the row
gone and the base and GSI data tables still there, and a startup pass leaves
them (two runs of each). When only the data commit fails and the data database
still answers, the drop is redone on fresh connections and the data tables are
removed.

The change

On the separate data database path, the catalog row is marked DELETING and
committed before the data commit, and it is removed only after the data commit
succeeds. When the data commit fails, the drop is redone on fresh
connections for up to 60 seconds, as before. When the retries are exhausted,
or the process dies, the row stays DELETING with its transition due, so the
control-plane poller drops the data tables and removes the row on a later pass
or at the next startup. The data tables are named by the DELETING row until
they are dropped, so none is left without a row.

The row removal takes the row with SELECT ... FOR UPDATE SKIP LOCKED before
it deletes the tags and the row, which is the order a control-plane pass uses.
When a pass or another request holds the row, the removal changes nothing and
wakes the poller, and a pass removes the row: the pass that holds it, or the
next one once the holder is done. Deleting the tags first and then waiting for
the row deadlocks with a pass on a tagged table.

The shared-database path and the control-plane poller are unchanged. The 60
second retry runs as before; its log lines, and the error DeleteTable returns
when the retries run out, now say the row is DELETING where they said it was
removed from the catalog. The poller already drops a DELETING table's data tables on the data
pool and removes the row only after that drop commits, so a DELETING row left
by a crash is finished with no further change.

A review comment asked whether the catalog delete lacks a timeout on a
pessimistic lock. On the separate data database path two waits have no timeout
and last as long as the session they wait for. The first is the SELECT ... FOR UPDATE that starts every
DeleteTable, which waits behind a CreateBackup's FOR SHARE, an UpdateTable,
or a control-plane pass holding the row; it is on main and tracked in #614.
The second is the delete of the table's pending queue rows on the data
database, which waits for a claim in flight by design, as on main. The drops
share a single 1 second deadline (SYNC_DROP_LOCK_TIMEOUT), the drop redone
after a failed data commit stops after the 60 second retry window plus the last
attempt's own waits, and pool acquires time out after 30 seconds.

The row removal this change adds does not wait for the row, since it takes it
with SKIP LOCKED. The tag delete that follows has no timeout either, but it
can wait only for a TagResource or UntagResource statement on the same tag, and
each of those commits on its own. The control-plane pass is unchanged and takes its rows with FOR UPDATE SKIP LOCKED too.

Rebase on #395 and #680

The branch is now two commits on main at 1d0d8f4 (#680). The earlier
revision marked the row DELETING first on both layouts and finished the delete
with a scoped control-plane pass under a lock timeout. #395 handles the shared
database, so only the separate data database case is left here, and
worker_store.rs is not touched.

Tests

On a separate data database, run as CI runs the PostgreSQL storage step. The
old order is main at 1d0d8f4.

Test What it asserts On the old order
process_death_between_the_commits_is_finished_by_the_startup_pass (new) killed between the commits, the row is DELETING and both data tables remain; one startup pass drops them and removes the row fails: the row is gone after the kill; measured, both data tables stayed and a startup pass left them
an_unreachable_data_database_past_the_bound_leaves_the_row_deleting_for_the_poller (was ..._reports_the_leaked_relations) the error names every data table; the row is DELETING after the bound; once the data database answers, control-plane passes drop the tables and remove the row together fails: the row is gone after the bound; measured, both data tables stayed and a startup pass left them
a_failed_data_commit_after_the_catalog_commit_is_retried the row is DELETING at the pause between the commits; after the held data backend is terminated the drop is redone, DeleteTable returns Ok, and no data table is left fails at the pause, where the row is already gone; the redone drop removes the data tables on both
a_caller_cancelled_between_the_commits_does_not_strand_the_data a caller cancelled after the catalog commit does not stop the drop; no data table is without a row while the detached task runs, and the row and every data table are gone within 5 s passes on both
process_death_after_the_data_commit_is_finished_by_the_startup_pass (new) killed after the data commit, the row is DELETING with no data tables; one startup pass removes the row no such point: the old order removes the row before the data commit
delete_table_removes_the_row_after_the_data_commit (new) at the pause after the data commit the row is DELETING with no data tables; resumed, DeleteTable returns Ok and the row is gone with no control-plane pass no such point, as above
a_pass_holding_the_deleting_row_does_not_fail_delete_table::tagged and ::untagged (new) while an outside transaction holds the DELETING row as a pass does, DeleteTable returns Ok without waiting on it; the transaction deletes the tags and the row and commits; no tag, row or data table is left no such window: the old order removes the row in the request's first transaction

The full table_snapshot suite passes in release on both layouts, with 86
passed and 2 ignored (the two timing race measurements, which are run by hand).
CI passed all 35 checks on 47e95b1.

Not tested

The wire tests were not run against servers built from this branch. The
DELETING window a client sees for a held lock is the async path, unchanged by
this change and covered by the Rust async-path tests. The rest of CI's
PostgreSQL storage step beyond table_snapshot was not re-run, since this
change touches only DeleteTable.

The test with a pass holding the row uses an outside transaction that runs the
pass's statements in its order, because no hook holds control_plane_pass
between its select and its tag delete. Recovery by the background poller after
the retries run out has no test, since the poller's 60 second idle interval has
no test hook and the tests drive the passes themselves.

LeeroyHannigan added a commit that referenced this pull request Oct 26, 2026
…does

A second DeleteTable and an UpdateTable during a table's DELETING window
answer 400 ResourceInUseException with "Attempt to change a resource which
is still in use: Table is being deleted: <name>" on all four backends.
PutItem, GetItem, Query and Scan are served during the window on PostgreSQL
and SQLite and answer ResourceNotFoundException once the table is gone; a
write made in the window goes away with the table. Two concurrent
DeleteTable calls on one ACTIVE table get one description and one
ResourceInUseException on PostgreSQL, SQLite and MongoDB. All measured
against the service on 2026-10-24 and 2026-10-25.

DeleteTable on PostgreSQL and SQLite looked the name up with a status filter
that excluded DELETING rows and answered ResourceNotFoundException. On
MongoDB and Cassandra it had no status filter and ran the delete again.
UpdateTable on every backend answered "Table <name> is not in ACTIVE state",
the sentence for the other non-ACTIVE statuses. The data plane on PostgreSQL
and SQLite answered ResourceNotFoundException for the whole window, because
the key-info read that authorization and the handlers share mapped a
DELETING row to not found. On SQLite the DeleteTable status lookup ran
outside the write transaction and on MongoDB the DELETING mark was
unconditioned, so two concurrent calls both proceeded.

New StorageError::TableBeingDeleted, worded once in the engine's message
table and mapped to ResourceInUseException by the DeleteTable, UpdateTable
and TTL error mappers. The key-info read on PostgreSQL and SQLite reads a
DELETING row as found; a statement or transaction that reaches a data table
the control plane has dropped is answered as not found instead of as an
internal error. SQLite's DeleteTable looks the row up inside its write
transaction and fences the DELETING mark on the table id; MongoDB's mark is
an update_one conditioned on the table id and status, and its final
delete_one is keyed on both.

On PostgreSQL and SQLite the DELETING row exists only on the asynchronous
DeleteTable path (control_plane_delay_seconds of 1 or more; the default is
0.25), so on a default deployment the new answers are reachable after #504,
which marks the row on both paths. On Cassandra DeleteTable never marks the
row, so the check is reachable only for an abandoned restore target, and the
data plane there is unchanged. MongoDB drops the collections inside the
DeleteTable call a few milliseconds after the mark, so its data plane keeps
answering not found during that window. The differences document carries
the per-backend shape.

Tests: engine unit tests for the three mappers; storage-level tests on each
backend for both control-plane requests and for a CREATING table keeping
its answer; on PostgreSQL and SQLite, for the four data-plane requests
during the window, for a put, a get and the two transaction calls after the
data table is dropped under a DELETING row, and for ten rounds of two
concurrent DeleteTable calls (also on MongoDB); a dual-target wire test for
the PostgreSQL case that holds the data table locked from a second
connection, with the data-plane rows, which skips on a server whose delay is
under 1 s until #504 lands. The PostgreSQL storage-level CI step runs the
new binary.

Closes #505
@LeeroyHannigan
LeeroyHannigan force-pushed the fix/449-pg-delete-table-orphans branch from 9b0fd87 to 0585b92 Compare October 26, 2026 08:05
@jcshepherd jcshepherd self-assigned this Oct 26, 2026
AND ($1::TEXT IS NULL OR table_id = $1) \
{lock_clause}"
);
let candidates: Vec<(String, String, String)> = sqlx::query_as(&candidate_sql)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Where is the 3s timeout being applied here (FOR UPDATE will block indefinitely)?

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, it wasn't. The 3 s was set inside drop_table_storage on the data-pool transaction, so it bounded the drops and not this select. The select waited on whichever transaction held the row. After DELETING commits the only thing that holds the row past one statement is a poller pass, which takes due DELETING rows with SKIP LOCKED and keeps the locks until it commits, so the wait was bounded by that pass's progress rather than by a timeout, and the comment overstated what the 3 s covered.

5f437d5 sets lock_timeout to the same 3 s on this transaction (one constant now, shared with the drop) before the select. On SQLSTATE 55P03 the pass rolls back and returns no transitions, so finish_table_delete gives Ok(false), DeleteTable answers with the table still DELETING and wakes the poller, which is the existing path for a drop that times out. The poller pass doesn't set it, since SKIP LOCKED doesn't wait.

New test delete_table_lock_wait: holds the row from a second connection, expects the pass to give up at about 3 s with the row still DELETING, then releases the row, runs the pass to completion and reads lock_timeout on every pooled connection, expecting 0. It fails with the set_config removed, with the value changed to 30 s, and with the setting made session-level (a committed pass then leaves 3 s on the pooled connection). The interrupt tests, fmt, clippy and the 1.88 build pass. Comments in worker_store.rs and delete_table.rs now say what bounds the wait.

Two related waits are on main and not in this PR: DeleteTable's first FOR UPDATE select has no lock timeout either and can wait behind CreateBackup's FOR SHARE, and with one database the scoped pass holds a catalog connection while the drop acquires a second one from the same pool, so pool_size concurrent DeleteTable calls all wait out the 30 s acquire timeout (measured: 24 calls at pool size 10, all answered after 30.07 s, rows finished by the poller afterwards). I'll file both.

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 branch is rebuilt on main at 1d0d8f4, and the scoped pass with the blocking FOR UPDATE is gone, so worker_store.rs is untouched now. The one catalog row lock this change adds is in remove_deleting_row (1db38b3), which takes the row with FOR UPDATE SKIP LOCKED and never waits on it; when a pass or another request holds the row, the removal leaves the row and wakes the poller. The SELECT ... FOR UPDATE that starts every DeleteTable still has no lock timeout. It's on main and tracked in #614.

@jcshepherd jcshepherd left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Catalog delete appears to be lacking a time-out on a pessimistic lock, but I could be wrong. Please verify.

@LeeroyHannigan
LeeroyHannigan force-pushed the fix/449-pg-delete-table-orphans branch from 5f437d5 to 37e0f87 Compare October 29, 2026 20:58
LeeroyHannigan added a commit that referenced this pull request Oct 29, 2026
…does

A second DeleteTable and an UpdateTable during a table's DELETING window
answer 400 ResourceInUseException with "Attempt to change a resource which
is still in use: Table is being deleted: <name>" on all four backends.
PutItem, GetItem, Query and Scan are served during the window on PostgreSQL
and SQLite and answer ResourceNotFoundException once the table is gone; a
write made in the window goes away with the table. Two concurrent
DeleteTable calls on one ACTIVE table get one description and one
ResourceInUseException on PostgreSQL, SQLite and MongoDB. All measured
against the service on 2026-10-24 and 2026-10-25.

DeleteTable on PostgreSQL and SQLite looked the name up with a status filter
that excluded DELETING rows and answered ResourceNotFoundException. On
MongoDB and Cassandra it had no status filter and ran the delete again.
UpdateTable on every backend answered "Table <name> is not in ACTIVE state",
the sentence for the other non-ACTIVE statuses. The data plane on PostgreSQL
and SQLite answered ResourceNotFoundException for the whole window, because
the key-info read that authorization and the handlers share mapped a
DELETING row to not found. On SQLite the DeleteTable status lookup ran
outside the write transaction and on MongoDB the DELETING mark was
unconditioned, so two concurrent calls both proceeded.

New StorageError::TableBeingDeleted, worded once in the engine's message
table and mapped to ResourceInUseException by the DeleteTable, UpdateTable
and TTL error mappers. The key-info read on PostgreSQL and SQLite reads a
DELETING row as found; a statement or transaction that reaches a data table
the control plane has dropped is answered as not found instead of as an
internal error. SQLite's DeleteTable looks the row up inside its write
transaction and fences the DELETING mark on the table id; MongoDB's mark is
an update_one conditioned on the table id and status, and its final
delete_one is keyed on both.

On PostgreSQL and SQLite the DELETING row exists only on the asynchronous
DeleteTable path (control_plane_delay_seconds of 1 or more; the default is
0.25), so on a default deployment the new answers are reachable after #504,
which marks the row on both paths. On Cassandra DeleteTable never marks the
row, so the check is reachable only for an abandoned restore target, and the
data plane there is unchanged. MongoDB drops the collections inside the
DeleteTable call a few milliseconds after the mark, so its data plane keeps
answering not found during that window. The differences document carries
the per-backend shape.

Tests: engine unit tests for the three mappers; storage-level tests on each
backend for both control-plane requests and for a CREATING table keeping
its answer; on PostgreSQL and SQLite, for the four data-plane requests
during the window, for a put, a get and the two transaction calls after the
data table is dropped under a DELETING row, and for ten rounds of two
concurrent DeleteTable calls (also on MongoDB); a dual-target wire test for
the PostgreSQL case that holds the data table locked from a second
connection, with the data-plane rows, which skips on a server whose delay is
under 1 s until #504 lands. The PostgreSQL storage-level CI step runs the
new binary.

Closes #505
LeeroyHannigan added a commit that referenced this pull request Oct 30, 2026
…does

A second DeleteTable and an UpdateTable during a table's DELETING window
answer 400 ResourceInUseException with "Attempt to change a resource which
is still in use: Table is being deleted: <name>" on all four backends.
PutItem, GetItem, Query and Scan are served during the window on PostgreSQL
and SQLite and answer ResourceNotFoundException once the table is gone; a
write made in the window goes away with the table. Two concurrent
DeleteTable calls on one ACTIVE table get one description and one
ResourceInUseException on PostgreSQL, SQLite and MongoDB. All measured
against the service on 2026-10-24 and 2026-10-25.

DeleteTable on PostgreSQL and SQLite looked the name up with a status filter
that excluded DELETING rows and answered ResourceNotFoundException. On
MongoDB and Cassandra it had no status filter and ran the delete again.
UpdateTable on every backend answered "Table <name> is not in ACTIVE state",
the sentence for the other non-ACTIVE statuses. The data plane on PostgreSQL
and SQLite answered ResourceNotFoundException for the whole window, because
the key-info read that authorization and the handlers share mapped a
DELETING row to not found. On SQLite the DeleteTable status lookup ran
outside the write transaction and on MongoDB the DELETING mark was
unconditioned, so two concurrent calls both proceeded.

New StorageError::TableBeingDeleted, worded once in the engine's message
table and mapped to ResourceInUseException by the DeleteTable, UpdateTable
and TTL error mappers. The key-info read on PostgreSQL and SQLite reads a
DELETING row as found; a statement or transaction that reaches a data table
the control plane has dropped is answered as not found instead of as an
internal error. SQLite's DeleteTable looks the row up inside its write
transaction and fences the DELETING mark on the table id; MongoDB's mark is
an update_one conditioned on the table id and status, and its final
delete_one is keyed on both.

On PostgreSQL and SQLite the DELETING row exists only on the asynchronous
DeleteTable path (control_plane_delay_seconds of 1 or more; the default is
0.25), so on a default deployment the new answers are reachable after #504,
which marks the row on both paths. On Cassandra DeleteTable never marks the
row, so the check is reachable only for an abandoned restore target, and the
data plane there is unchanged. MongoDB drops the collections inside the
DeleteTable call a few milliseconds after the mark, so its data plane keeps
answering not found during that window. The differences document carries
the per-backend shape.

Tests: engine unit tests for the three mappers; storage-level tests on each
backend for both control-plane requests and for a CREATING table keeping
its answer; on PostgreSQL and SQLite, for the four data-plane requests
during the window, for a put, a get and the two transaction calls after the
data table is dropped under a DELETING row, and for ten rounds of two
concurrent DeleteTable calls (also on MongoDB); a dual-target wire test for
the PostgreSQL case that holds the data table locked from a second
connection, with the data-plane rows, which skips on a server whose delay is
under 1 s until #504 lands. The PostgreSQL storage-level CI step runs the
new binary.

The tests #395 added for that call now expect the service's refusal
(12 of 12 runs on 2026-10-30).

Closes #505
…e data drop commits

On a separate data database the synchronous DeleteTable removed the catalog
row, committed it, then committed the drop of the table's data tables. A
process that died between the two commits, or a data database unreachable for
the whole retry window, left the data tables on the data database with no
catalog row naming them. On main at 1d0d8f4 both cases ended with the row
gone and the base and GSI data tables still there, and a startup pass did not
remove them. When only the data commit failed and the data database still
answered, the drop was redone on fresh connections and the data tables were
removed.

The catalog row is now marked DELETING and committed before the data commit,
and it is removed only after the data commit succeeds. When the data commit
fails, the drop is redone on fresh connections for up to the retry bound, as
before. When the retries are exhausted, or the process dies, the row stays
DELETING with its transition due, and the control-plane poller drops the data
tables and removes the row on a later pass or at the next startup. The data
tables are named by the DELETING row until they are dropped, so none is left
without a row.

The row removal locks the row with SELECT ... FOR UPDATE SKIP LOCKED before it
deletes the tags and the row, the order a control-plane pass uses. When a pass
or another request holds the row, the removal changes nothing and wakes the
poller, and a pass removes the row: the pass that holds it, or the next one
once the holder is done. Deleting the tags first and then waiting for the row
deadlocks with a pass on a tagged table.

The shared-database path is unchanged: there the row and the drops are one
commit, and an interrupted request rolls back whole, leaving the table ACTIVE
with its data. The control-plane poller is unchanged: it already drops a
DELETING table's data tables on the data pool and removes the row only after
that drop commits.

The tests run on a separate data database. A process killed between the two
commits leaves the row DELETING with both data tables, and one startup pass
drops them and removes the row. A process killed after the data commit leaves
the row DELETING with no data tables, and one startup pass removes the row;
with no kill the request removes the row itself. An unreachable data database
past the retry bound leaves the row DELETING, and control-plane passes drop the
data tables and remove the row once the data database answers. A failed data
commit has the drop redone within the request. With a transaction holding the
row the way a pass does, DeleteTable returns Ok without waiting on it, on a
tagged table and on an untagged one.

Closes #449
…tabase DeleteTable

The "Data tables without a catalog row" entry described an interrupted
DeleteTable on a separate data database as leaving data tables with no catalog
row. The catalog row is now held DELETING until the data drop commits, so an
interrupted delete leaves the row for the control-plane poller to finish. The
entry now says so, and keeps the queries for finding and dropping relations
that a release from before this behaviour left behind.

@jcshepherd jcshepherd left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Changes look good: thanks. I cut #935 because the MongoDB and Cassandra backends both diverge from PostgreSQL now in terms of customer-observable behavior.

@hitesh96db
hitesh96db added this pull request to the merge queue Nov 10, 2026
Merged via the queue into main with commit 29e66ab Nov 10, 2026
35 checks passed
@hitesh96db
hitesh96db deleted the fix/449-pg-delete-table-orphans branch November 10, 2026 21:10
LeeroyHannigan added a commit that referenced this pull request Nov 18, 2026
… texts

On a separate data database, main's #504 keeps the catalog row of a table DELETING until the drop of its data tables commits. It deletes the row after that drop. The catalog-check texts of this branch still said that a synchronous DeleteTable deletes the row before its drop. The lists of orphan reports in catalog_check.rs and troubleshooting.md no longer name that case, and troubleshooting.md no longer names a table among them. The example of a relation that another session drops first is now an UpdateTable that deleted a GSI. That change is in diagnostics.rs, in the fix test and in troubleshooting.md. The description of the report test no longer gives the old order.
amrith pushed a commit to amrith/extenddb that referenced this pull request Nov 24, 2026
…eps live tables (ExtendDB#690)

* fix(storage-postgres): check data relations against the catalog by id

Add DiagnosticsStore::check_storage_relations and drop_orphaned_relations
with default implementations that report the backend does not support
them. The PostgreSQL store implements both from the catalog's table_id,
index_id and vector index ids through the crate's own naming functions,
so the expected names match what the engine creates. Rows in every
status count as live. The drop takes SHARE locks on tables, indexes and
vector_indexes, reads the catalog again under them, and drops only the
reported relations that no row names.

* fix(app): compare data relations with the catalog through the storage backend

catalog-check expected relations named _ddb_{account}_{table} and
_ddb_{account}_{table}__gsi__{index}, while the storage layer names them
_ddb_{table_id}, _ddb_{index_id} and _ddb_vec_{index_id}. On PostgreSQL
every live relation was reported orphaned, every live table missing, and
--fix dropped the data tables of ACTIVE tables.

Checks 1 and 2 now call the backend's DiagnosticsStore, which derives the
expected names from the catalog ids with the engine's own naming
functions and re-checks each candidate under catalog locks before it
drops it. Missing relations are reported with the table or index that
owns them. Checks 3 and 4 are unchanged.

* test(storage-postgres): cover catalog-check against the relations the engine creates

On a deployment with a separate data database, a table with a GSI, an LSI
and a vector index is neither orphaned nor missing; a planted relation no
catalog row names is dropped alone while an unrelated table and a table
created after the check are kept; a renamed index relation is reported
missing with its owner; rows in CREATING, UPDATING and DELETING count as
live. The binary is listed with the other PostgreSQL storage-level tests.

* docs: describe catalog-check and --fix for data relations without a catalog row

The troubleshooting entry told operators not to use --fix because the
command expected a different relation-naming scheme. It now describes
what the check compares, how --fix re-checks each relation under catalog
locks before dropping it, and keeps the manual comparison for inspection.

* fix(storage-postgres): wait only for index writers in catalog-check

The drop locked tables, indexes and vector_indexes in SHARE mode in one
statement and kept the locks until every drop had finished. An
UpdateTable adding a GSI on a new attribute writes indexes and then
tables, so the two could deadlock and the client got a 500. A drop
waiting on a relation another session held kept every catalog write on
the server waiting for up to 30 seconds. Under REPEATABLE READ the
re-read after the lock wait used a snapshot taken before it, and the
drop removed a live GSI relation.

Only a GSI add creates a relation before its catalog row commits, and it
holds ROW EXCLUSIVE on indexes from its insert to its end; every
relation name comes from an id generated when its row is inserted. A
SHARE lock on indexes alone therefore covers every path. It is taken in
attempts of 200 ms, 50 ms apart, within the 30 second budget, in a READ
COMMITTED transaction whose first statements take no snapshot, and it is
released right after the catalog read. Each drop then runs in its own
transaction with a 1 second lock timeout and without IF EXISTS: a
relation another session dropped first is reported as already gone, one
another session holds as failed, and no notice reaches the output.

The report waits for the index writers the same way before the catalog
read that decides orphans, and reports a relation orphaned only when a
second listing still has it. It reads the catalog a second time after
that listing and reports a relation missing only when both reads expect
it and the listing lacks it. Rows in CREATING are no longer expected to
have relations.

A catalog without data_database_connection_string, or with an empty
one, is refused again with the message the command gave before.

* test(storage-postgres): cover catalog-check against changes in flight

Split the catalog_check test binary into report, fix and support
modules, keeping its name for CI. The new tests cover a GSI add whose
relation exists and whose row has not committed, against the drop at the
default isolation and at REPEATABLE READ and against the check, with the
add's table write and another index write timed; an orphan another
session holds, with a CreateTable sent while the drop waits; a relation
another session dropped first; rows in CREATING or DELETING whose
relations are gone; a catalog without the data database setting; and a
DeleteTable, a dropped orphan and a new orphan landing between the
check's first catalog read and its second listing, held there by a
test-hooks pause.

* docs: state what catalog-check reports and drops while a server runs

The troubleshooting entry now says that the check reads the data
database's current schema and refuses a catalog without the data
database setting, that rows in CREATING are not reported missing, and
which reports can still be wrong while a server on another host changes
tables. The --fix paragraph describes the wait for GSI additions in
flight, the one second lock wait of each drop, the Already gone outcome,
and that every _ddb_ relation in the schema is taken as this
deployment's. The manual query filters on the current schema, as the
command does.

* test(storage-postgres): bound the held-orphan drop in its test

The holder session is released only after the drop returns, so a drop
without a lock timeout of its own would keep the test waiting. A 10
second timeout around the drop makes that case fail instead.

* fix(storage-postgres): lock indexes in catalog-check only for an unnamed relation

The report took the SHARE lock on indexes on every run. While that
request waits behind an open writer, every new write to indexes queues
behind it for up to one attempt, the index rows of a CreateTable
included. The check now reads the catalog first and waits for the index
writers only when a listed relation is unnamed, which outside a GSI add
in flight means a relation no row will name, so a check that finds every
relation named holds up no write. An attempt now lasts 100 ms instead of
200 ms.

* test(storage-postgres): check the catalog-check lock wait holds nothing else

The drop test against a GSI add in flight now reads pg_locks while the
drop waits for its SHARE lock on indexes, and asserts that the waiting
session holds no lock on tables or vector_indexes. Before, a lock of all
three tables passed the test: each attempt's 100 ms lock timeout ends
the wait before PostgreSQL's deadlock check runs, so the add's table
write still finished in time.

* test(storage-postgres): commit the GSI add while catalog-check waits

The drop test committed the add after a fixed 600 ms, which fell in the
50 ms pause between two lock attempts about a third of the time. The next
attempt then started after the commit, and a snapshot taken before the
lock still saw the row, so the REPEATABLE READ case passed without the
isolation fix. The test now commits only once pg_locks shows a SHARE
request on indexes that began less than 20 ms earlier, so the commit
lands while that attempt waits.

* docs: state that catalog-check waits for index writers only when needed

The troubleshooting entry still said the check always waits for the GSI
additions in flight and that each lock attempt lasts 200 ms. The check
waits only when it finds a relation no row names, and an attempt lasts
100 ms. A write to indexes that queues behind the granted lock also
waits for the one catalog read the lock is held for; the entry and the
comment on the attempt length now say so.

* docs: drop the count from the catalog-check wrong-report sentence

The troubleshooting entry opened its list of the reports that can be
wrong while a server runs with a count of them. It now states the
condition and lists them.

* fix(app): open the encrypted connection string row in catalog-check

Main (ExtendDB#1003) encrypts the data_database_connection_string row of a PostgreSQL catalog with a key ring under the ring's DEK. Main's catalog-check read the row and opened it in data_connection_text. Without a ring the command takes the row as stored. With a ring the KEK of [auth.encryption] key_file opens it, and the command refuses a ring when key_file is not set. test_data_database_connection takes the key and reads the row through data_connection_string, with the same rules.

This branch reads the row in the PostgreSQL store, in data_pool, for check_storage_relations and drop_orphaned_relations. The plain read gave ciphertext in a catalog with a ring. The two methods now take the key as test_data_database_connection does. data_pool reads the row through data_connection_string with that key. catalog-check passes the key source of [auth.encryption] (the KEK with key_file set, else the catalog key). data_connection_text has no caller now, so the commit deletes it. A missing or empty row in a catalog without a ring still gets the message of this branch. The catalog_check tests pass the catalog key, as the command does without key_file.

* test(storage-postgres): set warm_throughput in the catalog_check GSI input

Main (ExtendDB#474) added the warm_throughput field to GsiInput. The CreateTableInput of the catalog_check test deployment in support.rs builds gsi1 with a GsiInput literal, which did not compile after the merge. The literal now sets warm_throughput to None, as the other PostgreSQL storage tests do, so the test creates gsi1 as before.

* fix(app): set up the locked key store before catalog-check reads the KEK

catalog-check read the KEK of [auth.encryption] key_file with key_file::key_source and did not set up the locked key store first. The DEK that the KEK unwraps was then held in heap memory. verify and migrate read the KEK through util::status_key_source, which sets up the locked key store before the read, and catalog-check now uses that helper too. With key_file set, on a host where memory locking fails and require_locked_memory is true, catalog-check now refuses to run, as verify and migrate do there.

* test(storage-postgres): run the catalog-check relation check on a catalog with a key ring

No test ran check_storage_relations on a catalog whose data database connection string row is encrypted under the DEK of the key ring. set_data_connection_writes_the_row_under_the_ring now runs it after set_data_connection writes the row. With the KEK the check opens the row, and with the catalog key it returns an error.

* docs: state the DeleteTable order of main's ExtendDB#504 in the catalog-check texts

On a separate data database, main's ExtendDB#504 keeps the catalog row of a table DELETING until the drop of its data tables commits. It deletes the row after that drop. The catalog-check texts of this branch still said that a synchronous DeleteTable deletes the row before its drop. The lists of orphan reports in catalog_check.rs and troubleshooting.md no longer name that case, and troubleshooting.md no longer names a table among them. The example of a relation that another session drops first is now an UpdateTable that deleted a GSI. That change is in diagnostics.rs, in the fix test and in troubleshooting.md. The description of the report test no longer gives the old order.

* test(storage-postgres): fail the catalog_check tests when a job needs a server and has none

The catalog_check tests skipped when EXTENDDB_TEST_PG_CONNECTION_STRING was not set, also with EXTENDDB_TEST_PG_REQUIRED=1. With that setting and no connection string, all 13 tests passed. base_conn in tests/catalog_check/support.rs now makes the check that iam_leftovers.rs and stream_commit_order.rs make. When EXTENDDB_TEST_PG_REQUIRED has a value other than 0 and the connection string is not set, the test fails. The comment at integration.yml:772 gives this behaviour for every test of the crate.

* test(storage-postgres): create pgvector in the catalog_check data database

Deployment::new in tests/catalog_check/support.rs did not create the pgvector extension in the data database. Neither create_data_db nor migrations::migrate runs CREATE EXTENSION vector, and template1 of the pgvector/pgvector:pg16 image has only plpgsql. So pgvector() was false on both CI images and no test created vec1. With named_relations changed to name no vector index relation, all 13 tests passed.

Deployment::new now calls try_create_vector_extension on the data database. The run-postgres-storage-tests job sets EXTENDDB_EXPECT_VECTORS=1, and with that setting Deployment::new fails when the data database has no pgvector. Now 8 of the 13 tests fail with that change.

* test(storage-postgres): cover the end of the catalog-check index lock budget

No test reached the end of the 30 second wait for the index writers in flight. All tests passed without the deadline check in read_after_index_writers, and also without the budget message in catalog_check_error.

PostgresCatalogStore now keeps the budget in a field that new and with_secret_keys set to INDEX_LOCK_BUDGET. with_index_lock_budget, compiled only with test-hooks, makes a store with a shorter budget. The new test holds ROW EXCLUSIVE on indexes past a budget of 2 seconds. Then it asserts the error of the check and of the drop, and that the orphan is still there. Without the deadline check the test fails at its 10 second timeout. Without the budget message it fails on the error text.

* fix(storage-postgres): give the catalog-check index lock text only for the indexes lock

catalog_check_error gave the text "index changes in progress kept the index catalog locked for more than 30 seconds" for each error that lock_wait_failed accepts. Those are SQLSTATE 55P03, 40P01 and 57014. A 55P03 from read_catalog can come from a lock on tables or vector_indexes. With statement_timeout=50ms on the catalog sessions, the check gave that text after the first lock attempt. With ACCESS EXCLUSIVE held on vector_indexes and no index change in flight, it gave that text when the budget ran out.

check and drop_orphaned now return a CheckFailure. read_after_index_writers gives CheckFailure::IndexLock when the last attempt timed out on the SHARE lock on indexes after the deadline. Every other error is CheckFailure::Sql, and catalog_check_error gives its text unchanged. A new test runs both cases, and the store gives the server's own error in each.

* fix(storage-postgres): list the data relations that the search path reaches in catalog-check

storage_relations listed the relations in current_schema() only. The server and the drop resolve unqualified names through the search_path. With search_path = alt, public set for the role on the data database, the server kept serving the table in public. The check then reported its relations missing, because current_schema() was alt. A listing of every schema also passed all tests.

The listing now reads pg_class and keeps the relations for which pg_table_is_visible is true, which resolves names as the server's statements and the drop do. The new test sets that search path and plants a relation with the prefix in a schema off the path. It checks that nothing is missing or orphaned. Without the fix the test reports the 4 relations of the table missing. Without the visibility filter it reports the planted relation orphaned. troubleshooting.md now gives that scope, and its query by hand uses the same filter.

* fix(storage-postgres): refuse a key ring row that the key does not open as not configured

data_pool mapped every error of data_connection_string to DiagError::QueryFailed. Without the KEK, catalog-check refused a catalog with a key ring. It printed "Cannot compare data relations with the catalog: Query failed: the catalog has a key ring, ...". No query failed. data_pool now maps MigrationError::Refused to DiagError::NotConfigured, as for the absent setting. catalog-check then prints the refusal on its own, as it did before the check moved to the storage backend.

In key_ring_rows.rs, the check without the KEK passed on any error, also on a connection failure. It now asserts NotConfigured with the start of the refusal text. At the previous commit that assertion fails with the QueryFailed error.

* docs: state the catalog-check report stop after 30 seconds and the wait of each indexes write

troubleshooting.md gave the outcome of a wait for index writers that runs past 30 seconds for --fix only. The report without --fix stops there too. It prints the error that says so and no result of any check, and exits with status 1. The paragraph on the check now says so.

The paragraph on --fix said that a server's write to indexes waits at most 100 ms plus the one catalog read. That bound holds for each write. One CreateTable with a GSI writes indexes more than once and can wait that long at each write. The paragraph now says "Each write to indexes" and names that case.

The sentences that the search path commit changed in the same section are now split into shorter ones. The lead-in to the query by hand now says that the query lists the relations that no catalog id names, which is what it returns.

* test(app): run catalog-check as the binary against a PostgreSQL deployment

No test covered cmd_catalog_check.rs, and no workflow ran catalog-check against PostgreSQL. The store tests stop at PostgresCatalogStore. So nothing tested the call of status_key_source, the mapping of NotConfigured, the lines the command prints or its exit code.

crates/bin/tests/catalog_check.rs runs the extenddb binary on the deployment of the catalog_check storage tests, through their support module. The deployment has one orphaned relation and one missing GSI relation. The test asserts the whole output and exit status 1 of catalog-check --fix and of the report without --fix. Then it removes the data database setting and asserts the refusal alone on stderr. With the NotConfigured message prefixed as the other errors are, the test fails on that last line. The run-postgres-storage-tests job runs the test with EXTENDDB_TEST_PG_REQUIRED=1. The bin crate gets dev-dependencies on extenddb-core and on extenddb-storage-postgres with test-hooks, which exports the naming functions that the support module uses.

* fix(storage-postgres): turn off statement logging on the diagnostics store's catalog pool

The diagnostics store connected to the catalog with statement logging on. A catalog read that waited on a lock for more than 1 second then printed a slow statement line. That line held the full CATALOG_ROWS text and came between the lines of the catalog-check report. The binary writes its log to stdout. The diagnostics store factory now connects with disable_statement_logging, as data_pool does for the data database.

In the catalog-check binary test, the report without --fix now runs while another session holds ACCESS EXCLUSIVE on vector_indexes for 1.5 seconds. At the previous commit, the output then has a line "WARN sqlx::query: slow statement: execution time exceeded alert threshold". The line comes after "Connected to catalog.", and the test fails. With this change the output has no log line.

* style: format the catalog-check tests with rustfmt

The rustfmt check of fmt.yml reported four test files that the earlier commits of this round changed: crates/bin/tests/catalog_check.rs, and fix.rs, support.rs and key_ring_rows.rs under crates/storage-postgres/tests. This commit applies cargo fmt to them. No code changes.

* test(storage-postgres): check pgvector on the built catalog_check deployment

Deployment::new checked the pgvector setting before it built the Deployment. When the check failed, Drop did not run and the two scratch databases stayed on the server. The check now runs on the built Deployment through pgvector(), so a failure drops the databases as any other test failure does.

* test(storage-postgres): run the drop in the catalog-check failure test too

No test covered the locked flag in read_after_index_writers. Row 2 of other_catalog_failures_do_not_report_index_changes holds ACCESS EXCLUSIVE on vector_indexes. The check stops in read_catalog there, before it requests any lock on indexes. The drop calls read_after_index_writers at once. So its read under the SHARE lock is the path that the flag guards.

Each row of the test now also runs drop_orphaned_relations on the planted orphan and asserts the same error text as for the check. With the flag removed from the IndexLock arm, the test fails on row 2's drop. That drop then gives the text "index changes in progress kept the index catalog locked for more than 2 seconds, so nothing was dropped".

* docs: drop the catalog-check sentence on waits at each indexes write

troubleshooting.md said that a request can write indexes more than once, as a CreateTable with a GSI does. It said that such a request can then wait behind the command at each write. A CreateTable inserts all its indexes rows in one catalog transaction (create_table.rs, from the begin at line 161 to the commit at line 555). PostgreSQL does not make a transaction wait again for a lock that it holds already. So a CreateTable waits on the command once. This commit deletes that sentence. The sentence before it stays: each write to indexes waits behind the command for at most 100 ms plus the one catalog read.

* test: one helper for the catalog-check sessions that hold a lock

Four places in the catalog-check tests opened a session, ran BEGIN and then ran one lock statement. These were hold_relation in support.rs, the budget test in fix.rs, the failure test in report.rs and the binary test. support.rs now has one helper, hold(url, statement), that does this and returns the session. hold_relation and the three tests use it.

* refactor(storage-postgres): map the diagnostics store's connect errors once

The diagnostics store factory mapped the parse error and the connect error to ConnectionFailed with two identical closures. It now parses and connects in one async block and maps the block's error once.

* ci: set the PostgreSQL test settings once for the storage test job

Both test steps of run-postgres-storage-tests set EXTENDDB_TEST_PG_CONNECTION_STRING, EXTENDDB_TEST_PG_REQUIRED and EXTENDDB_EXPECT_VECTORS to the same values. The job's env now sets them once, with the comments that the first step had.

* refactor(storage-postgres): drop the unused Debug derive of CheckFailure

Nothing formats a CheckFailure with {:?}. catalog_check_error matches on it, and no caller unwraps a Result that holds one. This commit removes the derive.

* test(storage-postgres): use the hold helper in the open index write test

a_check_that_finds_every_relation_named_does_not_wait_for_index_writers
opened a catalog session, began a transaction and ran its UPDATE of
indexes inline. The hold helper in the support module does the same, so
the test now calls it.

* test(storage-postgres): check an ACTIVE index of a settling table in catalog-check

CreateTable inserts the GSI, LSI and vector index rows ACTIVE under a
table row that can be CREATING. DeleteTable leaves them ACTIVE under a
DELETING table row. named_relations expects an index relation only when
neither the index row nor its table row is CREATING or DELETING. No test
covered the table half: with "table_settled &&" removed from the index
rows, all 16 catalog_check tests passed.

rows_being_created_or_deleted_are_not_reported_missing now sets the
index and vector index rows back to ACTIVE before it moves the table to
DELETING and CREATING. With "table_settled &&" removed, the test fails
with the gsi1, lsi1 and vec1 relations reported missing.

* refactor(storage-postgres): classify undefined_table beside lock_not_available

The catalog-check drop compared the SQLSTATE of its error with its own
42P01 constant, through a copy of the sqlstate function of
migrations/connect.rs. data/ddl.rs already classifies lock_not_available
with sqlstate_is. It now has undefined_table beside it, and the drop
calls that. catalog_check.rs no longer has the constant or the copy.

* refactor(storage-postgres): share the data database read and connect of the diagnostics store

data_pool repeated three steps of test_data_database_connection: the
PostgresTarget for the catalog, the data_connection_string read and the
pool connect. data_connection_row and connect_data now do them for both.
Each caller keeps its own errors: test_data_database_connection reports
a failed read as "Query failed", and data_pool reports a refused row as
not configured.

The connect of test_data_database_connection now has the options of the
data_pool connect: two connections at most and statement logging off. It
opens one connection and runs no statement on it, so extenddb verify
prints the same lines.

* test(storage-postgres): assert the full catalog-check messages

Four asserts of the catalog-check tests compared only the start or the
end of a message. One is the key ring refusal in key_ring_rows.rs. Three
are in catalog_check/fix.rs: the Kept reason of a later table, the lock
text of a held orphan and the index lock budget text. Each message has a
fixed text, so each assert now compares the whole text.

* test(app): remove the catalog-check config directory when the test fails

The binary test removed its config directory only after its last
assert, so a failed run left the directory under CARGO_TARGET_TMPDIR.
A ConfigDir guard now removes it on drop, as Deployment drops its
databases.

* docs: say catalog-check waits for the index changes in flight

The troubleshooting entry said that the check and --fix wait for the
GSI additions in flight. The SHARE lock on indexes waits for every open
write to indexes, and the error text says "index changes in progress".
The entry now says "index changes in flight".

* style: put PostgreSQL and GetItem in backticks in the catalog-check docs

clippy::pedantic gave doc_markdown warnings on five doc comment lines
that this branch adds: four name PostgreSQL and one names GetItem. The
names are now in backticks, and the pedantic run of the touched crates
gives no warning on a line of this branch.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release-blocker Must ship for its milestone's release v1 Needed for the 1.0 release

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants