Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions __tests__/bootstrap.php
Original file line number Diff line number Diff line change
Expand Up @@ -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' );
Expand Down
281 changes: 281 additions & 0 deletions __tests__/load-tests/Event_Selection_Load_Test.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,281 @@
<?php
/**
* Implementation-agnostic benchmark of Events::get_events().
*
* Only calls public API present on every revision, so the same file can be run
* against origin/main, the branch HEAD and the working tree.
*
* Env: LOAD_SCENARIO (issue|large|many_actions|ties), LOAD_TARGET (get_events|cron_option), LOAD_QUEUE (csv), LOAD_RUNS,
* LOAD_OUT (jsonl), LOAD_EXPLAIN (file), LOAD_DUMP (path prefix), LOAD_KEEP, LOAD_REV. Seeds persist in the `bench` schema. PHP 8.2+.
*/

namespace Automattic\WP\Cron_Control\Tests;

use Automattic\WP\Cron_Control\Events;

class Event_Selection_Load_Test extends \WP_UnitTestCase {

const SCENARIOS = [
// Shape of the site in #517: ~38k rows, ~37.4k pending, ~1.3KB args, skewed action mix.
'issue' => [ '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 ) );
}
}
}
Loading