Repository navigation
fix(storage-postgres): bound the lock wait of a TTL index drop - #1403
Conversation
UpdateTimeToLive with Enabled false ran DROP INDEX on the data table with no lock_timeout. The drop needs ACCESS EXCLUSIVE, so behind a long reader it waited until the reader finished, and every later lock request on the table queued behind the drop: reads and writes stalled for as long as the reader held the table. drop_ttl_index now runs the drop in a transaction with a 200 ms lock_timeout and retries lock-wait failures (55P03, 40P01, 57014) every 250 ms for up to 5 s. A queued drop therefore blocks other requests for at most one attempt at a time. If the budget runs out the error is returned (UpdateTimeToLive logs it), the index stays, and ttl_index_ready is already FALSE, so the sweeper does not use it. The new storage test holds ACCESS SHARE on the data table, starts the disable, checks that a read still completes within 2 s, then releases the reader and checks the drop completes. Without the fix the read queues behind the drop and the test fails. Signed-off-by: Hitesh Sharma <hts@amazon.com>
Resolves the conflict in drop_ttl_index with sqlx 0.9 (#1166): the bounded-wait retry loop is kept and its DROP INDEX goes through sqlx::AssertSqlSafe. The dynamic SQL in tests/ttl_index_drop_lock.rs is wrapped the same way so the test builds against sqlx 0.9. Signed-off-by: Hitesh Sharma <hts@amazon.com>
LJMart11
left a comment
There was a problem hiding this comment.
Reviewed at fc46528. 1 finding: 1 Critical.
The change runs the PostgreSQL TTL index drop in a transaction with a 200 ms lock_timeout and retries lock-wait failures every 250 ms for up to 5 s. Confirmed: while the drop retries behind an ACCESS SHARE reader, other reads of the table stay under one attempt (62 probes per trial, 3 trials, max 183-184 ms); the drop completes once the reader is gone; two concurrent disables both succeed, and a DeleteTable during the retry loop is deferred and then the drop succeeds. Through the server, an UpdateTimeToLive disable behind a reader now answers 200 after 5.19-5.20 s instead of waiting out the reader (the base answered after 8.00 s, when the reader released). Putting the base's drop back, or removing the lock_timeout, fails the new test at ttl_index_drop_lock.rs:267; removing the retry fails it at :255. The new test, 340 storage-postgres tests and clippy with -D warnings pass under 1.94.0; the branch already contains the current main tip.
- Critical
crates/storage-postgres/src/metadata_engine.rs:46— When the 5 s budget runs out, the TTL index stays after a disable that answered 200. PutItem with a fractional or out-of-range number in the old TTL attribute then fails with 500, and a re-enable on another attribute publishesttl_index_ready = TRUEover the stale index.
| /// attempt get their locks. | ||
| const TTL_DROP_RETRY_PAUSE: std::time::Duration = std::time::Duration::from_millis(250); | ||
| /// How long `drop_ttl_index` keeps retrying a lock wait before it gives up. | ||
| /// The index then stays, which only costs space: readiness is already off. |
There was a problem hiding this comment.
Critical
When the drop gives up after TTL_DROP_BUDGET (metadata_engine.rs:46), the index idx_ttl_<table> on the old attribute stays, and nothing retries the drop. That index casts (item_data->'exp'->>'N')::BIGINT on every write (:343-345). So after a disable that answered 200, a PutItem with exp set to 1.5 or 1E+30 fails, even though exp is no longer a TTL attribute. The index name does not depend on the attribute (:319), so a later enable on exp2 runs CREATE INDEX CONCURRENTLY IF NOT EXISTS (:343), which does nothing, and :356 sets ttl_index_ready = TRUE over the exp index. ExtendDB has no TTL cooldown (docs/differences-from-dynamodb.md:89), so disable-then-enable is an ordinary sequence. The comment at :46 ("only costs space: readiness is already off") does not hold.
What the user sees: both UpdateTimeToLive calls answer 200, and DescribeTimeToLive reports DISABLED and then ENABLED/exp2. PutItem with exp: {N: "1.5"} answers 500 InternalServerError, which the SDK retries 9 times. The table never gets an exp2 index, so every 60 s sweep (:476-481) runs a sequential scan (EXPLAIN shows Seq Scan). The only trace is one TTL index drop failed … lock timeout warning from engine/src/ttl.rs:183 at the disable. On the base the drop waits until the reader is gone, and the index was removed in my run.
Fix: do not leave the index behind silently. Either retry the drop off the request path, for example in the PostgreSQL TTL worker's pass (ttl_worker.rs:39-60) for tables whose ttl_attribute is NULL while the index exists, or, in create_ttl_index, drop a valid index whose definition does not index ttl_attribute, as :321-339 already does for an INVALID one. Comparing pg_get_indexdef with the expected expression is enough. Add a test next to tests/ttl_index_drop_lock.rs:224-286 that holds the reader past the budget and then asserts that the index is eventually gone, or that a re-enable on another attribute indexes that attribute. No migration is needed, but deployments that already hit this keep the index until a disable succeeds.
Evidence: through the server (PostgreSQL harness), I enabled exp, held SELECT count(*) open on the data table and sent the disable. It answered 200 after 5.19-5.20 s (3 of 3 trials), and the log read TTL index drop failed … canceling statement due to lock timeout. After a re-enable on exp2, the catalog row read ('exp2', True) and the index was still … ((item_data -> 'exp'::text) ->> 'N'::text))::bigint …. PutItem with exp 1.5 and with 1E+30 answered 500 (reached max retries: 9), and 12345 answered 200. On the base, the same disable answered 8.00 s later, when the reader released, the index was gone, and the re-enable built it on exp2. The vendor page (https://www.postgresql.org/docs/16/sql-createindex.html) says of IF NOT EXISTS: "there is no guarantee that the existing index is anything like the one that would have been created."
There was a problem hiding this comment.
Addressed in c3efcd8, with both fixes:
- The PostgreSQL TTL worker now retries the drop off the request path. Each pass, before it rebuilds pending indexes,
drop_leftover_ttl_indexeslistsidx_ttl__ddb_*indexes with onepg_classquery on the data database, keeps those whose catalog row hasttl_attribute IS NULL, and drops each with the same bounded drop (200 ms lock_timeout per attempt, 5 s budget). It holds the catalog rowFOR UPDATE SKIP LOCKEDand rechecks that TTL is still off, so a racing enable waits for the drop and then builds its own index. A drop that gives up again is retried next pass. create_ttl_indexnow also drops a valididx_ttl_<table>whosepg_get_indexdefdoes not contain(item_data -> '<attr>'::text)for the requested attribute, as it already did for an INVALID one, using the bounded drop. If that drop gives up it returns the error, sottl_index_readyis not published and the deferred build retries. A stale task whose attribute is no longer the table attribute skips the drop.- The
TTL_DROP_BUDGETcomment now says what happens when the budget runs out.
Tests in tests/ttl_index_drop_lock.rs, each holding the reader past the budget so the disable drop gives up:
the_ttl_worker_drops_an_index_a_disable_left_behind: after the reader is released, the worker pass drops 1 index and none remains. With the pass disabled it fails atassert_eq!(dropped, 1)(left: 0).a_re_enable_on_another_attribute_replaces_an_index_a_disable_left_behind: a re-enable onexp2leaves an index whose definition namesexp2and notexp, andttl_index_readyis TRUE. Without the definition check it fails with the index still((item_data -> 'exp'::text) ->> 'N'::text))::bigint.
All 3 tests in that file pass, plus cargo test -p extenddb-storage-postgres --lib (94 passed), cargo fmt --all -- --check and cargo +1.97.0 clippy -p extenddb-storage-postgres --all-targets -- -D warnings. I did not run cargo test --workspace or pytest locally.
When a TTL disable's bounded drop of idx_ttl_<table> ran out of its 5 s budget, the disable still answered 200 and the index on the old attribute stayed. Its ::BIGINT cast made PutItem with a fractional or out-of-range number in that attribute fail with 500, and a re-enable on another attribute kept the stale index (CREATE INDEX ... IF NOT EXISTS) and published ttl_index_ready = TRUE over it. - create_ttl_index drops an existing index whose pg_get_indexdef does not index the requested attribute, as it already did for an INVALID one, using the bounded drop. If that drop gives up it returns the error, so readiness is not published and the deferred build retries. A stale task whose attribute is no longer the table's skips the drop. - The PostgreSQL TTL worker's pass drops the TTL index of every table whose ttl_attribute is NULL, with the same bounded drop, holding the catalog row FOR UPDATE SKIP LOCKED so a racing enable waits. - Correct the TTL_DROP_BUDGET comment. Refs #606 Signed-off-by: Hitesh Sharma <hts@amazon.com>
LeeroyHannigan
left a comment
There was a problem hiding this comment.
Thanks. I read the change against main 92155f3. Against PostgreSQL 16 (pgvector/pgvector:pg16), the three tests in ttl_index_drop_lock.rs passed in 3 of 3 runs at this head. On main the first test fails at line 267 in about 4 s, which is the defect of #606.
The bounded drop fixes the first point of #606 by the mechanism that the description states. With a 200 ms lock_timeout per attempt, the drop leaves the lock queue, and the readers queued behind it run in the 250 ms pause. The worker pass and the definition check in create_ttl_index answer LJMart11's review of fc46528. I checked their interleavings with an enable, and both end with the right index. No client answer changes.
One change is needed before I approve. The retry lets an enable on another attribute run between two attempts of a disable, and a later attempt can then drop the new index. The inline comment at line 533 gives the sequence. The retry introduces this race, so the fix belongs in this PR.
Smaller points:
- Line 68 repeats
set_lock_timeoutindata/ddl.rs:731, which ispub(super). Withpub(crate), a call would remove the copy.delete_table::SYNC_DROP_LOCK_TIMEOUT(1 s) is documented as the longest time that a drop's queuedACCESS EXCLUSIVErequest can stall other requests. Please reuse it, or say in the description why this drop uses 200 ms. - Lines 34-165 of the test file copy the scratch harness of
put_create_race.rs, with itseddb_putr_prefix and its table namet_put_create_race. A database that a failing run leaves then names the other test.tests/common/stream_disable_fixture.rsexportsScratch,base_conn,shipped_migrationsandscratch, and four test files share it. Please use it, or at least give this file its own prefix and table name. docs/differences-from-dynamodb.mdrows 79 and 80 say that the PostgreSQL disable returns once the catalog flip is durable, and that it is synchronous. After this change it waits up to 5 s for its drop, and the TTL worker finishes a drop that gave up. A short entry under a### v1.2.0:heading in the upgrade manual would tell operators the same.- On main the third test hangs instead of failing.
disable_with_a_given_up_dropcommits its reader only after the drop at line 322 returns, and main's drop waits for the reader. A later change that removed the bound would stall the CI job until its 40-minute timeout. Atokio::time::timeoutaround that drop would make the test fail with a message. - Line 152 logs a failed leftover drop at debug level, and the next pass tries it again. A failure that repeats, such as a missing privilege, then never reaches the warn log. A warn for an error other than a lock wait would show it.
I found no other open or recent PR that changes this drop or names #606.
| .map_err(|e| StorageError::Internal(format!("TTL index drop failed: {e}")))?; | ||
|
|
||
| Ok(()) | ||
| self.drop_ttl_index_bounded(&index_name).await |
There was a problem hiding this comment.
The retry lets an enable run between two attempts of this drop, and a later attempt can then drop the enable's new index. The index name carries no attribute. The sequence:
- A reader holds the table. A disable of
expcommits its catalog flip, and this drop starts its attempts. - An enable on
exp2commits. Itscreate_ttl_indexfinds theexpindex and starts its own bounded drop. - The reader ends. The enable's drop wins and removes the
expindex, andCREATE INDEX CONCURRENTLYbuildsexp2. - The disable's next attempts wait behind the build and time out. After the build, an attempt inside the 5 s budget drops the
exp2index and returnsOk. - The enable publishes
ttl_index_ready = TRUEover no index. Neither the worker pass norretry_pending_indexesrebuilds it, so each 60 s sweep scans the whole table.
On main the drop stays in the lock queue ahead of the build's lock request, so the build always comes after the drop. If the drop holds the catalog row FOR UPDATE across its attempts, as drop_leftover_ttl_indexes does, the enable waits for it. A check of pg_get_indexdef against the disabled attribute (_ttl_attribute, line 504) before each attempt would narrow the window. The index can still change between that check and the drop.
There was a problem hiding this comment.
Thanks, confirmed and fixed in 1283ec9 (merged with main in 202c033). drop_ttl_index now locks the tables row FOR UPDATE, rechecks that ttl_attribute is still NULL, and holds the row across every attempt, so the enable's update_ttl waits for the drop instead of committing between two attempts. If an enable committed before the drop took the row, the drop returns without dropping: the index is then the enable's, and create_ttl_index keeps or replaces it by its definition. create_ttl_index's own replacement drop takes the row the same way and rechecks its attribute.
I did not add the pg_get_indexdef check before each attempt. With the row held, ttl_attribute cannot change during the attempts, and every index on a table whose TTL is off is one to drop.
Every path takes the catalog row before the data table, as DeleteTable does. On one shared database the attempts run in savepoints of the row's transaction, so a disable holds one pooled connection. With a separate data database each attempt is its own data transaction. A deferred CREATE INDEX CONCURRENTLY takes no row lock, and the drop's attempts time out behind it, so the two cannot wait on each other for longer than the 5 s budget.
an_enable_during_a_retrying_disable_drop_waits_for_the_drop reproduces your sequence: a reader holds the table, the disable's drop starts, and 600 ms later an enable on exp2 starts. At c3efcd8 it fails with the enable committed while the disable's drop was still retrying (left: Some("exp2")). a_disable_drop_after_a_later_enable_keeps_the_enable_index runs step 4 alone. At c3efcd8 the late drop removed the exp2 index. Both pass at the new head. They run only the shared-database path, and I did not test the separate data database path locally.
A disable's bounded drop retries, and between two attempts an enable on another attribute could drop the old index and build its own; a later attempt then dropped the new index, and the enable published ttl_index_ready = TRUE over no index. drop_ttl_index now locks the table's catalog row FOR UPDATE, rechecks that ttl_attribute is still NULL (an enable that committed first owns the index), and holds the row across every attempt, so an enable's catalog update waits for the drop. create_ttl_index's replacement drop takes the row the same way and rechecks its attribute. Every path locks the catalog row before the data table, as DeleteTable does. On one shared database the attempts run in savepoints of the row's transaction, so a disable holds one pooled connection. Each attempt now uses data::set_lock_timeout with delete_table::SYNC_DROP_LOCK_TIMEOUT (1 s) instead of its own 200 ms. The worker pass logs a leftover drop that fails for a reason other than a lock wait at warn. The test file uses tests/common/stream_disable_fixture.rs, bounds the given-up drop with tokio::time::timeout, and adds tests for the interleaving and for a late disable drop. The docs describe the disable's wait and add a v1.2.0 upgrade-manual entry. Signed-off-by: Hitesh Sharma <hts@amazon.com>
…timeout Signed-off-by: Hitesh Sharma <hts@amazon.com>
|
Thanks @LeeroyHannigan. I answered the race in its thread. These commits cover the smaller points: 1283ec9, and the merge of main in 202c033.
Local runs: |
LeeroyHannigan
left a comment
There was a problem hiding this comment.
Approve. The push fixes the round 1 condition. The disable's index drop now holds the table's catalog row from its first attempt until it commits. An enable that runs during the drop waits for that row. A drop that finds an enable already committed returns without dropping, so the enable keeps its index.
I built the branch at 202c033 and ran the tests that cover the change. The five tests in ttl_index_drop_lock.rs passed three times each. The storage-postgres library tests passed, 94 of 94. I then changed the fix in two ways, to check the tests catch a regression. With the recheck removed from drop_ttl_index, a_disable_drop_after_a_later_enable_keeps_the_enable_index fails, as it should. Against the previous head c3efcd8, the new interleaving test fails. That is the sequence the PR set out to fix.
CI is green at this head. 69 of 69 checks pass, and the PostgreSQL storage job ran the five tests.
Duplication and size. No other open PR changes the TTL index drop. #599 also edits metadata_engine.rs, but for the DELETING window. Its hunks do not meet this change. Four PRs add text at the same point of the two docs this PR edits. In the upgrade manual they are #1446, #1411 and #1131. In the differences table it is #1154. Each is a different change, so whichever merges second re-places its own lines. The change is production +234 and -34, tests +321, docs +11 and -2. It adds no second copy of a check. The commit removes the set_config statement, the drop timeout and the copied test harness that round 1 named.
The points below are not conditions for approval:
- The drop can run about 6 s, not the 5 s the docs and the body give. An attempt now waits up to 1 s. The code checks the deadline only after an attempt fails, so the fifth attempt can start at 5.0 s and run its full second. I put the text to use inline on the two docs.
- The recheck in
create_ttl_index's replacement path has no test. Nor does the drop under a separate data database. One test over both table layouts covers the second gap. A held-row test covers the first. - Two nits inline. One is a reset of
ttl_index_readythat changes nothing. The other is a test header that names one of the five tests.
|
|
||
| **What changed** (#606). `UpdateTimeToLive` with `Enabled: false` drops the table's TTL index. The drop needs `ACCESS EXCLUSIVE`, and in 1.1.0 it waited with no timeout: behind a long reader, such as a table snapshot or an in-catalog backup, every later request on the table queued behind it until the reader finished. The drop now waits at most 1 s per attempt and retries for up to 5 s, so a reader stalls the table's other requests for at most 1 s at a time. The disable's answer changes in two ways: | ||
|
|
||
| - The call can take up to about 5 s longer while a reader holds the table. An `UpdateTimeToLive` that enables TTL on the same table during that wait waits for it. |
There was a problem hiding this comment.
Two small corrections for this line.
The wait is about 6 s, not 5 s. An attempt waits up to 1 s. The code checks the deadline only after an attempt fails. The attempts start at 0, 1.25, 2.5, 3.75 and 5.0 s, and the fifth runs its full second. Either write "up to about 6 s", or cap each attempt by the time left so the 5 s holds.
An enable is one of several callers that wait. The drop holds the table's tables row. Every catalog write on that row waits for it: a second UpdateTimeToLive, UpdateTable, DeleteTable, a stream change, a warm throughput update. Reads do not wait. Suggested text: "Control-plane calls on the same table wait for the drop. Reads do not."
| | TTL attribute value validation | Non-conforming values are ignored | Cassandra matches: only a positive integral `N` is expired, and missing, non-numeric, fractional, zero, and negative values are ignored. | | ||
| | `UpdateTimeToLive` response timing | Returns immediately; the change takes effect asynchronously (up to about an hour) | Matches: the call returns once the catalog flip is durable. The Cassandra queue backfill runs in the background with a durable per-page cursor (a failed host's retry resumes rather than rescanning), and the disable drain is finished by the worker. | | ||
| | `DescribeTimeToLive` transitional states | `ENABLING` and `DISABLING` are reported while a change settles | Matches on Cassandra (all four states; `ENABLED` means the queue covers every item) and on PostgreSQL for enable (`ENABLING` until the concurrent index build publishes; its disable is synchronous so `DISABLING` never appears). During `DISABLING`, `AttributeName` is absent, unlike DynamoDB. Updates are rejected while a transition is settling, as in DynamoDB. | | ||
| | `UpdateTimeToLive` response timing | Returns immediately; the change takes effect asynchronously (up to about an hour) | Matches: the call returns once the catalog flip is durable, except a PostgreSQL disable, which also waits up to 5 s to drop the TTL index; a drop that gives up (a long reader holds the table) still answers 200 and is finished by the TTL worker's next pass, and an enable sent during that wait waits for it. The Cassandra queue backfill runs in the background with a durable per-page cursor (a failed host's retry resumes rather than rescanning), and the disable drain is finished by the worker. | |
There was a problem hiding this comment.
Same timing point as the upgrade manual. This line says "waits up to 5 s to drop the TTL index". The drop can run about 6 s. Use the same figure in both files.
| .await | ||
| .map_err(|e| StorageError::Internal(e.to_string()))?; | ||
| let current: Option<i32> = sqlx::query_scalar( | ||
| "SELECT 1 FROM tables WHERE table_id = $1 AND ttl_attribute = $2 FOR UPDATE", |
There was a problem hiding this comment.
This recheck has no test. With the condition removed, all five tests still pass. It guards a create_ttl_index whose attribute stopped being current between the read above and this row lock. Without it, that call drops the current attribute's index by name, and the readiness update below does not repair it. A test could hold the row, start a replacement for one attribute, set the attribute back, commit, then check the first index survives. Not a condition.
| .execute(&self.pool) | ||
| .await | ||
| .map_err(|e| StorageError::Internal(e.to_string()))?; | ||
| sqlx::query("UPDATE tables SET ttl_index_ready = FALSE WHERE table_id = $1") |
There was a problem hiding this comment.
This reset of ttl_index_ready changes nothing. The drop runs only when ttl_attribute is NULL. The one statement that sets it NULL already sets ttl_index_ready FALSE. On a give-up, the row transaction rolls back. The line can go, or a comment can name the path that leaves the row ready with a NULL attribute. Not a condition.
Main is at e8b5f10, three commits past 01556cf: #481, #1137 and #1403. #1403 adds a v1.2.0 entry for #606 at the top of "Behavior Changes by Release" in docs/manuals/07-upgrade-manual.md, where this branch adds its v1.2.0 entry. That is the one conflict. The merge keeps both entries, the entry of main first. Git merged crates/engine/src/lib.rs with no conflict. Main adds a test module there, and this branch adds serialization_exception.
The base merges main at e8b5f10 through #1260, which brings #481, #1137 and #1403. #1403 adds a v1.2.0 entry for #606 at the top of "Behavior Changes by Release" in docs/manuals/07-upgrade-manual.md, above the entry of #1260. Git merged the file with no conflict, so the order is #606, #1260, then the entry of this branch.
Main is at c8e66fb, six commits past 01556cf: #481, #1137, #1403, #1465, #1515 and #1411. #1403 and #1411 add v1.2.0 entries at the top of "Behavior Changes by Release" in docs/manuals/07-upgrade-manual.md, where the entry of this branch goes next. The merge has no conflict. Git merged crates/core/src/types/table.rs and crates/engine/src/lib.rs at other lines. In table.rs, main changes the members of a DELETING table in TableDescription, and this branch adds the ReplicaUpdates member of UpdateTableInput. In lib.rs, main declares a test module, and this branch declares nested_enums and adds enum_constraint. The lines that this branch changes are the same before and after the merge.
The base merges main at c8e66fb, which brings #481, #1137, #1403, #1465, #1515 and #1411, and adds the v1.2.0 entries of #1110 and #1114 to docs/manuals/07-upgrade-manual.md. The merge has no conflict. Git merged two files at other lines. In crates/core/src/types/table.rs, main changes the members of a DELETING table in TableDescription, and this branch changes the doc comment of the SSESpecification member of UpdateTableInput. In crates/storage-mongodb/src/table_engine.rs, main makes the creation time of a table description optional, and this branch records the specification in update_table.
UpdateTimeToLive reads the table's status after its write, so that it sends no index statement for a DELETING table. A failed read skipped the index statements too. For an enable, the TTL worker's pending-index pass builds the index later. A disable left the index on the ACTIVE table, and on SQLite and MongoDB no later pass drops it. Now a failed read skips an enable's index work only, and a disable's drop runs. The comment on the skip said that a PostgreSQL drop waits with no lock timeout. Since #1403, merged from main, the drop retries for up to 5 s behind a holder, and the comment now says so. The new PostgreSQL test renames table_restores for the call, so that describe_table fails and the TTL write does not. The disable answers 200 and drops the index.
What
On PostgreSQL,
UpdateTimeToLivewithEnabled: falsenow bounds the lock wait of itsDROP INDEX. The drop (drop_ttl_index_bounded) makes attempts that each wait at mostdelete_table::SYNC_DROP_LOCK_TIMEOUT(1 s, set withdata::set_lock_timeout), and retries lock-wait failures (55P03, 40P01, 57014, viadata::lock_wait_failed) after a 250 ms pause for up to 5 s. If the budget runs out it returns the error, whichUpdateTimeToLivealready logs, and the disable still answers 200.The catalog row is held across the attempts.
drop_ttl_indexlocks the table'stablesrowFOR UPDATE, rechecks thatttl_attributeis still NULL, and keeps the row until the drop commits or gives up. An enable'supdate_ttltherefore waits for the drop, so it cannot build its index between two attempts, where a later attempt would drop it (the nameidx_ttl_<table>carries no attribute). If an enable committed before the disable's drop took the row,ttl_attributeis not NULL and the drop does nothing: the index is the enable's, whichcreate_ttl_indexkeeps or replaces by its definition. Every path locks the catalog row before the data table, asDeleteTabledoes:shared_data_pool), each attempt runs in a savepoint of the row's transaction, so a disable holds one pooled connection, not two.A
CREATE INDEX CONCURRENTLYthat runs during a disable's drop (a deferred build of an attribute that is no longer current) takes no catalog row lock, and the drop's attempts time out behind it, so the two cannot wait on each other for longer than the 5 s budget.If the drop gives up, the index on the old attribute is not left behind for good:
idx_ttl__ddb_*indexes with onepg_classquery on the data database, keeps those whose catalog row hasttl_attribute IS NULLwith one catalog query, and drops each with the same bounded drop. It holds that catalog rowFOR UPDATE SKIP LOCKEDwhile it drops and rechecks that TTL is still off; a row another request holds is skipped until the next pass. A drop that fails on a lock wait is logged at debug and retried next pass; any other failure (for example a missing privilege) is logged at warn.create_ttl_indexalready dropped an INVALIDidx_ttl_<table>before itsCREATE INDEX CONCURRENTLY IF NOT EXISTS. It now also drops a valid one whosepg_get_indexdefdoes not index the requested attribute, with the bounded drop, holding the catalog rowFOR UPDATEand rechecking thatttl_attributeis still the requested one. If that drop gives up, it returns the error, sottl_index_readyis not published and the existing deferred build retries.Until one of these runs, the leftover index's
::BIGINTcast still applies to writes of the old attribute (see below).Why
Part of #606 (the disable half; see "Not in this PR").
The drop needs
ACCESS EXCLUSIVE. With nolock_timeout, behind a long reader it waited until the reader finished, and every later lock request on the table queued behind it, so the table's reads and writes stalled for as long as the reader held the table. With the timeout, a queued drop blocks other requests for at most one attempt (1 s, the boundDeleteTabledocuments for the same stall) at a time, and the drop completes once the reader is gone.Not in this PR: the issue's second point, that
CREATE INDEX CONCURRENTLYon enable delays a table delete by the length of the build. That is a different code path and I would handle it separately.Testing done
Storage tests in
crates/storage-postgres/tests/ttl_index_drop_lock.rs, each on its own scratch database fromtests/common/stream_disable_fixture.rs(one database for catalog and data, so the savepoint path):a_ttl_disable_behind_a_reader_does_not_stall_the_table_and_completes_after: a transaction holdsACCESS SHAREon the data table, the disable starts, a read of the table must still finish within 2 s, then the reader is released and the drop must complete and remove the index. Against the unbounded drop it fails with "a read queued behind the index drop".the_ttl_worker_drops_an_index_a_disable_left_behind: the reader is held past the 5 s budget so the disable's drop gives up and theexpindex stays; after the reader is released, the worker's pass (drop_leftover_ttl_indexes, through a test hook) drops one index and none is left. The given-up drop is wrapped in a 30 stokio::time::timeout, so an unbounded drop fails the test instead of hanging the job.a_re_enable_on_another_attribute_replaces_an_index_a_disable_left_behind: after the same given-up drop, TTL is enabled onexp2; the index'spg_get_indexdefmust name'exp2'and not'exp', andttl_index_readymust be TRUE.an_enable_during_a_retrying_disable_drop_waits_for_the_drop: with a reader holding the table, the disable's drop starts; 600 ms later an enable onexp2(update_ttlthencreate_ttl_index) starts; 1.5 s later the catalog'sttl_attributemust still be NULL. Then the reader is released, both must finish, and the index must indexexp2with readiness TRUE. At c3efcd8 it fails:the enable committed while the disable's drop was still retrying,left: Some("exp2").a_disable_drop_after_a_later_enable_keeps_the_enable_index: disable, enable onexp2and its build, then the disable's drop runs late. Theexp2index and readiness TRUE must stay. At c3efcd8 it fails withthe exp2 index stays(the late drop removed it).The tests cover the shared-database layout only; the separate data database path (one data transaction per attempt) is not exercised by a local test.
Separately, on
origin/main(5489d29) with TTL enabled onexp, a storage-level PutItem withexp=1.5or1E+30already fails withinvalid input syntax for type bigint(an internal error), while12345succeeds. That comes from the same index cast and is not changed here; this PR only stops it from outliving a disable.I did not run
cargo test --workspaceor the pytest suites locally; I am relying on CI for those.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).
Clippy ran with
-D warnings(the CI setting), not-W clippy::pedantic.docs/differences-from-dynamodb.md(theUpdateTimeToLivetiming and transitional-state rows) and av1.2.0entry under Behavior Changes by Release indocs/manuals/07-upgrade-manual.mddescribe the disable's wait and the worker's retry.ADR / RFC: n/a (internal fix; no wire, trait, auth, on-disk or CLI change)
Breaking changes
None.
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.