Skip to content

fix(jobs): Job.refresh() stays fast when key_source is restricted by part tables - #1674

Merged
dimitri-yatsenko merged 8 commits into
masterfrom
fix/refresh-vanished-keys
Dec 1, 2026
Merged

dimitri-yatsenko merged 8 commits into
masterfrom
fix/refresh-vanished-keys

Conversation

@dimitri-yatsenko

@dimitri-yatsenko dimitri-yatsenko commented Nov 10, 2026 •

Copy link
Copy Markdown
Member

Summary

Job.refresh() removed jobs whose keys had left key_source with DELETE ... WHERE (pk) NOT IN (key_source). When key_source is restricted by part tables, for example A * 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 in key_source. In the case from the issue (2 keys, part tables of 42,000 and 6,400 rows), one refresh() takes about two minutes on MySQL 8.0 (measured below), while key_source on its own takes milliseconds when MySQL plans it well. A loop that refreshes before each populate() pays that on every pass.

Now refresh() checks jobs against key_source through a SELECT DISTINCT derived table:

... AND (pk) NOT IN (SELECT pk FROM (SELECT DISTINCT pk FROM (<key_source>) AS a) AS b)

MySQL does not merge a derived table that has DISTINCT into the query around it, so it computes the keys of key_source once, with the plan key_source gets 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 one DELETE, as on master.

Fixes #1673

Changes

  • New Job._materialized_key_source() returns the keys of key_source as that derived table. Steps 3a and 3b of refresh() restrict by its negation instead of by key_source.proj(). Nothing else in refresh() changes. The wrapping works for any key_source expression, including aggregations, unions and dj.Top.
  • An earlier version of this PR compared candidate jobs with key_source page by page in Python. It made refresh() several times slower than master for an ordinary key_source whenever 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 to test_refresh_cleanup_is_set_based are removed with it.
  • The earlier description was also inaccurate. It said the cleanup issued a fixed number of statements, but the paged version issued about two statements per 1,000 candidate jobs. It said the set of jobs removed and kept was unchanged, but the paged version kept a job whose key could not be matched by its own value (such as an inexact float32 key) and could remove a job whose key returned to key_source between the check and the DELETE. 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) with keep_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.

  • Simple: key_source is the parent table; 100,000 old success jobs, and 0 or 10 pending jobs whose parent rows were deleted.
  • Issue: the case from the issue, Profile * Grouping & Profile.Item & Grouping.Item with 2 keys and part tables of 42,000 and 6,400 rows; nothing vanished, or one key left key_source while its target row stayed. "Forced" turns off MySQL's other semijoin strategies (firstmatch, loosescan, duplicateweedout), as the test below does.
  • Parts, many jobs: Master & Master.PartA & Master.PartB with 100,000 masters of one part row each, 100,000 old success jobs, and 0 or 10 keys that left key_source.
Case MySQL 8.0 master MySQL 8.0 paged MySQL 8.0 this PR MySQL 8.4 master MySQL 8.4 this PR PostgreSQL 15 master PostgreSQL 15 paged PostgreSQL 15 this PR
Simple, 0 vanished 0.37 0.40 0.42 0.25 0.27 0.09 0.10 0.14
Simple, 10 vanished 0.38 3.72 0.41 0.26 0.26 0.08 2.70 0.12
Issue, 0 vanished 116 0.02 0.01 57 0.01 0.01 0.01 0.01
Issue, 1 vanished 58 0.03 0.09 29 0.02 0.01 0.01 0.01
Issue, forced, 0 vanished 236 0.03 0.06 114 0.04
Issue, forced, 1 vanished 119 0.05 0.06 58 0.02
Parts, many jobs, 0 vanished 0.87 0.56 0.84 0.48 0.50 0.39 0.39 0.41
Parts, many jobs, 10 vanished 0.81 4.08 0.87 0.48 0.52 0.37 19.87 0.42

On PostgreSQL the derived table adds a few hundredths of a second for 100,000 jobs.

The speedup depends on how MySQL plans key_source itself, because refresh() now builds key_source once as a derived table. With current table statistics, key_source takes milliseconds and refresh() with it. With stale statistics (for example right after a bulk insert, before ANALYZE TABLE), key_source alone can take seconds, and refresh() can be slower than on master: in one reviewer run on the issue's shape, about 65 s against 45 s. After ANALYZE TABLE both 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 and key_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 after stale_timeout. All other jobs are kept.
  • test_refresh_negates_key_source_only_as_a_derived_table: records every statement refresh() issues and asserts that each NOT IN (...) that mentions the part tables reaches them through a SELECT DISTINCT derived 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 through optimizer_switch. On master refresh() 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 for key_source = A * B & A.Item & B.Item.
  • test_refresh_removes_vanished_inexact_keys: jobs with float32 keys, one of them stored inexactly, are removed when their keys vanish.

The existing tests in tests/integration/test_jobs_refresh.py pass unchanged. The full test suite passes locally on both backends.

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.
@dimitri-yatsenko dimitri-yatsenko added this to the v2.3.7 milestone Nov 10, 2026
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.
@dimitri-yatsenko
dimitri-yatsenko marked this pull request as ready for review November 10, 2026 17:38
…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.
@dimitri-yatsenko dimitri-yatsenko changed the title Check vanished jobs in refresh() without nesting key_source in NOT IN fix(jobs): Job.refresh() stays fast when key_source is restricted by part tables Nov 21, 2026
…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 MilagrosMarin left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 MilagrosMarin left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

@dimitri-yatsenko

Copy link
Copy Markdown
Member Author

Thanks @MilagrosMarin. 97c147a: _negated_subqueries now matches both NOT IN ( and NOT EXISTS (, so test_refresh_negates_key_source_only_as_a_derived_table holds whichever of this PR and #1663 lands first. Checked both ways on MySQL and PostgreSQL: on this branch (11 passed, 1 skipped) and with #1663 merged on top (11 passed, 1 skipped).

@MilagrosMarin MilagrosMarin left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

@dimitri-yatsenko
dimitri-yatsenko merged commit 2054a2b into master Dec 1, 2026
25 checks passed
@dimitri-yatsenko
dimitri-yatsenko deleted the fix/refresh-vanished-keys branch December 1, 2026 19:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: Job.refresh() takes minutes when key_source is restricted by part tables (MySQL)

2 participants