diff --git a/__tests__/bootstrap.php b/__tests__/bootstrap.php index ea91635..f87a0f6 100644 --- a/__tests__/bootstrap.php +++ b/__tests__/bootstrap.php @@ -38,6 +38,9 @@ function _manually_load_plugin() { if ( ! Cron_Control\Events_Store::is_installed() ) { Cron_Control\Events_Store::instance()->install(); Cron_Control\register_adapter_hooks(); + } elseif ( Cron_Control\Events_Store::needs_upgrade() ) { + // The table survives reruns, the options table does not. + Cron_Control\Events_Store::instance()->install(); } } tests_add_filter( 'muplugins_loaded', '_manually_load_plugin' ); diff --git a/__tests__/load-tests/Event_Selection_Load_Test.php b/__tests__/load-tests/Event_Selection_Load_Test.php new file mode 100644 index 0000000..c58f62c --- /dev/null +++ b/__tests__/load-tests/Event_Selection_Load_Test.php @@ -0,0 +1,281 @@ + [ 'pending' => 37400, 'other' => 634, 'future' => 0, 'actions' => 60, 'args_min' => 200, 'args_max' => 2400, 'zipf' => true ], + 'large' => [ 'pending' => 300000, 'other' => 30000, 'future' => 20000, 'actions' => 200, 'args_min' => 200, 'args_max' => 1800, 'zipf' => true ], + 'many_actions' => [ 'pending' => 50000, 'other' => 0, 'future' => 0, 'actions' => 5000, 'args_min' => 100, 'args_max' => 900, 'zipf' => false ], + // Bulk-scheduled events sharing timestamps. + 'ties' => [ 'pending' => 20000, 'other' => 0, 'future' => 0, 'actions' => 20, 'args_min' => 100, 'args_max' => 300, 'zipf' => false, 'distinct_ts' => 50 ], + ]; + + const INTERNAL_ACTIONS = [ 'a8c_cron_control_force_publish_missed_schedules', 'a8c_cron_control_confirm_scheduled_posts', 'a8c_cron_control_clean_legacy_data', 'a8c_cron_control_purge_completed_events' ]; + + public function test_bench() { + global $wpdb; + + $scenario = getenv( 'LOAD_SCENARIO' ) ?: 'issue'; + $spec = self::SCENARIOS[ $scenario ]; + $queues = array_map( 'intval', explode( ',', getenv( 'LOAD_QUEUE' ) ?: '10,50,250' ) ); + $runs = (int) ( getenv( 'LOAD_RUNS' ) ?: 5 ); + $table = $wpdb->prefix . 'a8c_cron_control_jobs'; + $due = 1700000000; // Fixed; get_events() uses time(), all seeded "due" rows are in the past. + $seed = 'bench.seed_' . $scenario; // Outside the test DB, which the WP installer wipes. + + // WP_UnitTestCase wraps tests in a transaction; seeds and the DDL below must persist. + $wpdb->query( 'COMMIT' ); + $wpdb->query( 'SET autocommit = 1' ); + // The test case rewrites CREATE/DROP TABLE to temporary tables. + remove_filter( 'query', [ $this, '_create_temporary_tables' ] ); + remove_filter( 'query', [ $this, '_drop_temporary_tables' ] ); + + $this->ensure_seed( $seed, $spec, $due ); + + $columns = 'timestamp, action, action_hashed, instance, args, schedule, `interval`, status, created, last_modified'; + // The table outlives test runs; rebuild it with this revision's schema. + $wpdb->query( "DROP TABLE IF EXISTS `{$table}`" ); + delete_option( 'a8c_cron_control_db_version' ); + wp_cache_flush(); + \Automattic\WP\Cron_Control\Events_Store::instance()->install(); + $indexes = implode( ',', array_unique( $wpdb->get_col( "SHOW INDEX FROM `{$table}`", 2 ) ) ); + $wpdb->query( "INSERT INTO `{$table}` ({$columns}) SELECT {$columns} FROM {$seed} ORDER BY seq" ); + $wpdb->query( "ANALYZE TABLE `{$table}`" ); + + $counts = $wpdb->get_row( "SELECT COUNT(*) total, SUM(status='pending') pending, ROUND(AVG(LENGTH(args))) avg_args FROM `{$table}`", ARRAY_A ); + $server = $wpdb->get_var( 'SELECT VERSION()' ); + + $captured = []; + $capture = function ( $query ) use ( &$captured, $table ) { + if ( false !== strpos( $query, $table ) && 0 === stripos( ltrim( $query, " \t\n(" ), 'SELECT' ) ) { + $captured[] = $query; + } + return $query; + }; + + $results = []; + foreach ( $queues as $n ) { + $samples = []; + for ( $r = 0; $r < $runs; $r++ ) { + $captured = []; + add_filter( 'query', $capture ); + $samples[] = 'cron_option' === getenv( 'LOAD_TARGET' ) + ? $this->measure( fn() => [ 'events' => self::flatten_cron( \Automattic\WP\Cron_Control\pre_get_cron_option( false ) ) ] ) + : $this->measure( fn() => Events::instance()->get_events( $n ) ); + remove_filter( 'query', $capture ); + } + + usort( $samples, fn( $a, $b ) => $a['ms'] <=> $b['ms'] ); + $median = $samples[ intdiv( count( $samples ), 2 ) ]; + + $results[] = array_merge( [ 'queue' => $n ], $median, [ 'queries' => count( $captured ) ] ); + + $dump = getenv( 'LOAD_DUMP' ); + if ( $dump ) { + file_put_contents( "{$dump}-{$scenario}-{$n}.json", wp_json_encode( Events::instance()->get_events( $n )['events'], JSON_PRETTY_PRINT ) ); + } + + $explain_file = getenv( 'LOAD_EXPLAIN' ); + if ( $explain_file ) { + $this->explain( $captured, $explain_file, "{$scenario} queue={$n} server={$server}" ); + } + } + + $report = [ 'rev' => getenv( 'LOAD_REV' ), 'target' => getenv( 'LOAD_TARGET' ) ?: 'get_events', 'scenario' => $scenario, 'server' => $server, 'indexes' => $indexes, 'table' => $counts, 'results' => $results ]; + fwrite( STDERR, "\n" . wp_json_encode( $report, JSON_PRETTY_PRINT ) . "\n" ); + $out = getenv( 'LOAD_OUT' ); + if ( $out ) { + file_put_contents( $out, wp_json_encode( $report ) . "\n", FILE_APPEND ); + } + + if ( ! getenv( 'LOAD_KEEP' ) ) { + $wpdb->query( "TRUNCATE TABLE `{$table}`" ); + } + $this->assertNotEmpty( $results ); + } + + private function measure( callable $callback ): array { + global $wpdb; + + wp_cache_flush(); + gc_collect_cycles(); + + $handler0 = $this->status(); + $handler1 = $this->status(); // Cost of reading status itself. + $overhead = array_map( fn( $k ) => $handler1[ $k ] - $handler0[ $k ], array_combine( array_keys( $handler0 ), array_keys( $handler0 ) ) ); + + $queries0 = $wpdb->num_queries; + memory_reset_peak_usage(); + $mem0 = memory_get_usage(); + $t0 = hrtime( true ); + + $result = $callback(); + + $ms = ( hrtime( true ) - $t0 ) / 1e6; + $peak = memory_get_peak_usage() - $mem0; + $after = $this->status(); + + $events = $result['events'] ?? []; + $events = is_array( $events ) ? $events : []; + + return [ + 'ms' => round( $ms, 2 ), + 'peak_mem_kb' => round( $peak / 1024 ), + 'rows_examined' => ( $after['rows'] - $handler1['rows'] ) - $overhead['rows'], + 'bytes_sent_kb' => round( ( ( $after['bytes'] - $handler1['bytes'] ) - $overhead['bytes'] ) / 1024, 1 ), + 'db_queries' => $wpdb->num_queries - $queries0, + 'events' => count( $events ), + // Order matters for the runner (round-robin), so fingerprint the sequence. + 'fingerprint' => substr( sha1( wp_json_encode( $events ) ), 0, 12 ), + 'set_fp' => substr( sha1( wp_json_encode( self::sorted( $events ) ) ), 0, 12 ), + ]; + } + + private static function flatten_cron( array $cron ): array { + unset( $cron['version'] ); + $events = []; + foreach ( $cron as $timestamp => $hooks ) { + foreach ( $hooks as $action => $instances ) { + foreach ( array_keys( $instances ) as $instance ) { + $events[] = [ 'timestamp' => $timestamp, 'action' => md5( $action ), 'instance' => $instance ]; + } + } + } + return $events; + } + + private static function sorted( array $events ): array { + usort( $events, fn( $a, $b ) => [ $a['timestamp'], $a['action'], $a['instance'] ] <=> [ $b['timestamp'], $b['action'], $b['instance'] ] ); + return $events; + } + + private function status(): array { + global $wpdb; + + $rows = $wpdb->get_results( "SHOW SESSION STATUS WHERE Variable_name LIKE 'Handler_read%' OR Variable_name = 'Bytes_sent'", ARRAY_A ); + $status = [ 'rows' => 0, 'bytes' => 0 ]; + foreach ( $rows as $row ) { + if ( 'Bytes_sent' === $row['Variable_name'] ) { + $status['bytes'] = (int) $row['Value']; + } else { + $status['rows'] += (int) $row['Value']; + } + } + return $status; + } + + private function explain( array $queries, string $file, string $label ): void { + global $wpdb; + + $is_maria = false !== stripos( $wpdb->get_var( 'SELECT VERSION()' ), 'mariadb' ); + $out = "\n===== {$label}\n"; + foreach ( $queries as $query ) { + $out .= '--- ' . ( strlen( $query ) > 600 ? substr( $query, 0, 600 ) . ' ...[' . strlen( $query ) . ' chars]' : $query ) . "\n"; + if ( $is_maria ) { + $plan = $wpdb->get_results( 'EXPLAIN ' . $query, ARRAY_A ); + foreach ( (array) $plan as $row ) { + $out .= sprintf( " %s %s type=%s key=%s rows=%s extra=%s\n", $row['id'], $row['table'], $row['type'], $row['key'], $row['rows'], $row['Extra'] ); + } + } else { + $out .= $wpdb->get_var( 'EXPLAIN ANALYZE ' . $query ) . "\n"; + } + } + file_put_contents( $file, $out, FILE_APPEND ); + } + + private function ensure_seed( string $seed, array $spec, int $due ): void { + global $wpdb; + + $expected = $spec['pending'] + $spec['other'] + $spec['future'] + count( self::INTERNAL_ACTIONS ) * 3; + if ( (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = %s AND table_name = %s', 'bench', substr( $seed, 6 ) ) ) ) { + if ( (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$seed}" ) === $expected ) { + return; + } + $wpdb->query( "DROP TABLE {$seed}" ); + } + + $wpdb->query( "CREATE DATABASE IF NOT EXISTS bench" ); + $wpdb->query( "CREATE TABLE {$seed} ( + seq int unsigned NOT NULL PRIMARY KEY, + `timestamp` bigint unsigned NOT NULL, action varchar(255) NOT NULL, action_hashed varchar(32) NOT NULL, + instance varchar(32) NOT NULL, args longtext NOT NULL, schedule varchar(255) NULL, `interval` int unsigned DEFAULT 0, + status varchar(32) NOT NULL, created datetime NOT NULL, last_modified datetime NOT NULL + ) ENGINE=InnoDB" ); + + mt_srand( 517 ); + + $weights = []; + for ( $i = 0; $i < $spec['actions']; $i++ ) { + $weights[ $i ] = $spec['zipf'] ? 1 / ( $i + 1 ) : 1; + } + $total_weight = array_sum( $weights ); + + $plan = []; + $add = function ( int $count, string $status, bool $future ) use ( &$plan, $weights, $total_weight, $spec ) { + $left = $count; + foreach ( $weights as $i => $w ) { + $n = ( $i === array_key_last( $weights ) ) ? $left : min( $left, (int) round( $count * $w / $total_weight ) ); + $left -= $n; + for ( $j = 0; $j < $n; $j++ ) { + $plan[] = [ 'bench_action_' . $i, $status, $future ]; + } + } + }; + $add( $spec['pending'], 'pending', false ); + $add( $spec['other'], 'complete', false ); + $add( $spec['future'], 'pending', true ); + foreach ( self::INTERNAL_ACTIONS as $internal ) { + foreach ( [ 'pending', 'pending', 'complete' ] as $status ) { + $plan[] = [ $internal, $status, false ]; + } + } + + shuffle( $plan ); // Insert (= ID) order is independent of timestamp and action. + + $count = count( $plan ); + $offsets = range( 1, $count ); + shuffle( $offsets ); + + $rows = []; + foreach ( $plan as $seq => [ $action, $status, $future ] ) { + if ( isset( $spec['distinct_ts'] ) ) { + $ts = $due - 60 * mt_rand( 1, $spec['distinct_ts'] ); + } else { + $ts = $future ? $due + 86400 * 365 * 20 + $offsets[ $seq ] : $due - 60 * $offsets[ $seq ]; + } + // Stored instance must match the args: legacy selection recomputes it from them. + $args = serialize( [ 'p' => str_repeat( 'x', mt_rand( $spec['args_min'], $spec['args_max'] ) ), 'n' => $seq ] ); + $rows[] = $wpdb->prepare( + "(%d, %d, %s, %s, %s, %s, NULL, 0, %s, '2026-01-01 00:00:00', '2026-01-01 00:00:00')", + $seq, + $ts, + $action, + md5( $action ), + md5( $args ), + $args, + $status + ); + if ( count( $rows ) >= 1000 ) { + $wpdb->query( "INSERT INTO {$seed} VALUES " . implode( ',', $rows ) ); + $rows = []; + } + } + if ( $rows ) { + $wpdb->query( "INSERT INTO {$seed} VALUES " . implode( ',', $rows ) ); + } + } +} diff --git a/__tests__/unit-tests/test-events-store.php b/__tests__/unit-tests/test-events-store.php index 76eeb31..21ca55e 100644 --- a/__tests__/unit-tests/test-events-store.php +++ b/__tests__/unit-tests/test-events-store.php @@ -263,4 +263,238 @@ public function test_query_raw_events_orderby() { $this->assertEquals( 4, count( $result ), 'returned the correct amount of events' ); $this->assertEquals( $event_four->get_id(), $result[0]->ID, 'the highest ID is returned first' ); } + + public function test_query_raw_events_supports_keyset_pagination() { + $store = Events_Store::instance(); + $events = []; + + foreach ( range( 1, 5 ) as $number ) { + $events[] = Utils::create_test_event( [ + 'action' => 'test_keyset_pagination', + 'timestamp' => 200 - $number, + 'args' => [ $number ], + ] ); + } + + $ids = array_map( fn( $event ) => $event->get_id(), $events ); + $args = [ + 'action' => 'test_keyset_pagination', + 'limit' => 2, + 'orderby' => 'ID', + ]; + + $first_page = $store->_query_events_raw( $args ); + $this->assertSame( [ $ids[0], $ids[1] ], array_map( 'intval', wp_list_pluck( $first_page, 'ID' ) ) ); + + $second_page = $store->_query_events_raw( array_merge( $args, [ 'after_id' => (int) end( $first_page )->ID ] ) ); + $this->assertSame( [ $ids[2], $ids[3] ], array_map( 'intval', wp_list_pluck( $second_page, 'ID' ) ) ); + + $descending = $store->_query_events_raw( array_merge( $args, [ 'order' => 'DESC', 'after_id' => $ids[3] ] ) ); + $this->assertSame( [ $ids[2], $ids[1] ], array_map( 'intval', wp_list_pluck( $descending, 'ID' ) ) ); + } + + public function test_query_raw_events_rejects_keyset_without_id_order() { + Utils::create_test_event( [ 'action' => 'test_keyset_order' ] ); + + $this->assertSame( [], @Events_Store::instance()->_query_events_raw( [ 'action' => 'test_keyset_order', 'after_id' => 1 ] ) ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged + } + + public function test_query_due_event_candidates_returns_only_public_event_columns() { + $event = Utils::create_test_event( [ + 'action' => 'test_due_candidates', + 'args' => [ 'large' => str_repeat( 'x', 1024 ) ], + 'timestamp' => 123, + ] ); + + $candidates = Events_Store::instance()->_query_due_event_candidates( 200, 10, [] ); + + $this->assertCount( 1, $candidates ); + $this->assertSame( [ 'ID', 'timestamp', 'action_hashed', 'instance' ], array_keys( (array) $candidates[0] ) ); + $this->assertSame( $event->get_id(), (int) $candidates[0]->ID ); + $this->assertSame( 123, (int) $candidates[0]->timestamp ); + $this->assertSame( md5( 'test_due_candidates' ), $candidates[0]->action_hashed ); + $this->assertSame( $event->get_instance(), $candidates[0]->instance ); + } + + public function test_query_due_event_candidates_bounds_rows_per_action_and_actions() { + foreach ( range( 1, 5 ) as $i ) { + Utils::create_test_event( [ 'action' => 'early_action', 'timestamp' => 100 + $i, 'args' => [ $i ] ] ); + Utils::create_test_event( [ 'action' => 'middle_action', 'timestamp' => 110 + $i, 'args' => [ $i ] ] ); + Utils::create_test_event( [ 'action' => 'late_action', 'timestamp' => 120 + $i, 'args' => [ $i ] ] ); + } + Utils::create_test_event( [ 'action' => 'not_due_action', 'timestamp' => 500 ] ); + $completed = Utils::create_test_event( [ 'action' => 'completed_action', 'timestamp' => 90 ] ); + $completed->complete(); + + $candidates = Events_Store::instance()->_query_due_event_candidates( 200, 2, [ md5( 'late_action' ) ] ); + $names = []; + foreach ( [ 'early_action', 'middle_action', 'late_action' ] as $name ) { + $names[ md5( $name ) ] = $name; + } + + $this->assertSame( + [ + [ 101, 'early_action' ], + [ 102, 'early_action' ], + [ 103, 'early_action' ], + [ 111, 'middle_action' ], + [ 112, 'middle_action' ], + [ 113, 'middle_action' ], + [ 121, 'late_action' ], + [ 122, 'late_action' ], + [ 123, 'late_action' ], + [ 124, 'late_action' ], + [ 125, 'late_action' ], + ], + array_map( + fn( $row ) => [ (int) $row->timestamp, $names[ $row->action_hashed ] ], + $candidates + ), + 'Earliest actions only, one row past the queue size per action; unbounded actions in full.' + ); + } + + public function test_query_due_event_candidates_breaks_ties_by_action_then_id() { + $beta = Utils::create_test_event( [ 'action' => 'tie_beta', 'timestamp' => 100 ] ); + $alpha = Utils::create_test_event( [ 'action' => 'tie_alpha', 'timestamp' => 100, 'args' => [ 1 ] ] ); + $alpha_two = Utils::create_test_event( [ 'action' => 'tie_alpha', 'timestamp' => 100, 'args' => [ 2 ] ] ); + + $by_hash = [ md5( 'tie_alpha' ) => [ $alpha, $alpha_two ], md5( 'tie_beta' ) => [ $beta ] ]; + ksort( $by_hash ); + $expected = array_map( fn( $event ) => $event->get_id(), array_merge( ...array_values( $by_hash ) ) ); + + $this->assertSame( $expected, array_map( 'intval', wp_list_pluck( Events_Store::instance()->_query_due_event_candidates( 200, 10, [] ), 'ID' ) ) ); + + $first_hash = array_key_first( $by_hash ); + $this->assertSame( [ $first_hash ], array_values( array_unique( wp_list_pluck( Events_Store::instance()->_query_due_event_candidates( 200, 1, [] ), 'action_hashed' ) ) ) ); + } + + public function test_schema_has_indexes_for_due_event_selection_and_event_lookup() { + global $wpdb; + + $table = Utils::get_table_name(); + + // Table name comes from the trusted WPDB prefix. + $indexes = wp_list_pluck( $wpdb->get_results( "SHOW INDEX FROM {$table}" ), 'Key_name' ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared + + $this->assertContains( 'status_action_hashed_ts_id_instance', $indexes, 'Due-event selection needs the per-action index.' ); + $this->assertContains( 'action_instance_status_ts', $indexes, 'The event lookup index must survive the upgrade.' ); + $this->assertContains( 'ts_action_instance_status', $indexes, 'The original unique index must be retained.' ); + $this->assertSame( Events_Store::DB_VERSION, (int) get_option( Events_Store::DB_VERSION_OPTION, 0 ) ); + } + + public function test_prepare_table_does_not_alter_an_up_to_date_table() { + $alters = []; + $record_alter = function ( $query ) use ( &$alters ) { + if ( false !== stripos( $query, 'ALTER TABLE' ) ) { + $alters[] = $query; + return ''; + } + return $query; + }; + add_filter( 'query', $record_alter ); + + try { + $prepare = new \ReflectionMethod( Events_Store::class, '_prepare_table' ); + $prepare->setAccessible( true ); + $prepare->invoke( Events_Store::instance() ); + } finally { + remove_filter( 'query', $record_alter ); + } + + $this->assertSame( [], $alters, 'Upgrades must only run the DDL they need.' ); + } + + public function test_prepare_table_does_not_record_version_when_index_is_wrong() { + global $wpdb; + + $table = Utils::get_table_name(); + + // Table name comes from the trusted WPDB prefix. + $wpdb->query( "DROP INDEX status_action_hashed_ts_id_instance ON {$table}" ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared + $wpdb->query( "ALTER TABLE {$table} ADD KEY status_action_hashed_ts_id_instance (status)" ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared + delete_option( Events_Store::DB_VERSION_OPTION ); + + $block_index_creation = function ( $query ) { + if ( false !== stripos( $query, 'ALTER TABLE' ) && false !== strpos( $query, 'status_action_hashed_ts_id_instance' ) ) { + return ''; + } + return $query; + }; + add_filter( 'query', $block_index_creation ); + + try { + $prepare = new \ReflectionMethod( Events_Store::class, '_prepare_table' ); + $prepare->setAccessible( true ); + $prepare->invoke( Events_Store::instance() ); + + $this->assertSame( 0, (int) get_option( Events_Store::DB_VERSION_OPTION, 0 ), 'Version must not advance when the index definition is wrong.' ); + } finally { + remove_filter( 'query', $block_index_creation ); + + // Before the DDL: it commits the test transaction, so the option must already be restored. + update_option( Events_Store::DB_VERSION_OPTION, Events_Store::DB_VERSION ); + $wpdb->query( "DROP INDEX status_action_hashed_ts_id_instance ON {$table}" ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared + $wpdb->query( "ALTER TABLE {$table} ADD KEY status_action_hashed_ts_id_instance (status, action_hashed, timestamp, ID, instance)" ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared + } + } + + public function test_prepare_table_does_not_require_the_status_index() { + global $wpdb; + + $table = Utils::get_table_name(); + + // Table name comes from the trusted WPDB prefix. + $wpdb->query( "DROP INDEX status ON {$table}" ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared + delete_option( Events_Store::DB_VERSION_OPTION ); + + $block_index_creation = function ( $query ) { + return false !== stripos( $query, 'ALTER TABLE' ) ? '' : $query; + }; + add_filter( 'query', $block_index_creation ); + + try { + $prepare = new \ReflectionMethod( Events_Store::class, '_prepare_table' ); + $prepare->setAccessible( true ); + $prepare->invoke( Events_Store::instance() ); + + $this->assertSame( Events_Store::DB_VERSION, (int) get_option( Events_Store::DB_VERSION_OPTION, 0 ), 'The status index is redundant with the per-action index.' ); + } finally { + remove_filter( 'query', $block_index_creation ); + + // Before the DDL: it commits the test transaction, so the option must already be restored. + update_option( Events_Store::DB_VERSION_OPTION, Events_Store::DB_VERSION ); + $wpdb->query( "ALTER TABLE {$table} ADD KEY status (status)" ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared + } + } + + public function test_upgrade_during_shutdown_requires_cli_or_an_administrator() { + require_once ABSPATH . 'wp-admin/includes/class-wp-screen.php'; + require_once ABSPATH . 'wp-admin/includes/screen.php'; + + set_current_screen( 'dashboard' ); + wp_set_current_user( 0 ); + update_option( Events_Store::DB_VERSION_OPTION, Events_Store::DB_VERSION - 1 ); + wp_cache_delete( 'upgrade_lock', 'cron-control' ); + + // DDL would commit the test transaction. + $block_ddl = function ( $query ) { + return false !== stripos( $query, 'ALTER TABLE' ) ? '' : $query; + }; + add_filter( 'query', $block_ddl ); + + try { + Events_Store::instance()->maybe_upgrade_during_shutdown(); + $this->assertTrue( Events_Store::needs_upgrade(), 'Anonymous admin requests must not run the schema upgrade.' ); + + wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) ); + Events_Store::instance()->maybe_upgrade_during_shutdown(); + $this->assertFalse( Events_Store::needs_upgrade(), 'Administrators should run the schema upgrade.' ); + } finally { + remove_filter( 'query', $block_ddl ); + update_option( Events_Store::DB_VERSION_OPTION, Events_Store::DB_VERSION ); + wp_cache_delete( 'upgrade_lock', 'cron-control' ); + set_current_screen( 'front' ); + } + } } diff --git a/__tests__/unit-tests/test-events.php b/__tests__/unit-tests/test-events.php index 05ef3fe..53b5cb0 100644 --- a/__tests__/unit-tests/test-events.php +++ b/__tests__/unit-tests/test-events.php @@ -261,6 +261,136 @@ public function test_get_events() { $this->check_get_events( $results, $window_events ); } + public function test_get_events_clamps_queue_size() { + $max = \Automattic\WP\Cron_Control\JOB_QUEUE_SIZE_MAX; + + for ( $i = 0; $i <= $max; $i++ ) { + Utils::create_test_event( [ + 'action' => 'test_clamp_' . $i, + 'timestamp' => 100 + $i, + ] ); + } + + $this->assertCount( $max, Events::instance()->get_events( 1000 )['events'], 'Large queue size should be clamped to the maximum.' ); + $this->assertCount( 1, Events::instance()->get_events( 0 )['events'], 'Zero queue size should be clamped to one.' ); + } + + public function test_get_events_includes_internal_events_beyond_queue_size() { + Utils::create_test_event( [ + 'action' => 'test_bounded_regular_event', + 'timestamp' => 100, + ] ); + + $internal_action = 'a8c_cron_control_purge_completed_events'; + foreach ( [ 101, 102, 103 ] as $timestamp ) { + Utils::create_test_event( [ + 'action' => $internal_action, + 'args' => [ $timestamp ], + 'timestamp' => $timestamp, + ] ); + } + + $events = Events::instance()->get_events( 1 )['events']; + + $this->assertCount( 4, $events, 'Internal events should bypass the regular queue cap.' ); + $this->assertSame( md5( 'test_bounded_regular_event' ), $events[0]['action'], 'Regular events should come first.' ); + $this->assertSame( md5( $internal_action ), $events[1]['action'] ); + $this->assertSame( md5( $internal_action ), $events[2]['action'] ); + $this->assertSame( md5( $internal_action ), $events[3]['action'] ); + } + + public function test_get_events_uses_stored_identifiers_in_projected_mode() { + $this->create_event_with_stored_hash( 'stored-hash' ); + + $events = Events::instance()->get_events( 1 )['events']; + + $this->assertSame( 'stored-hash', $events[0]['action'] ); + } + + public function test_get_events_can_restore_legacy_selection() { + $this->create_event_with_stored_hash( 'stored-hash' ); + + add_filter( 'a8c_cron_control_use_projected_event_selection', '__return_false' ); + try { + $events = Events::instance()->get_events( 1 )['events']; + } finally { + remove_filter( 'a8c_cron_control_use_projected_event_selection', '__return_false' ); + } + + $this->assertSame( md5( 'test_stored_identifier_event' ), $events[0]['action'] ); + } + + public function test_get_events_projected_selection_matches_legacy() { + $n = 0; + foreach ( [ 'a' => 30, 'b' => 3, 'c' => 12, 'd' => 1, 'e' => 20, 'f' => 7 ] as $action => $count ) { + for ( $i = 0; $i < $count; $i++ ) { + // Distinct, interleaved timestamps: legacy order of ties is undefined. + Utils::create_test_event( [ 'action' => 'test_equivalence_' . $action, 'timestamp' => 2000 + ( ++$n * 37 ) % 1009, 'args' => [ $i ] ] ); + } + } + Utils::create_test_event( [ 'action' => 'test_equivalence_future', 'timestamp' => time() + DAY_IN_SECONDS ] ); + Utils::create_test_event( [ 'action' => 'a8c_cron_control_purge_completed_events', 'timestamp' => 1001 ] ); + + foreach ( [ 1, 4, 6, 10, 25, 250 ] as $queue_size ) { + $projected = Events::instance()->get_events( $queue_size ); + + add_filter( 'a8c_cron_control_use_projected_event_selection', '__return_false' ); + try { + $legacy = Events::instance()->get_events( $queue_size ); + } finally { + remove_filter( 'a8c_cron_control_use_projected_event_selection', '__return_false' ); + } + + $this->assertSame( $legacy, $projected, "Selection for queue size {$queue_size} should match the legacy queue." ); + } + } + + public function test_get_events_projected_selection_matches_legacy_for_one_backed_up_action() { + for ( $i = 0; $i < 100; $i++ ) { + Utils::create_test_event( [ 'action' => 'test_backed_up_action', 'timestamp' => 2000 + $i, 'args' => [ $i ] ] ); + } + + foreach ( [ 10, 15, 16, 50, 99, 100, 250 ] as $queue_size ) { + $projected = Events::instance()->get_events( $queue_size ); + + add_filter( 'a8c_cron_control_use_projected_event_selection', '__return_false' ); + try { + $legacy = Events::instance()->get_events( $queue_size ); + } finally { + remove_filter( 'a8c_cron_control_use_projected_event_selection', '__return_false' ); + } + + $this->assertSame( $legacy, $projected, "Selection for queue size {$queue_size} should match the legacy queue." ); + } + + $this->assertCount( 15, Events::instance()->get_events( 50 )['events'], 'A backed-up action is capped per batch.' ); + } + + public function test_get_events_uses_legacy_selection_until_schema_is_upgraded() { + $this->create_event_with_stored_hash( 'stored-hash' ); + update_option( Events_Store::DB_VERSION_OPTION, Events_Store::DB_VERSION - 1 ); + + try { + $events = Events::instance()->get_events( 1 )['events']; + } finally { + update_option( Events_Store::DB_VERSION_OPTION, Events_Store::DB_VERSION ); + } + + $this->assertSame( md5( 'test_stored_identifier_event' ), $events[0]['action'], 'The legacy path hashes the action name.' ); + } + + private function create_event_with_stored_hash( string $action_hash ) { + $instance = Event::create_instance_hash( [] ); + Events_Store::instance()->_create_event( [ + 'status' => Events_Store::STATUS_PENDING, + 'action' => 'test_stored_identifier_event', + 'action_hashed' => $action_hash, + 'timestamp' => 100, + 'args' => serialize( [] ), + 'instance' => $instance, + ] ); + } + private function check_get_events( $results, $desired_results ) { $this->assertEquals( count( $results['events'] ), count( $desired_results ), 'Incorrect number of events returned' ); diff --git a/__tests__/unit-tests/test-wp-adapter.php b/__tests__/unit-tests/test-wp-adapter.php index 0495b99..8c7f67e 100644 --- a/__tests__/unit-tests/test-wp-adapter.php +++ b/__tests__/unit-tests/test-wp-adapter.php @@ -171,6 +171,15 @@ public function test_pre_unschedule_hook() { $this->assertEquals( 0, $result, 'nothing was cleared' ); } + public function test_pre_unschedule_hook_clears_more_than_one_batch() { + for ( $i = 0; $i < 1001; $i++ ) { + Utils::create_test_event( [ 'action' => 'test_pre_unschedule_hook_batches', 'timestamp' => time() + $i, 'args' => [ $i ] ] ); + } + + $this->assertSame( 1001, Cron_Control\pre_unschedule_hook( null, 'test_pre_unschedule_hook_batches' ) ); + $this->assertSame( [], Events::query( [ 'action' => 'test_pre_unschedule_hook_batches' ] ) ); + } + public function test_pre_get_scheduled_event() { $event_details = (object) [ 'hook' => 'test_pre_get_scheduled_event', @@ -232,6 +241,33 @@ public function test_pre_get_cron_option() { $this->assert_event_matches_expected_args( $flat_option[3], $test_events['recurring'] ); } + public function test_pre_clear_scheduled_hook_reads_every_page() { + $this->create_events_across_pages( 501, 'test_clear_pagination' ); + + $result = Cron_Control\pre_clear_scheduled_hook( null, 'test_clear_pagination', [] ); + + $this->assertSame( 501, $result ); + $this->assertEmpty( Events::query( [ 'action' => 'test_clear_pagination', 'limit' => -1 ] ) ); + } + + public function test_pre_get_cron_option_reads_every_page() { + $this->create_events_across_pages( 501, 'test_cron_option_pagination' ); + + $cron_option = Cron_Control\pre_get_cron_option( false ); + + $this->assertCount( 502, $cron_option ); + } + + private function create_events_across_pages( int $count, string $action ): void { + for ( $i = 0; $i < $count; $i++ ) { + Utils::create_test_event( [ + 'action' => $action, + 'args' => [], + 'timestamp' => time() + $i, + ] ); + } + } + public function test_pre_update_cron_option() { // Ironically, if the function being tested here is broken, // the below will make it clear because test setup/teardown won't be able to clear things out :) diff --git a/includes/class-events-store.php b/includes/class-events-store.php index 4437598..e6acee4 100644 --- a/includes/class-events-store.php +++ b/includes/class-events-store.php @@ -10,7 +10,7 @@ class Events_Store extends Singleton { const TABLE_SUFFIX = 'a8c_cron_control_jobs'; - const DB_VERSION = 1; + const DB_VERSION = 2; const DB_VERSION_OPTION = 'a8c_cron_control_db_version'; const STATUS_PENDING = 'pending'; @@ -26,6 +26,8 @@ protected function class_init() { // Keep trying in case we weren't around during the site installation. add_action( 'shutdown', array( $this, 'maybe_install_during_shutdown' ) ); + } elseif ( self::needs_upgrade() ) { + add_action( 'shutdown', array( $this, 'maybe_upgrade_during_shutdown' ) ); } // Handle adding/removing tables when subsites are created/deleted. @@ -120,10 +122,31 @@ public function maybe_install_during_shutdown() { } } + public static function needs_upgrade(): bool { + return (int) get_option( self::DB_VERSION_OPTION, 0 ) < self::DB_VERSION; + } + + public function maybe_upgrade_during_shutdown() { + // Index builds can be slow on large tables, keep them out of anonymous and runner REST requests. + $is_cli = defined( 'WP_CLI' ) && WP_CLI; + $is_admin = is_admin() && ! wp_doing_ajax() && current_user_can( 'manage_options' ); + + if ( ( ! $is_cli && ! $is_admin ) || ! self::needs_upgrade() ) { + return; + } + + // Must outlast the index build, otherwise the next request starts a second one. + if ( wp_cache_add( 'upgrade_lock', true, 'cron-control', 15 * \MINUTE_IN_SECONDS ) ) { + $this->_prepare_table(); + } + } + /** * Create the plugin's DB table when necessary */ protected function _prepare_table() { + global $wpdb; + // Use Core's method of creating/updating tables. if ( ! function_exists( 'dbDelta' ) ) { require_once ABSPATH . '/wp-admin/includes/upgrade.php'; @@ -134,39 +157,80 @@ protected function _prepare_table() { // Define schema and create the table. $schema = "CREATE TABLE `{$table_name}` ( `ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT, - `timestamp` bigint(20) unsigned NOT NULL, `action` varchar(255) NOT NULL, `action_hashed` varchar(32) NOT NULL, `instance` varchar(32) NOT NULL, - `args` longtext NOT NULL, `schedule` varchar(255) DEFAULT NULL, - `interval` int unsigned DEFAULT 0, + `interval` int(10) unsigned DEFAULT 0, `status` varchar(32) NOT NULL DEFAULT 'pending', - `created` datetime NOT NULL, `last_modified` datetime NOT NULL, - PRIMARY KEY (`ID`), UNIQUE KEY `ts_action_instance_status` (`timestamp`, `action` (191), `instance`, `status`), - KEY `status` (`status`) - ) ENGINE=InnoDB;\n"; + KEY `status` (`status`), + KEY `action_instance_status_ts` (`action` (191), `instance`, `status`, `timestamp`), + KEY `status_action_hashed_ts_id_instance` (`status`, `action_hashed`, `timestamp`, `ID`, `instance`) + ) ENGINE=InnoDB;"; dbDelta( $schema, true ); - // Confirm that the table was created, and set the option to prevent further updates. - $is_installed = self::table_exists( $table_name ); - wp_cache_set( 'is_installed', $is_installed, 'cron-control' ); + $has_srtm = property_exists( $wpdb, 'srtm' ); + if ( $has_srtm ) { + // Replicas may not have the new schema yet. + $previous_srtm = $wpdb->srtm; + $wpdb->srtm = true; + } + + $table_exists = self::table_exists( $table_name ); + wp_cache_set( 'is_installed', $table_exists, 'cron-control' ); - if ( $is_installed ) { + if ( $table_exists && $this->has_required_indexes( $table_name ) ) { update_option( self::DB_VERSION_OPTION, self::DB_VERSION ); } + if ( $has_srtm ) { + $wpdb->srtm = $previous_srtm; + } + // Clear caches now that the table exists. self::flush_event_cache(); } + private function has_required_indexes( string $table_name ): bool { + global $wpdb; + + // Table name is built from the trusted WPDB prefix. @codingStandardsIgnoreLine + $rows = $wpdb->get_results( "SHOW INDEX FROM `{$table_name}`", ARRAY_A ); + + $actual = []; + foreach ( (array) $rows as $row ) { + $column = $row['Column_name'] . ( is_null( $row['Sub_part'] ) ? '' : '(' . $row['Sub_part'] . ')' ); + $actual[ $row['Key_name'] ][ (int) $row['Seq_in_index'] ] = $column; + } + + $expected = [ + 'PRIMARY' => [ 'ID' ], + 'ts_action_instance_status' => [ 'timestamp', 'action(191)', 'instance', 'status' ], + 'action_instance_status_ts' => [ 'action(191)', 'instance', 'status', 'timestamp' ], + 'status_action_hashed_ts_id_instance' => [ 'status', 'action_hashed', 'timestamp', 'ID', 'instance' ], + ]; + + foreach ( $expected as $name => $columns ) { + if ( ! isset( $actual[ $name ] ) ) { + return false; + } + + ksort( $actual[ $name ] ); + if ( array_values( $actual[ $name ] ) !== $columns ) { + return false; + } + } + + return true; + } + /** * When deleting a subsite from a multisite instance, include the plugin's table. * @@ -359,6 +423,10 @@ public function _query_events_raw( array $args = [] ): array { 'default' => 1, 'validation' => fn( $page ) => is_int( $page ) && $page >= 1, ], + 'after_id' => [ + 'default' => null, + 'validation' => 'is_int', + ], 'orderby' => [ 'default' => 'timestamp', 'validation' => fn( $orderby ) => is_null( $orderby ) || ( is_string( $orderby ) && in_array( $orderby, [ 'timestamp', 'ID' ], true ) ), @@ -381,6 +449,11 @@ public function _query_events_raw( array $args = [] ): array { } } + if ( isset( $parsed_args['after_id'] ) && 'ID' !== $parsed_args['orderby'] ) { + trigger_error( 'Cron-Control: after_id requires orderby ID', E_USER_WARNING ); + return []; + } + $table = $this->get_table_name(); $sql = "SELECT * FROM `{$table}` WHERE 1=1"; $placeholders = []; @@ -446,6 +519,11 @@ public function _query_events_raw( array $args = [] ): array { } } + if ( isset( $parsed_args['after_id'] ) ) { + $sql .= strtoupper( $parsed_args['order'] ) === 'ASC' ? ' AND ID > %d' : ' AND ID < %d'; + $placeholders[] = $parsed_args['after_id']; + } + if ( ! is_null( $parsed_args['orderby'] ) ) { $sql .= ' ORDER BY ' . $parsed_args['orderby']; $sql .= strtoupper( $parsed_args['order'] ) === 'ASC' ? ' ASC' : ' DESC'; @@ -494,6 +572,62 @@ public function _query_events_raw( array $args = [] ): array { return $results; } + /** + * Due events reduce_queue() can pick from: up to $limit + 1 rows from each of the $limit earliest actions, all rows of $unbounded_action_hashes. + * + * The extra row per action makes the result exceed $limit whenever an action was cut off, + * so callers trim it with reduce_queue() exactly as they would the full set. + * + * @param int $due_before Latest timestamp to include. + * @param int $limit Queue size. + * @param string[] $unbounded_action_hashes Internal action hashes. + * @return object[] ID, timestamp, action_hashed, instance. + */ + public function _query_due_event_candidates( int $due_before, int $limit, array $unbounded_action_hashes ): array { + global $wpdb; + + $table = $this->get_table_name(); + + // Grouping by the whole index prefix enables a loose index scan. + $first_due = $wpdb->get_results( $wpdb->prepare( + "SELECT action_hashed, MIN(timestamp) AS first_due FROM `{$table}` WHERE status = %s AND timestamp <= %d GROUP BY status, action_hashed", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared + self::STATUS_PENDING, + $due_before + ) ); + + $unbounded = []; + $bounded = []; + foreach ( (array) $first_due as $row ) { + if ( in_array( $row->action_hashed, $unbounded_action_hashes, true ) ) { + $unbounded[] = $row->action_hashed; + } else { + $bounded[ $row->action_hashed ] = (int) $row->first_due; + } + } + + $bounded_order = array_keys( $bounded ); + usort( $bounded_order, fn( $a, $b ) => [ $bounded[ $a ], $a ] <=> [ $bounded[ $b ], $b ] ); + $bounded = array_slice( $bounded_order, 0, $limit ); + + $branch = "SELECT ID, timestamp, action_hashed, instance FROM `{$table}` WHERE status = %s AND action_hashed = %s AND timestamp <= %d"; + $branches = []; + foreach ( $bounded as $action_hashed ) { + // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQLPlaceholders + $branches[] = $wpdb->prepare( "({$branch} ORDER BY timestamp ASC, ID ASC LIMIT %d)", self::STATUS_PENDING, $action_hashed, $due_before, $limit + 1 ); + } + foreach ( $unbounded as $action_hashed ) { + // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQLPlaceholders + $branches[] = $wpdb->prepare( "({$branch})", self::STATUS_PENDING, $action_hashed, $due_before ); + } + + if ( empty( $branches ) ) { + return []; + } + + // Same tie order as the cut above. + return (array) $wpdb->get_results( implode( ' UNION ALL ', $branches ) . ' ORDER BY timestamp ASC, action_hashed ASC, ID ASC' ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared + } + private static function validate_status( $status ): bool { $allowed_string_statuses = array_merge( self::ALLOWED_STATUSES, [ 'any' ] ); diff --git a/includes/class-events.php b/includes/class-events.php index e4013b3..b11d71d 100644 --- a/includes/class-events.php +++ b/includes/class-events.php @@ -98,16 +98,28 @@ public function populate_concurrent_action_whitelist() { * @return array Events to be run in the next batch. */ public function get_events( $job_queue_size = null, $job_queue_window = null ): array { - $job_queue_size = is_null( $job_queue_size ) ? JOB_QUEUE_SIZE : $job_queue_size; + $job_queue_size = max( 1, min( absint( $job_queue_size ?? JOB_QUEUE_SIZE ), JOB_QUEUE_SIZE_MAX ) ); $job_queue_window = is_null( $job_queue_window ) ? JOB_QUEUE_WINDOW_IN_SECONDS : $job_queue_window; - // Grab relevant events that are due, or soon will be. - $current_time = time(); - $events = self::query( [ - 'timestamp' => [ 'from' => 0, 'to' => $current_time + $job_queue_window ], - 'status' => Events_Store::STATUS_PENDING, - 'limit' => -1, // Need to get all, to ensure we grab internals even when queue is backed up. - ] ); + $due_before = time() + $job_queue_window; + $internal_hashes = Internal_Events::instance()->get_internal_action_hashes(); + + // action is hashed to avoid information disclosure. + if ( $this->use_projected_event_selection() ) { + $events = array_map( + fn( $row ) => [ 'timestamp' => (int) $row->timestamp, 'action' => $row->action_hashed, 'instance' => $row->instance ], + Events_Store::instance()->_query_due_event_candidates( $due_before, $job_queue_size, $internal_hashes ) + ); + } else { + $events = array_map( + fn( $event ) => [ 'timestamp' => $event->get_timestamp(), 'action' => md5( $event->get_action() ), 'instance' => $event->get_instance() ], + self::query( [ + 'timestamp' => [ 'from' => 0, 'to' => $due_before ], + 'status' => Events_Store::STATUS_PENDING, + 'limit' => -1, // Need to get all, to ensure we grab internals even when queue is backed up. + ] ) + ); + } // That was easy. if ( empty( $events ) ) { @@ -117,18 +129,11 @@ public function get_events( $job_queue_size = null, $job_queue_window = null ): $current_events = []; $internal_events = []; foreach ( $events as $event ) { - // action is hashed to avoid information disclosure. - $event_data_public = [ - 'timestamp' => $event->get_timestamp(), - 'action' => md5( $event->get_action() ), - 'instance' => $event->get_instance(), - ]; - // Queue internal events separately to avoid them being blocked. - if ( $event->is_internal() ) { - $internal_events[] = $event_data_public; + if ( in_array( $event['action'], $internal_hashes, true ) ) { + $internal_events[] = $event; } else { - $current_events[] = $event_data_public; + $current_events[] = $event; } } @@ -142,6 +147,11 @@ public function get_events( $job_queue_size = null, $job_queue_window = null ): return [ 'events' => array_merge( $current_events, $internal_events ) ]; } + private function use_projected_event_selection(): bool { + // Without the schema v2 index every bounded query would scan the table. + return ! Events_Store::needs_upgrade() && apply_filters( 'a8c_cron_control_use_projected_event_selection', true ); + } + /** * Trim events queue down to a specific limit. * diff --git a/includes/class-internal-events.php b/includes/class-internal-events.php index ab033bb..ed464b2 100644 --- a/includes/class-internal-events.php +++ b/includes/class-internal-events.php @@ -134,6 +134,10 @@ public function is_internal_event( $action ): bool { return in_array( $action, wp_list_pluck( $this->internal_events, 'action' ), true ); } + public function get_internal_action_hashes(): array { + return array_values( array_unique( array_map( 'md5', wp_list_pluck( $this->internal_events, 'action' ) ) ) ); + } + /* |-------------------------------------------------------------------------- | Internal Event Callbacks diff --git a/includes/constants.php b/includes/constants.php index 804b5cc..d52872a 100644 --- a/includes/constants.php +++ b/includes/constants.php @@ -10,10 +10,12 @@ /** * Adjustable queue size and concurrency limits, to facilitate scaling */ +const JOB_QUEUE_SIZE_MAX = 250; + $job_queue_size = 10; if ( defined( 'CRON_CONTROL_JOB_QUEUE_SIZE' ) && is_numeric( \CRON_CONTROL_JOB_QUEUE_SIZE ) ) { $job_queue_size = absint( \CRON_CONTROL_JOB_QUEUE_SIZE ); - $job_queue_size = max( 1, min( $job_queue_size, 250 ) ); + $job_queue_size = max( 1, min( $job_queue_size, JOB_QUEUE_SIZE_MAX ) ); } define( __NAMESPACE__ . '\JOB_QUEUE_SIZE', $job_queue_size ); unset( $job_queue_size ); diff --git a/includes/wp-adapter.php b/includes/wp-adapter.php index 510b537..bf44e8e 100644 --- a/includes/wp-adapter.php +++ b/includes/wp-adapter.php @@ -20,6 +20,25 @@ function register_adapter_hooks() { add_filter( 'pre_update_option_cron', __NAMESPACE__ . '\\pre_update_cron_option', 10, 2 ); } +function query_all_events_in_batches( array $query_args = [] ): array { + $limit = 500; + + $query_args['limit'] = $limit; + $query_args['orderby'] = 'ID'; + $query_args['order'] = 'ASC'; + unset( $query_args['page'], $query_args['after_id'] ); + + $all_events = []; + + do { + $events = Events::query( $query_args ); + array_push( $all_events, ...$events ); + $query_args['after_id'] = $events ? end( $events )->get_id() : null; + } while ( count( $events ) === $limit ); + + return $all_events; +} + /** * Intercept event scheduling. * @@ -146,32 +165,31 @@ function pre_clear_scheduled_hook( $pre, $hook, $args ) { return $pre; } + // Completed events drop out of the default active statuses, so each pass fetches the next batch. + // No ordering, so the action/instance index serves the lookup instead of a primary key scan. $query_args = [ - 'action' => $hook, - 'args' => $args, - 'limit' => 500, - 'page' => 1, + 'action' => $hook, + 'args' => $args, + 'limit' => 500, + 'orderby' => null, ]; - // First grab all the events before making any changes (avoiding pagination complexities). - $all_events = []; - do { - $events = Events::query( $query_args ); - $all_events = array_merge( $all_events, $events ); - - ++$query_args['page']; - } while ( ! empty( $events ) ); - + $cleared = 0; $all_successful = true; - foreach ( $all_events as $event ) { - $result = $event->complete(); - - if ( true !== $result ) { - $all_successful = false; + do { + $events = Events::query( $query_args ); + + foreach ( $events as $event ) { + if ( true === $event->complete() ) { + ++$cleared; + } else { + $all_successful = false; + } } - } + // A failed event would be fetched again, stop instead of looping on it. + } while ( $all_successful && count( $events ) === $query_args['limit'] ); - return $all_successful ? count( $all_events ) : new WP_Error( 'cron-control:wp:failed-event-deleting' ); + return $all_successful ? $cleared : new WP_Error( 'cron-control:wp:failed-event-deleting' ); } /** @@ -247,15 +265,7 @@ function pre_get_cron_option( $pre ) { } // For maximum BC, we need to truly give all events here. - // Stepping in increments of 500 to allow query caching to do it's job. - $query_args = [ 'limit' => 500, 'page' => 1 ]; - $all_events = []; - do { - $events = Events::query( $query_args ); - $all_events = array_merge( $all_events, $events ); - - ++$query_args['page']; - } while ( ! empty( $events ) ); + $all_events = query_all_events_in_batches(); $cron_array = Events::format_events_for_wp( $all_events ); $cron_array['version'] = 2; // a legacy core thing