Repository navigation
fix(jobs): Job.refresh() stays fast when key_source is restricted by part tables - #1674
Conversation
refresh() removed jobs whose keys had left key_source with DELETE ... WHERE key NOT IN (key_source). MySQL materializes that subquery, and when key_source is restricted by two part tables (A * B & A.Part & B.Part) it builds the materialized key_source as the join of both parts: the product of their rows. With 21,087 and 6,407 parts per master and two masters, each refresh() took about 110 s on MySQL 8.0, so a loop that refreshes before every populate() spent minutes per cycle on a key_source of two keys. The cleanup now counts the candidate jobs, then counts the key_source keys restricted to them, with key_source at the top level of the query. Equal counts mean nothing vanished. Otherwise the keys are compared and the vanished jobs deleted by key, in batches. Same reproduction: 0.02 s. test_refresh_cleanup_is_set_based now uses 50 vanished keys, since the cleanup issues a few more statements (still a fixed number).
When the counts show that some candidate jobs have left key_source, _delete_vanished() fetched every candidate key and every present key_source key at once. With keep_completed=True the stale-job step's candidates are all old success jobs, so a single vanished key loaded the whole jobs table into memory. The comparison now reads the candidates one page of VANISHED_DELETE_BATCH keys at a time, ordered by key, and deletes each page's vanished jobs in one statement. Memory is bounded by the page size; the common case (nothing vanished) is still two counts. New tests use a master with two part tables and a key_source that requires rows in both (Master & Master.PartA & Master.PartB): - vanished success and error records are removed at once, a vanished key that still has a target row goes after stale_timeout, and the other jobs are kept; - no statement issued by refresh() nests the part tables inside a NOT IN subquery (fails before the fix on both backends); - with a page size of 2, vanished keys on and inside page boundaries are all removed.
A page of keys that do not match their own values as a restriction (an inexact float32 key, for example) was neither found present nor deleted, and the cursor did not move, so refresh() read the same page forever. The cursor now advances by the rows each page leaves in place, and a test covers a float32 key on both backends. Also drop the test schemas with the adapter's DROP statement, which is DROP SCHEMA ... CASCADE on PostgreSQL, and state the re-restriction guarantee in the docstring precisely.
…rtcut Job._delete_vanished() runs against an in-memory stand-in for the jobs table and key_source: nothing vanished deletes nothing, vanished keys on and inside page boundaries are all removed, only candidate jobs are removed, and a page of keys that cannot be matched by value does not stop the cleanup.
…sh() Replace the paged cleanup with the single DELETE per step that refresh() used before, but check jobs against key_source through a SELECT DISTINCT derived table instead of nesting key_source in NOT IN directly. MySQL cannot merge such a derived table into the surrounding query, so it computes key_source once, with the plan it gets on its own, instead of flattening a part-table restriction into the NOT IN and building the join of the part tables. The paging read every candidate key and its key_source match into Python, which made refresh() several times slower than before for an ordinary key_source whenever many old jobs were candidates and at least one had vanished. The derived table keeps the earlier statement count and semantics, and removes the paging's check-then-delete window and its exception for keys that do not match their own values.
MilagrosMarin
left a comment
There was a problem hiding this comment.
Thanks @dimitri-yatsenko for the fix and the detailed write-up. I checked out the branch with master merged in and ran it against MySQL 8.0.46 and PostgreSQL 15.
- Unit tests (1078) and the full suite (2064 passed, 18 skipped) pass. With master's jobs.py restored, test_refresh_does_not_join_the_parts[mysql] and test_refresh_negates_key_source_only_as_a_derived_table (both backends) fail, so the new tests guard the change.
- The win is real when MySQL picks materialization. With the issue's shape (2 profiles x 10,000 parts, 1 grouping x 3,000 parts), fresh statistics and firstmatch/loosescan/duplicateweedout turned off, refresh() went from 49.1 s on master to 0.03 s on this branch.
- With the same data before ANALYZE TABLE (stale statistics right after the bulk insert), key_source alone took about 17 s, and refresh() took about 45 s on master and about 65 s on this branch, across reruns. EXPLAIN showed the derived table built with DuplicateWeedout over the join of the two part tables. After ANALYZE TABLE, both versions took 0.02-0.03 s. So the derived table helps when key_source's own plan is good, and can be slower when it is not. Could the description say that the speedup depends on key_source's own plan, rather than that key_source "takes milliseconds"?
- PostgreSQL timings are unchanged (0.02 s for the issue shape, 0.04 s for 20,000 jobs).
- Overlap with #1663: merged locally on top of this branch, test_refresh_negates_key_source_only_as_a_derived_table fails on both backends ("refresh() no longer checks jobs against key_source") because it scans for "NOT IN (" and #1663 emits NOT EXISTS. The other 23 tests pass with both PRs merged. Whichever PR lands second will need to update this test, for example by matching both forms.
Could you update the test (or note the merge order with #1663) and adjust the performance wording?
MilagrosMarin
left a comment
There was a problem hiding this comment.
Thanks @dimitri-yatsenko for rewording the description. The performance section now says the speedup depends on how MySQL plans key_source and includes the stale-statistics case, which covers my earlier point.
One item is still open: test_refresh_negates_key_source_only_as_a_derived_table still matches only "NOT IN (", so it will fail once #1663 lands, since that PR emits NOT EXISTS. Could you either make the test accept both forms, or note in the description that whichever PR merges second updates this test?
Happy to approve once that is settled.
|
Thanks @MilagrosMarin. 97c147a: |
MilagrosMarin
left a comment
There was a problem hiding this comment.
Thanks @dimitri-yatsenko. 97c147a resolves the remaining item: _negated_subqueries now matches both NOT IN and NOT EXISTS, and #1663's complement (NOT EXISTS (SELECT 1 FROM (SELECT ... FROM ()) ...)) still exposes the SELECT DISTINCT derived table to the check, so the test holds whichever PR lands first.
Optional: the docstring names "#1663 (v2.4)". Something like "the complement may compile to either form" would age better than a PR reference. Not blocking.
Approving, pending green CI.
Summary
Job.refresh()removed jobs whose keys had leftkey_sourcewithDELETE ... WHERE (pk) NOT IN (key_source). Whenkey_sourceis restricted by part tables, for exampleA * B & A.Item & B.Item, MySQL flattens the part restrictions inside that subquery into joins and deduplicates only at the end. It then builds the join of the part tables before reducing it to the few keys inkey_source. In the case from the issue (2 keys, part tables of 42,000 and 6,400 rows), onerefresh()takes about two minutes on MySQL 8.0 (measured below), whilekey_sourceon its own takes milliseconds when MySQL plans it well. A loop that refreshes before eachpopulate()pays that on every pass.Now
refresh()checks jobs againstkey_sourcethrough aSELECT DISTINCTderived table:MySQL does not merge a derived table that has
DISTINCTinto the query around it, so it computes the keys ofkey_sourceonce, with the plankey_sourcegets on its own, and then anti-joins the jobs against them. PostgreSQL already evaluated the subquery once and is unaffected. Each cleanup step is still oneDELETE, as on master.Fixes #1673
Changes
Job._materialized_key_source()returns the keys ofkey_sourceas that derived table. Steps 3a and 3b ofrefresh()restrict by its negation instead of bykey_source.proj(). Nothing else inrefresh()changes. The wrapping works for anykey_sourceexpression, including aggregations, unions anddj.Top.key_sourcepage by page in Python. It maderefresh()several times slower than master for an ordinarykey_sourcewhenever many old jobs were candidates and at least one had vanished (measured below), so it is replaced. Its unit tests (tests/unit/test_jobs_delete_vanished.py) and its change totest_refresh_cleanup_is_set_basedare removed with it.float32key) and could remove a job whose key returned tokey_sourcebetween the check and theDELETE. None of this applies to the current change, which keeps master's statements and semantics.Behavior change
None other than speed:
refresh()issues the same statements as on master, with the same restrictions, and removes the same jobs.Performance
Seconds per
refresh(stale_timeout=60)withkeep_completed=True, one run each on local Docker containers; differences under about 0.05 s are noise. "Paged" is the earlier version of this PR.key_sourceis the parent table; 100,000 old success jobs, and 0 or 10 pending jobs whose parent rows were deleted.Profile * Grouping & Profile.Item & Grouping.Itemwith 2 keys and part tables of 42,000 and 6,400 rows; nothing vanished, or one key leftkey_sourcewhile its target row stayed. "Forced" turns off MySQL's other semijoin strategies (firstmatch,loosescan,duplicateweedout), as the test below does.Master & Master.PartA & Master.PartBwith 100,000 masters of one part row each, 100,000 old success jobs, and 0 or 10 keys that leftkey_source.On PostgreSQL the derived table adds a few hundredths of a second for 100,000 jobs.
The speedup depends on how MySQL plans
key_sourceitself, becauserefresh()now buildskey_sourceonce as a derived table. With current table statistics,key_sourcetakes milliseconds andrefresh()with it. With stale statistics (for example right after a bulk insert, beforeANALYZE TABLE),key_sourcealone can take seconds, andrefresh()can be slower than on master: in one reviewer run on the issue's shape, about 65 s against 45 s. AfterANALYZE TABLEboth took 0.02–0.03 s.Tests
tests/integration/test_jobs_refresh_part_restricted.py, on MySQL and PostgreSQL:test_refresh_master_with_two_parts: a master with two part tables andkey_source = Master & Master.PartA & Master.PartB, with four success and two error jobs. After a master is deleted and a part of each of two others,refresh()removes the vanished success and error records at once. The vanished key whose target row remains is removed afterstale_timeout. All other jobs are kept.test_refresh_negates_key_source_only_as_a_derived_table: records every statementrefresh()issues and asserts that eachNOT IN (...)that mentions the part tables reaches them through aSELECT DISTINCTderived table. It fails on master on both backends.test_refresh_does_not_join_the_parts(MySQL only): two masters with 3,000 parts each and one master with 2,000 parts, with MySQL's materialization strategy forced throughoptimizer_switch. On masterrefresh()exceeds the 2 s limit and the test fails; with this change it passes.test_refresh_removes_only_vanished_jobs: vanished success and pending jobs, first, last and in between, are removed, and the rest kept.test_refresh_removes_jobs_of_vanished_keys: the same checks forkey_source = A * B & A.Item & B.Item.test_refresh_removes_vanished_inexact_keys: jobs withfloat32keys, one of them stored inexactly, are removed when their keys vanish.The existing tests in
tests/integration/test_jobs_refresh.pypass unchanged. The full test suite passes locally on both backends.