Skip to content

Bound due-event selection and replace OFFSET paging - #543

Open
nnlugovoy wants to merge 1 commit into
Automattic:mainfrom
nnlugovoy:issue-517-bounded-event-selection
Open

nnlugovoy wants to merge 1 commit into
Automattic:mainfrom
nnlugovoy:issue-517-bounded-event-selection

Conversation

@nnlugovoy

@nnlugovoy nnlugovoy commented Nov 28, 2026 •

Copy link
Copy Markdown

Fixes #517
Related: #516

Problem

Events::get_events(), the query behind the runner's list-due-batch, loads every due pending row into PHP, including the args longtext, and then trims the result to the queue size. pre_get_cron_option() and pre_clear_scheduled_hook() page with LIMIT/OFFSET, so every page re-scans the table from the start. Both costs grow with the size of the pending queue.

OFFSET paging over ORDER BY timestamp is also not stable when many events share a timestamp. Page boundaries shift between queries, so pre_get_cron_option() can return some events twice and omit others.

Changes

Due-event selection (Events_Store::_query_due_event_candidates())

  • Reads only the rows reduce_queue() can pick, in two queries:
    1. SELECT action_hashed, MIN(timestamp) ... GROUP BY status, action_hashed: a loose index scan, about two index reads per action.
    2. A UNION ALL of per-action ORDER BY timestamp, ID LIMIT <queue size + 1> branches for the <queue size> earliest actions. Internal actions are read without a limit, as before.
  • Selects only ID, timestamp, action_hashed, instance; args is never read. The new index covers the per-action branches, so they are answered from the index alone.
  • The extra row per action makes the candidate set exceed the queue size whenever an action was cut off. The result then goes through the unchanged reduce_queue(), exactly as the full set would, so the output is identical to the old selection. This includes the 15-per-action cap when one action dominates the queue.
  • Until the schema reaches v2, get_events() uses the old query, because without the index the bounded queries would scan the table once per action.
  • Kill switch: add_filter( 'a8c_cron_control_use_projected_event_selection', '__return_false' ).

Paging and bulk unscheduling

  • query_all_events_in_batches(), which pre_get_cron_option() uses, pages by primary key (after_id with orderby => 'ID'). Each page is a short primary-key range read, and every event is returned exactly once. Cron array order is unaffected, because format_events_for_wp() already sorts by timestamp.
  • pre_clear_scheduled_hook() and pre_unschedule_hook() no longer collect every match before acting. They fetch 500 active events with no ordering, complete them, and repeat. Completed events leave the active statuses, so each pass fetches the next batch, and the action/instance index serves the lookup. If an event fails to complete, the loop stops after that batch and returns the existing cron-control:wp:failed-event-deleting error.

Schema v2

  • Adds two indexes:
  • Existing tables are upgraded at shutdown, on WP-CLI requests or page loads by a user with manage_options. Anonymous and REST requests never run the DDL.
    • An upgrade_lock held for 15 minutes prevents concurrent index builds.
    • The version is recorded only after SHOW INDEX, read from the primary database, confirms the expected definitions.
  • interval is declared int(10) unsigned. On MariaDB, int unsigned made dbDelta() issue ALTER TABLE ... CHANGE COLUMN interval on every table check, because core ignores integer display width only on MySQL 8.0.17+.

Other

  • get_events() clamps the queue size to JOB_QUEUE_SIZE_MAX (250), which bounds the candidate query.
  • Tests:
    • The bootstrap reinstalls the table when the schema is behind, because the plugin table survives test reruns but the options table does not.
    • Adds __tests__/load-tests/Event_Selection_Load_Test.php, a benchmark that calls only public API, so the same file runs against any revision.

Performance

Both main (4ccb953) and this branch were run with __tests__/load-tests/Event_Selection_Load_Test.php:

  • Same seeded data for both revisions.
  • MariaDB 10.3.39 with the query cache disabled (the Docker image enables it by default).
  • PHP 8.3 without Xdebug.
  • Median of 5 runs.
  • "Rows" is the delta of the Handler_read_* counters; memory is peak PHP memory.

get_events() at queue size 10 (the runner default):

Scenario Before After
38k rows, 1.3 KB args (#517 shape) 672 ms · 252 MB · 74.8k rows · 54.7 MB transferred 3.6 ms · 0.2 MB · 616 rows · 21 KB
350k rows 84.5 s · 1.68 GB · 620k rows · 343 MB 16 ms · 0.2 MB · 896 rows · 28 KB
50k rows, 5,000 actions 561 ms · 208 MB · 100k rows 55 ms · 3.9 MB · 10.5k rows
20k rows, 50 distinct timestamps 194 ms · 65 MB 2.2 ms · 0.2 MB

At queue size 250: 38k rows goes from 529 to 43 ms; 350k rows goes from 106.9 s to 144 ms, and from 1.69 GB to 59 MB.

pre_get_cron_option():

Scenario Before After
38k rows 5.2 s · 4.07M rows examined 0.81 s · 38k rows examined
50k rows, 5,000 actions 8.4 s · 7.38M rows 0.99 s · 50k rows
20k rows, 50 distinct timestamps 1.4 s · 19,912 of 20,008 events returned 0.21 s · all 20,008 events

On MySQL 8.0.28, EXPLAIN ANALYZE was used to check the query plans; these were not timed:

  • The GROUP BY query uses Using index for group-by.
  • For an action with 15,000 due rows, the per-action branch is a covering index range scan that stops at 251 rows, in 0.8 ms, with no filesort.
  • A wp_next_scheduled()-style lookup for a hook with no rows reads 0 rows. On the v1 schema the same lookup scans the whole unique index.

Correctness

  • The selected events, both the set and the order, match main at queue sizes 10, 50, and 250 in every benchmark scenario without timestamp ties (38k, 50k, and 350k rows).
  • With timestamp ties, main's order, and so which tied events fit in the batch, depends on the query plan. The new code breaks ties by (action_hashed, ID), and its output equals the old reduce_queue() run over the whole queue sorted that way.
  • Two tests compare the bounded and old paths:
    • test_get_events_projected_selection_matches_legacy, across queue sizes 1-250.
    • test_get_events_projected_selection_matches_legacy_for_one_backed_up_action: one action with 100 due rows at queue sizes 10-250. It fails if the per-action limit is reduced to the queue size.

Upgrade

  • On VIP the runner issues WP-CLI commands continuously, so the v2 upgrade runs within seconds of deployment, inside that request's shutdown.
  • InnoDB builds the indexes online, but the ALTER briefly waits for a metadata lock at its start and end.
  • Until the upgrade completes, selection uses the old query, so behaviour is unchanged.
  • Recommended before rollout on large tables: time the upgrade on a production-sized copy.

Testing

  • __tests__/bin/test.sh (MariaDB 10.3, PHP 8.3): 69 tests pass single-site and multisite. The only skips are the multisite-only tests and one test that needs CREATE DATABASE permission.
  • New tests cover:
    • shutdown-upgrade gating (anonymous admin screen versus administrator)
    • no ALTER on an up-to-date table
    • the status index not being required
    • unscheduling more than one batch (1,001 events)
  • PHPCS is clean on includes/ and __tests__/unit-tests/.

Known limitations / follow-ups

  • The candidate query reads at most queue size × (queue size + 1) index rows. That is 110 at the default queue size of 10, and up to 62,750 at 250. A smaller per-action limit would change which events are selected.
  • The status index is redundant with status_action_hashed_ts_id_instance. It is no longer required by the version check, but dropping it needs an explicit migration.
  • Callers passing a queue size above 250 to get_events() now get 250.
  • Bulk unscheduling still issues one UPDATE per event; a set-based update per batch is a possible follow-up.

@nnlugovoy
nnlugovoy force-pushed the issue-517-bounded-event-selection branch from 004f3d8 to c428a4e Compare November 28, 2026 16:40
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.

Ready-event selection loads the entire pending queue into PHP

1 participant