fix(retain): match chunk-delete link endpoints through indexable joins (#3387) - #3393
Merged
Conversation
#3387) The ordered memory_links pre-delete in delete_chunks_by_ids matched link endpoints with `tu.id = ml.from_unit_id OR tu.id = ml.to_unit_id`. An OR spanning two columns of ml cannot be driven from either endpoint index, so PostgreSQL made memory_links the outer relation of a nested-loop semi join and sequentially scanned the whole table on every delete — O(links x units), with no bank_id predicate, so every bank scanned every other bank's rows. Past a few million links that exceeded the asyncpg command timeout and delta retain failed with a bare TimeoutError (str(TimeoutError()) is empty, so it logged as "Task execution failed: batch_retain, error:" with nothing after). Splitting the OR into a UNION of two single-column joins makes each half an index scan. Measured on PG18 with the current index set, 300k units / 1.5M links, deleting the links of 3 chunks (150 units): before 20,420 ms Seq Scan, 224.9M rows removed by join filter after 31 ms two index scans, same 1,464 rows 10 chunks took 49.8s before — already over the 60s default at a table size well below production. The row set is identical (EXCEPT in both directions returns nothing), and the deterministic ORDER BY + FOR UPDATE that #2570 added stay in ordered_links, which still locks the rows in that order.
#3388 moved the store capability to writes_memory_rows_in_sql_for(bank_id) and added drop_bank_storage, but two duck-typed test doubles still carried the old surface, so test-api shard 2 has been red on main since it merged: test_integrity_violation_not_retried — SimpleNamespace(writes_memory_rows_in_sql=True) -> AttributeError: no attribute 'writes_memory_rows_in_sql_for' test_list_banks_non_sql_store._NonSqlStore — teardown's delete_bank routes the drop through the store for a non-SQL bank -> AttributeError: no attribute 'drop_bank_storage' Both doubles are hand-rolled rather than subclasses of the store base, which is why the refactor could not update them mechanically.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #3387.
The problem
The ordered
memory_linkspre-delete indelete_chunks_by_idsmatched link endpoints with a single predicate:An
ORspanning two columns ofmlcannot be driven from either endpoint index, so PostgreSQL makesmemory_linksthe outer relation of a nested-loop semi join and sequentially scans the whole table on every delete —O(rows_in_memory_links x target_units). There is nobank_idpredicate either, so each bank's delta retain scans every other bank's rows too.Past a few million links this exceeds the asyncpg command timeout and delta retain fails with a bare
TimeoutError. Becausestr(TimeoutError())is empty, it surfaces asTask execution failed: batch_retain, error:with nothing after it.The fix
Split the
ORinto aUNIONof two single-column joins, so each half is an index scan on the existingidx_memory_links_from_type_weight/idx_memory_links_to_type_weight. The deterministicORDER BYandFOR UPDATE OF mlthat #2570 introduced stay inordered_links, which still locks the rows in that order (LockRowssits aboveSortin the plan, before and after).Measurements
Reproduced on PostgreSQL 18 with the current shipped index set, 300k units / 1.5M links, running the emitted statement verbatim (the full
DELETE ... USING, not a count):10 changed chunks already blew the 60s default at a table size well below production, which matches the reporter's finding that raising the timeout to 120s did not move the failure rate.
Row sets are identical —
EXCEPTin both directions returns zero.Tests
test_delete_chunks_by_ids_matches_link_endpoints_through_indexable_joins— asserts the endpoint match stays two single-column joins and the OR-across-columns predicate is not reintroduced.test_delete_chunks_by_ids_sweeps_links_on_both_endpoints— real-DB equivalence guard: a link is now matched twice, once from each side, so a rewrite that dropped one arm would silently leave half the links to the FK cascade and reopen the Fix chunk delete deadlock ordering #2570 deadlock. Seeds a link in each direction on the doomed unit plus one between survivors, and asserts only the survivors' link remains.Deliberately not in this PR
bank_idpredicate. The UNION removes the whole-table scan, which was the actual cost;bank_idwould be redundant given uuid endpoints, andbank_idis an optional argument of this function.link_utils.bulk_insert_linkssorts by(from_unit_id, to_unit_id)while this delete orders by(LEAST, GREATEST, link_type, COALESCE(entity_id, ...))— different orders, so INSERT-vs-DELETE cycles are not covered by either. That is a separate defect from the timeout and is worth its own issue.ctidandDELETE ... USINGpass through_rewrite_pg_to_oracleuntouched, and neither is valid Oracle. The rewrite keeps exactly that shape, so Oracle behaviour is unchanged. Filed separately rather than widened into this fix.Also in this PR: two test doubles broken by #3388
test-apishard 2 has been red onmainsince #3388 landed — unrelated to this fix, but it blocks the shard, so it is repaired here:test_integrity_violation_not_retriedstubbed the store asSimpleNamespace(writes_memory_rows_in_sql=True); the capability is now consulted per bank aswrites_memory_rows_in_sql_for(bank_id).test_list_banks_non_sql_store._NonSqlStorelackeddrop_bank_storage, which the test's owndelete_bankteardown routes through the store for a non-SQL bank.Both doubles are hand-rolled rather than subclasses of the store base, which is why #3388 could not update them mechanically.