From f8df5677aac86baf41ef7b2ee249193e26840a40 Mon Sep 17 00:00:00 2001 From: Filip Ilic Date: Tue, 17 Nov 2026 13:47:51 +0100 Subject: [PATCH 1/4] Rework tracking limits from #93 review The tracking-limited flag paused unused-option recommendations site-wide and only a manual reset cleared it, yet it was set by routine events: a 1s lock timeout under concurrent traffic, any request reading over 1,000 options, or a transient SQL error. Legacy migrations over 10,000 names could never finish, and pruning deleted the oldest (core) rows. - Drop the GET_LOCK serialisation; the 10,000-name cap is now a soft limit checked without a lock. No MySQL-only lock functions or DELETE ... LIMIT. - Set the flag only when a new name is actually dropped for capacity, or one request reads more names than storage holds. Write failures don't set it. - Detect existing names with a SQL join, so case/accent variants of a stored row count as existing, matching the primary key's collation. - Migrate legacy data without the cap so migration always completes. - Never prune rows, and don't truncate reads at the limit. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- src/class-database.php | 164 ++++++++++++++++++----------------------- src/class-plugin.php | 4 +- tests/hardening.php | 104 ++++++++++++++++---------- 4 files changed, 141 insertions(+), 133 deletions(-) diff --git a/README.md b/README.md index d6c7098..14927d4 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,7 @@ Essential WordPress options, including site URLs, active plugins, theme settings ### Why are unused-option recommendations paused? -Tracking retains at most 10,000 distinct names and records at most 1,000 distinct names per request. When a limit is reached or a tracking write fails, the plugin marks observations incomplete and pauses unused-option recommendations. Existing recorded counts can still increase. Older oversized tables are reduced to the limit on the next tracking write. Reset tracking to start a fresh observation period. +Tracking stores up to about 10,000 distinct names. The limit is checked without locking, so concurrent requests can push slightly past it. Once it is reached, names already recorded keep counting, but a new name is dropped, and the plugin then marks observations incomplete and pauses unused-option recommendations, because a dropped name could otherwise be reported as unused. Data migrated from older versions is kept in full, even past the limit. A failed tracking write does not pause recommendations; it loses at most that request's counts. Reset tracking to start a fresh observation period. ### How can I add recognized plugins? diff --git a/src/class-database.php b/src/class-database.php index 17d841d..f0e457d 100644 --- a/src/class-database.php +++ b/src/class-database.php @@ -42,28 +42,14 @@ public static function mark_tracking_limited() { /** * Whether unused-option recommendations would be incomplete. * - * Also detects an oversized table from an older plugin version before the - * next tracking write has had a chance to prune it. + * True only after an observation was actually dropped because tracking storage was full, + * or a single request read more names than can be stored. Transient write failures don't + * set it: they lose at most one request's counts, which the next request records again. * * @return bool */ public static function is_tracking_limited() { - global $wpdb; - if ( \get_option( 'aaa_option_optimizer_tracking_limited', false ) ) { - return true; - } - $table = self::get_table_name(); - // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching - return null !== $wpdb->get_var( $wpdb->prepare( 'SELECT option_name FROM %i LIMIT 1 OFFSET %d', $table, self::MAX_TRACKED_OPTIONS - 1 ) ); - } - - /** - * Lock name scoped to this database and blog. - * - * @return string - */ - private static function get_tracking_lock() { - return 'aaaoo_' . md5( ( defined( 'DB_NAME' ) ? DB_NAME : '' ) . self::get_table_name() ); + return (bool) \get_option( 'aaa_option_optimizer_tracking_limited', false ); } /** @@ -200,9 +186,10 @@ public static function migrate_chunk() { // Take a chunk of options to migrate. $chunk = \array_slice( $option_data['used_options'], 0, self::MIGRATION_CHUNK_SIZE, true ); - // Remove only observations that were committed; failed or capacity-limited - // writes must leave the remaining source data available for a retry. - $written = self::batch_insert( $chunk ); + // Legacy observations were already stored in full, so they are migrated without the + // capacity limit; otherwise a large legacy dataset could never finish migrating. + // Remove only committed observations, so a failed write can be retried. + $written = self::batch_insert( $chunk, 500, false ); if ( false === $written ) { return [ 'success' => false, @@ -223,15 +210,6 @@ public static function migrate_chunk() { \delete_transient( 'aaa_option_optimizer_migration_total' ); } - if ( count( $written ) < count( $chunk ) ) { - return [ - 'success' => false, - 'remaining' => $remaining, - 'total' => (int) $total, - 'message' => \__( 'Tracking storage is full. Unmigrated observations have been retained.', 'aaa-option-optimizer' ), - ]; - } - return [ 'success' => true, 'remaining' => $remaining, @@ -250,85 +228,95 @@ public static function migrate_chunk() { * VALUES list; with per-request access order, concurrent requests lock * the same rows in different orders and deadlock each other. * + * The capacity limit is soft: it is checked without a lock, so concurrent + * requests near the limit can each add their new names and overshoot it + * slightly. Taking a global lock on every request costs far more than a + * few extra rows, and isn't portable beyond MySQL. + * * @param array $options Array of option_name => count. * @param int $chunk_size Number of options per query. Default 500. + * @param bool $enforce_cap Whether new names are limited to MAX_TRACKED_OPTIONS. Default true. * * @return array|false Committed observations, or false on a write failure. */ - public static function batch_insert( $options, $chunk_size = 500 ) { + public static function batch_insert( $options, $chunk_size = 500, $enforce_cap = true ) { global $wpdb; if ( empty( $options ) ) { return []; } - $table = self::get_table_name(); - $lock = self::get_tracking_lock(); - // Serialize capacity checks and writes across concurrent requests. - // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching - if ( '1' !== (string) $wpdb->get_var( $wpdb->prepare( 'SELECT GET_LOCK(%s, 1)', $lock ) ) ) { - self::mark_tracking_limited(); - return false; - } + \ksort( $options, SORT_STRING ); + $chunk_size = max( 1, min( 500, (int) $chunk_size ) ); + $accepted = $options; - try { + if ( $enforce_cap ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching - $count = $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM %i', $table ) ); + $count = $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM %i', self::get_table_name() ) ); if ( null === $count ) { - self::mark_tracking_limited(); return false; } - $count = (int) $count; - $limited = false; - if ( $count >= self::MAX_TRACKED_OPTIONS ) { - self::mark_tracking_limited(); - } - if ( $count > self::MAX_TRACKED_OPTIONS ) { - // Bound tables created by older versions too. Never infer unused options after pruning. - // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching - if ( false === $wpdb->query( $wpdb->prepare( 'DELETE FROM %i ORDER BY created_at ASC, option_name ASC LIMIT %d', $table, $count - self::MAX_TRACKED_OPTIONS ) ) ) { - return false; - } - $count = self::MAX_TRACKED_OPTIONS; - } + $remaining = self::MAX_TRACKED_OPTIONS - (int) $count; - \ksort( $options, SORT_STRING ); - $remaining = max( 0, self::MAX_TRACKED_OPTIONS - $count ); - $accepted = []; - foreach ( array_chunk( $options, 500, true ) as $chunk ) { - $names = array_keys( $chunk ); - $slots = implode( ',', array_fill( 0, count( $names ), '%s' ) ); - // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared - $existing = array_fill_keys( $wpdb->get_col( $wpdb->prepare( "SELECT option_name FROM %i WHERE option_name IN ($slots)", array_merge( [ $table ], $names ) ) ), true ); - if ( $wpdb->last_error ) { - self::mark_tracking_limited(); + // Below the limit with room for every name: no need to tell new names from existing ones. + if ( count( $options ) > $remaining ) { + $existing = self::get_existing_names( array_keys( $options ) ); + if ( false === $existing ) { return false; } - foreach ( $chunk as $name => $accesses ) { + $accepted = []; + $dropped = false; + foreach ( $options as $name => $accesses ) { if ( isset( $existing[ $name ] ) ) { $accepted[ $name ] = $accesses; } elseif ( $remaining > 0 ) { $accepted[ $name ] = $accesses; --$remaining; } else { - $limited = true; + $dropped = true; } } + if ( $dropped ) { + self::mark_tracking_limited(); + } } - if ( $limited ) { - self::mark_tracking_limited(); + } + + if ( $accepted && ! self::write_chunks( $accepted, $chunk_size ) ) { + if ( ! self::last_error_is_deadlock() || ! self::write_chunks( $accepted, $chunk_size ) ) { + return false; } + } + return $accepted; + } - if ( $accepted && ! self::write_chunks( $accepted, max( 1, min( 500, $chunk_size ) ) ) ) { - if ( ! self::last_error_is_deadlock() || ! self::write_chunks( $accepted, max( 1, min( 500, $chunk_size ) ) ) ) { - self::mark_tracking_limited(); - return false; - } + /** + * Find which submitted names already have a row, using the table's own collation. + * + * The submitted names are joined against the table in SQL, so a name that differs from a + * stored row only by case or accents counts as existing, exactly as the primary key and + * ON DUPLICATE KEY UPDATE treat it. Comparing the returned rows in PHP would not. + * + * @param string[] $names Submitted option names. + * + * @return array|false Submitted names that match a row, or false on a query failure. + */ + private static function get_existing_names( array $names ) { + global $wpdb; + + $table = self::get_table_name(); + $existing = []; + foreach ( array_chunk( $names, 500 ) as $chunk ) { + $selects = implode( ' UNION ALL ', array_fill( 0, count( $chunk ), 'SELECT %s AS n' ) ); + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- Placeholders are generated above. + $found = $wpdb->get_col( $wpdb->prepare( "SELECT s.n FROM ($selects) s INNER JOIN %i t ON t.option_name = s.n", array_merge( array_map( 'strval', $chunk ), [ $table ] ) ) ); + if ( $wpdb->last_error ) { + return false; + } + foreach ( $found as $name ) { + $existing[ $name ] = true; } - return $accepted; - } finally { - // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching - $wpdb->get_var( $wpdb->prepare( 'SELECT RELEASE_LOCK(%s)', $lock ) ); } + return $existing; } /** @@ -409,7 +397,7 @@ public static function get_tracked_options() { $table_name = self::get_table_name(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name is safe (from constant). - $results = $wpdb->get_results( $wpdb->prepare( 'SELECT option_name, access_count FROM %i ORDER BY option_name LIMIT %d', $table_name, self::MAX_TRACKED_OPTIONS ), ARRAY_A ); + $results = $wpdb->get_results( $wpdb->prepare( 'SELECT option_name, access_count FROM %i', $table_name ), ARRAY_A ); if ( empty( $results ) ) { return []; @@ -434,7 +422,7 @@ public static function get_tracked_option_keys() { $table_name = self::get_table_name(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name is safe (from constant). - $option_names = $wpdb->get_col( $wpdb->prepare( 'SELECT option_name FROM %i ORDER BY option_name LIMIT %d', $table_name, self::MAX_TRACKED_OPTIONS ) ); + $option_names = $wpdb->get_col( $wpdb->prepare( 'SELECT option_name FROM %i', $table_name ) ); if ( empty( $option_names ) ) { return []; @@ -450,21 +438,11 @@ public static function get_tracked_option_keys() { */ public static function clear_tracked_options() { global $wpdb; - $lock = self::get_tracking_lock(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching - if ( '1' !== (string) $wpdb->get_var( $wpdb->prepare( 'SELECT GET_LOCK(%s, 1)', $lock ) ) ) { - return false; - } - try { - // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching - if ( false !== $wpdb->query( $wpdb->prepare( 'TRUNCATE TABLE %i', self::get_table_name() ) ) ) { - \delete_option( 'aaa_option_optimizer_tracking_limited' ); - return ! \get_option( 'aaa_option_optimizer_tracking_limited', false ); - } + if ( false === $wpdb->query( $wpdb->prepare( 'TRUNCATE TABLE %i', self::get_table_name() ) ) ) { return false; - } finally { - // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching - $wpdb->get_var( $wpdb->prepare( 'SELECT RELEASE_LOCK(%s)', $lock ) ); } + \delete_option( 'aaa_option_optimizer_tracking_limited' ); + return ! \get_option( 'aaa_option_optimizer_tracking_limited', false ); } } diff --git a/src/class-plugin.php b/src/class-plugin.php index 893a8ff..f768f24 100644 --- a/src/class-plugin.php +++ b/src/class-plugin.php @@ -174,7 +174,9 @@ public function monitor_option_accesses_pre_option( $pre, $option_name ) { */ protected function add_option_usage( $option_name ) { if ( ! array_key_exists( $option_name, $this->accessed_options ) ) { - if ( count( $this->accessed_options ) >= 1000 ) { + // Only a request reading more names than storage can hold is capped; reaching this means + // the observation really is incomplete. + if ( count( $this->accessed_options ) >= Database::MAX_TRACKED_OPTIONS ) { $this->tracking_limited = true; return; } diff --git a/tests/hardening.php b/tests/hardening.php index d2bcf5d..f1f120c 100644 --- a/tests/hardening.php +++ b/tests/hardening.php @@ -241,7 +241,6 @@ static function () { check( [ 'size', SORT_DESC ] === $rest->get_sort_params(), 'Valid sort without redundant nonce.' ); $_GET = []; -// Hold the lock on a separate connection to exercise real lock timeouts. Database::clear_tracked_options(); Database::batch_insert( [ 'before_reset' => 2 ] ); Database::mark_tracking_limited(); @@ -253,22 +252,18 @@ static function () { ], ]; update_option( 'option_optimizer', $source, false ); + +// A concurrent connection holding the old GET_LOCK name must not block or fail tracking writes. $other_connection = new \wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST ); -$lock = 'aaaoo_' . md5( DB_NAME . $table ); -check( '1' === (string) $other_connection->get_var( $other_connection->prepare( 'SELECT GET_LOCK(%s, 0)', $lock ) ), 'Acquire the contention fixture lock.' ); +$other_connection->get_var( $other_connection->prepare( 'SELECT GET_LOCK(%s, 0)', 'aaaoo_' . md5( DB_NAME . $table ) ) ); try { - $response = request( 'migrate' ); - check( 503 === $response->get_status() && false === $response->get_data()['success'], 'Migration lock timeout must report failure.' ); - check( 2 === $response->get_data()['remaining'], 'Failed migration must report retained observations.' ); - check( $source === get_option( 'option_optimizer' ), 'Lock timeout must preserve migration source.' ); - check( 1 === (int) $wpdb->get_var( "SELECT COUNT(*) FROM $table" ), 'Failed migration must not insert rows.' ); - check( 503 === request( 'reset' )->get_status(), 'Reset lock timeout must report failure.' ); - check( 2 === (int) $wpdb->get_var( "SELECT access_count FROM $table WHERE option_name = 'before_reset'" ), 'Failed reset must retain tracking rows.' ); - check( Database::is_tracking_limited(), 'Failed reset must retain incomplete state.' ); + $started = microtime( true ); + check( [ 'lock_free' => 1 ] === Database::batch_insert( [ 'lock_free' => 1 ] ), 'Tracking writes take no global lock.' ); + check( microtime( true ) - $started < 0.5, 'Tracking writes never wait on a lock.' ); } finally { - $other_connection->get_var( $other_connection->prepare( 'SELECT RELEASE_LOCK(%s)', $lock ) ); $other_connection->close(); } +$wpdb->query( "DELETE FROM $table WHERE option_name = 'lock_free'" ); $fail_tracking_insert = static function ( $query ) use ( $table ) { return str_starts_with( $query, "INSERT INTO $table " ) ? 'INSERT INTO aaaoo_missing_table VALUES (1)' : $query; @@ -309,25 +304,45 @@ static function () { $reset_plugin->update_tracked_options(); check( 0 === (int) $wpdb->get_var( "SELECT COUNT(*) FROM $table" ), 'Shutdown must not repopulate a successful reset.' ); +// A failed tracking write loses at most that request's counts; it must not pause recommendations. Database::clear_tracked_options(); +$wpdb->suppress_errors( true ); +add_filter( 'query', $fail_tracking_insert ); +try { + check( false === Database::batch_insert( [ 'write_fails' => 1 ] ), 'Failed tracking INSERT reports failure.' ); + check( ! Database::is_tracking_limited(), 'A failed write must not mark tracking incomplete.' ); +} finally { + remove_filter( 'query', $fail_tracking_insert ); + $wpdb->suppress_errors( false ); +} + +// Capacity: new names beyond the limit are dropped and flagged; existing names keep counting. $observations = []; -for ( $index = 0; $index < Database::MAX_TRACKED_OPTIONS + 1; ++$index ) { +for ( $index = 0; $index < Database::MAX_TRACKED_OPTIONS; ++$index ) { $observations[ 'dynamic_' . $index ] = 1; } Database::batch_insert( $observations ); -$table = Database::get_table_name(); -check( Database::MAX_TRACKED_OPTIONS === (int) $wpdb->get_var( "SELECT COUNT(*) FROM $table" ), 'Tracking storage bound.' ); -check( Database::is_tracking_limited(), 'Overflow must mark observations incomplete.' ); -check( [] === request( 'unused-options', [], 'GET' )->get_data()['data'], 'Do not recommend deletions from incomplete observations.' ); -Database::batch_insert( +check( Database::MAX_TRACKED_OPTIONS === (int) $wpdb->get_var( "SELECT COUNT(*) FROM $table" ), 'Fill storage to the limit.' ); +check( ! Database::is_tracking_limited(), 'A full table alone, with nothing dropped, keeps recommendations.' ); + +// Names that match a stored row only by case or accents are existing rows, not new ones. +Database::batch_insert( [ 'DYNAMIC_0' => 2 ] ); +check( 3 === (int) $wpdb->get_var( "SELECT access_count FROM $table WHERE option_name = 'dynamic_0'" ), 'Collation alias updates the existing row at capacity.' ); +check( ! Database::is_tracking_limited(), 'Collation alias at capacity is not a dropped observation.' ); +check( Database::MAX_TRACKED_OPTIONS === (int) $wpdb->get_var( "SELECT COUNT(*) FROM $table" ), 'Collation alias adds no row.' ); + +$written = Database::batch_insert( [ - 'dynamic_0' => 3, + 'dynamic_1' => 3, 'another_missing' => 1, ] ); -check( 4 === (int) $wpdb->get_var( "SELECT access_count FROM $table WHERE option_name = 'dynamic_0'" ), 'Existing counts still update at capacity.' ); -check( Database::MAX_TRACKED_OPTIONS === count( Database::get_tracked_options() ), 'Bounded reads.' ); -// A partial migration removes only committed keys and stops automatic retries. +check( [ 'dynamic_1' => 3 ] === $written, 'Only the existing name is written at capacity.' ); +check( 4 === (int) $wpdb->get_var( "SELECT access_count FROM $table WHERE option_name = 'dynamic_1'" ), 'Existing counts still update at capacity.' ); +check( Database::is_tracking_limited(), 'A dropped new name marks observations incomplete.' ); +check( [] === request( 'unused-options', [], 'GET' )->get_data()['data'], 'Do not recommend deletions from incomplete observations.' ); + +// Legacy data is migrated in full, even past the limit, so migration always finishes. update_option( 'option_optimizer', [ @@ -339,31 +354,44 @@ static function () { false ); $response = request( 'migrate' ); -check( 503 === $response->get_status() && 1 === $response->get_data()['remaining'], 'Full storage must report a partial migration.' ); -check( [ 'zz_unmigrated' => 3 ] === get_option( 'option_optimizer' )['used_options'], 'Retain only unsaved observations after a partial migration.' ); -check( 11 === (int) $wpdb->get_var( "SELECT access_count FROM $table WHERE option_name = 'dynamic_0'" ), 'Commit the existing observation once.' ); -check( 503 === request( 'migrate' )->get_status(), 'Retry while full must report failure.' ); -check( 11 === (int) $wpdb->get_var( "SELECT access_count FROM $table WHERE option_name = 'dynamic_0'" ), 'Retry must not replay already migrated observations.' ); +check( 200 === $response->get_status() && 0 === $response->get_data()['remaining'], 'Migration completes at capacity.' ); +check( [] === get_option( 'option_optimizer' )['used_options'], 'Migration leaves no observations behind.' ); +check( 10 === (int) $wpdb->get_var( "SELECT access_count FROM $table WHERE option_name = 'dynamic_0'" ), 'Commit the existing observation once.' ); +check( 3 === (int) $wpdb->get_var( "SELECT access_count FROM $table WHERE option_name = 'zz_unmigrated'" ), 'Migrate the new observation past the limit.' ); +check( 200 === request( 'migrate' )->get_status(), 'Retry after completion is a no-op.' ); +check( 10 === (int) $wpdb->get_var( "SELECT access_count FROM $table WHERE option_name = 'dynamic_0'" ), 'Retry must not replay already migrated observations.' ); -Database::clear_tracked_options(); -check( ! Database::is_tracking_limited(), 'Reset clears incomplete state.' ); +// An oversized table is never pruned: reads return every row, and core rows survive. +$rows = (int) $wpdb->get_var( "SELECT COUNT(*) FROM $table" ); +check( Database::MAX_TRACKED_OPTIONS + 1 === $rows, 'Table may exceed the soft limit.' ); +Database::batch_insert( [ 'dynamic_2' => 1 ] ); +check( $rows === (int) $wpdb->get_var( "SELECT COUNT(*) FROM $table" ), 'Writes never prune rows.' ); +check( $rows === count( Database::get_tracked_options() ), 'Reads are not truncated at the limit.' ); +check( $rows === count( Database::get_tracked_option_keys() ), 'Key reads are not truncated at the limit.' ); -// An old oversized table is pruned on the next write. -$wpdb->query( "INSERT INTO $table (option_name, access_count) VALUES ('legacy_extra', 1)" ); -Database::batch_insert( $observations ); -$wpdb->query( "INSERT INTO $table (option_name, access_count) VALUES ('legacy_extra_two', 1)" ); -Database::batch_insert( [ 'legacy_extra' => 1 ] ); -check( Database::MAX_TRACKED_OPTIONS === (int) $wpdb->get_var( "SELECT COUNT(*) FROM $table" ), 'Prune legacy oversized storage.' ); Database::clear_tracked_options(); +check( ! Database::is_tracking_limited(), 'Reset clears incomplete state.' ); +// A heavy request (well over 1,000 names) is normal and must not pause recommendations. $plugin = new Plugin(); -for ( $index = 0; $index < 1001; ++$index ) { +for ( $index = 0; $index < 3000; ++$index ) { $plugin->monitor_option_accesses_pre_option( false, 'request_' . $index ); } $_GET['page'] = 'aaa-option-optimizer'; $plugin->update_tracked_options(); -check( Database::is_tracking_limited(), 'Request cap must be visible.' ); -check( 1000 === (int) $wpdb->get_var( "SELECT COUNT(*) FROM $table" ), 'Frontend page parameter must not suppress tracking.' ); +check( ! Database::is_tracking_limited(), 'A heavy request is not an incomplete observation.' ); +check( 3000 === (int) $wpdb->get_var( "SELECT COUNT(*) FROM $table" ), 'Frontend page parameter must not suppress tracking.' ); $_GET = []; +// Only a request reading more names than storage holds is capped and flagged. +Database::clear_tracked_options(); +$plugin = new Plugin(); +for ( $index = 0; $index <= Database::MAX_TRACKED_OPTIONS; ++$index ) { + $plugin->monitor_option_accesses_pre_option( false, 'huge_' . $index ); +} +$plugin->update_tracked_options(); +check( Database::is_tracking_limited(), 'Request cap must be visible.' ); +check( Database::MAX_TRACKED_OPTIONS === (int) $wpdb->get_var( "SELECT COUNT(*) FROM $table" ), 'Request cap bounds one request.' ); +Database::clear_tracked_options(); + \WP_CLI::success( 'Hardening integration regressions passed.' ); From 1ea05ec9b519b626b4bdf780428440a1cda71273 Mon Sep 17 00:00:00 2001 From: Filip Ilic Date: Tue, 17 Nov 2026 13:49:42 +0100 Subject: [PATCH 2/4] Keep the tracking table first in the existing-name join wpdb parses the first FROM to check the table charset for non-ASCII queries; a leading subquery made every at-capacity write with a non-ASCII name fail. Co-Authored-By: Claude Opus 5.5 --- src/class-database.php | 4 +++- tests/hardening.php | 7 +++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/src/class-database.php b/src/class-database.php index f0e457d..5dba778 100644 --- a/src/class-database.php +++ b/src/class-database.php @@ -307,8 +307,10 @@ private static function get_existing_names( array $names ) { $existing = []; foreach ( array_chunk( $names, 500 ) as $chunk ) { $selects = implode( ' UNION ALL ', array_fill( 0, count( $chunk ), 'SELECT %s AS n' ) ); + // The table must come first: for non-ASCII names wpdb parses the first FROM to check the + // table's charset, and a leading subquery makes that check fail the whole query. // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- Placeholders are generated above. - $found = $wpdb->get_col( $wpdb->prepare( "SELECT s.n FROM ($selects) s INNER JOIN %i t ON t.option_name = s.n", array_merge( array_map( 'strval', $chunk ), [ $table ] ) ) ); + $found = $wpdb->get_col( $wpdb->prepare( "SELECT s.n FROM %i t INNER JOIN ($selects) s ON t.option_name = s.n", array_merge( [ $table ], array_map( 'strval', $chunk ) ) ) ); if ( $wpdb->last_error ) { return false; } diff --git a/tests/hardening.php b/tests/hardening.php index f1f120c..463c69c 100644 --- a/tests/hardening.php +++ b/tests/hardening.php @@ -330,6 +330,13 @@ static function () { check( 3 === (int) $wpdb->get_var( "SELECT access_count FROM $table WHERE option_name = 'dynamic_0'" ), 'Collation alias updates the existing row at capacity.' ); check( ! Database::is_tracking_limited(), 'Collation alias at capacity is not a dropped observation.' ); check( Database::MAX_TRACKED_OPTIONS === (int) $wpdb->get_var( "SELECT COUNT(*) FROM $table" ), 'Collation alias adds no row.' ); +// Non-ASCII names at capacity go through wpdb's charset check, which must still find the table. +$wpdb->query( "UPDATE $table SET option_name = 'é😀_stored' WHERE option_name = 'dynamic_9999'" ); +check( [ 'É😀_STORED' => 1 ] === Database::batch_insert( [ 'É😀_STORED' => 1 ] ), 'Non-ASCII alias at capacity is written, not failed.' ); +check( 2 === (int) $wpdb->get_var( "SELECT access_count FROM $table WHERE option_name = 'é😀_stored'" ), 'Non-ASCII alias updates the existing row.' ); +check( [] === Database::batch_insert( [ 'ñew_😀' => 1 ] ), 'New non-ASCII name at capacity is dropped, not failed.' ); +check( Database::is_tracking_limited(), 'Dropped non-ASCII name marks observations incomplete.' ); +delete_option( 'aaa_option_optimizer_tracking_limited' ); $written = Database::batch_insert( [ From 8188c8c175fe256d4d8a7307399dfbe2b0d42da7 Mon Sep 17 00:00:00 2001 From: Filip Ilic Date: Tue, 17 Nov 2026 13:58:14 +0100 Subject: [PATCH 3/4] Update the tracking-limited notice to the new trigger Write failures no longer pause recommendations, so the notice now names the only remaining cause: a full tracking table. Co-Authored-By: Claude Opus 5.5 --- src/class-admin-page.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/class-admin-page.php b/src/class-admin-page.php index 39cb387..e786bf9 100644 --- a/src/class-admin-page.php +++ b/src/class-admin-page.php @@ -283,7 +283,7 @@ public function render_admin_page_ajax() {

-

+

From 3e96b260fcbe3dd8a29ccefb4b94b2f549849700 Mon Sep 17 00:00:00 2001 From: Filip Ilic Date: Tue, 17 Nov 2026 14:09:36 +0100 Subject: [PATCH 4/4] Use an alias both MySQL and SQLite fold in the non-ASCII capacity test SQLite's case folding is ASCII-only, so vary only the ASCII letters; the name stays non-ASCII to keep exercising wpdb's charset check. Co-Authored-By: Claude Opus 5.5 --- tests/hardening.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/hardening.php b/tests/hardening.php index 463c69c..88a3ce5 100644 --- a/tests/hardening.php +++ b/tests/hardening.php @@ -332,7 +332,7 @@ static function () { check( Database::MAX_TRACKED_OPTIONS === (int) $wpdb->get_var( "SELECT COUNT(*) FROM $table" ), 'Collation alias adds no row.' ); // Non-ASCII names at capacity go through wpdb's charset check, which must still find the table. $wpdb->query( "UPDATE $table SET option_name = 'é😀_stored' WHERE option_name = 'dynamic_9999'" ); -check( [ 'É😀_STORED' => 1 ] === Database::batch_insert( [ 'É😀_STORED' => 1 ] ), 'Non-ASCII alias at capacity is written, not failed.' ); +check( [ 'é😀_STORED' => 1 ] === Database::batch_insert( [ 'é😀_STORED' => 1 ] ), 'Non-ASCII alias (ASCII case differs) at capacity is written, not failed.' ); check( 2 === (int) $wpdb->get_var( "SELECT access_count FROM $table WHERE option_name = 'é😀_stored'" ), 'Non-ASCII alias updates the existing row.' ); check( [] === Database::batch_insert( [ 'ñew_😀' => 1 ] ), 'New non-ASCII name at capacity is dropped, not failed.' ); check( Database::is_tracking_limited(), 'Dropped non-ASCII name marks observations incomplete.' );