From 464115d4eada312da2aec8a6a564e25e6c7a00ea Mon Sep 17 00:00:00 2001 From: Grzegorz Ziolkowski Date: Mon, 15 Jun 2026 15:53:19 +0200 Subject: [PATCH 01/51] Site Health: Cache the full results and a timestamp in the status transient. Previously the `health-check-site-status-result` transient stored only the aggregate `good`, `recommended`, and `critical` counts, so any consumer that needed the underlying results had to re-run the Site Health tests synchronously. The scheduled check now caches the complete results array and the time they were collected alongside the counts. The Site Health screen AJAX handler validates the submitted counts and preserves the cached results and timestamp while refreshing the counts, and `enqueue_scripts()` only localizes the counts to avoid embedding the full results in every Site Health and Dashboard page. This provides a reusable cached source of detailed Site Health data for the dashboard, the admin menu, and future REST/Abilities consumers without triggering synchronous tests. Adds unit tests covering the scheduled-check caching and the AJAX result handler. See #65232. Co-Authored-By: Claude Opus 4.8 (1M context) --- src/wp-admin/includes/ajax-actions.php | 34 +++- .../includes/class-wp-site-health.php | 30 ++- tests/phpunit/tests/admin/wpSiteHealth.php | 111 +++++++++++ .../wpAjaxHealthCheckSiteStatusResult.php | 179 ++++++++++++++++++ 4 files changed, 351 insertions(+), 3 deletions(-) create mode 100644 tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php diff --git a/src/wp-admin/includes/ajax-actions.php b/src/wp-admin/includes/ajax-actions.php index 076549b218b82..767a1e2973faf 100644 --- a/src/wp-admin/includes/ajax-actions.php +++ b/src/wp-admin/includes/ajax-actions.php @@ -5449,6 +5449,8 @@ function wp_ajax_health_check_loopback_requests() { * Handles site health check to update the result status via AJAX. * * @since 5.2.0 + * @since 7.1.0 The submitted counts are validated, and the full test results and + * collection timestamp cached by the scheduled check are preserved. */ function wp_ajax_health_check_site_status_result() { check_ajax_referer( 'health-check-site-status-result' ); @@ -5457,7 +5459,37 @@ function wp_ajax_health_check_site_status_result() { wp_send_json_error(); } - set_transient( 'health-check-site-status-result', wp_json_encode( $_POST['counts'] ) ); + $counts = isset( $_POST['counts'] ) ? wp_unslash( $_POST['counts'] ) : null; + + if ( ! is_array( $counts ) ) { + wp_send_json_error(); + } + + $site_status = array( + 'good' => isset( $counts['good'] ) ? (int) $counts['good'] : 0, + 'recommended' => isset( $counts['recommended'] ) ? (int) $counts['recommended'] : 0, + 'critical' => isset( $counts['critical'] ) ? (int) $counts['critical'] : 0, + ); + + /* + * Only the aggregate counts are refreshed here. Preserve the full test results + * and the timestamp recorded by the scheduled check so they are not discarded + * when the counts are updated from the Site Health screen. + */ + $cached = get_transient( 'health-check-site-status-result' ); + $cached = is_string( $cached ) ? json_decode( $cached, true ) : null; + + if ( is_array( $cached ) ) { + if ( isset( $cached['results'] ) && is_array( $cached['results'] ) ) { + $site_status['results'] = $cached['results']; + } + + if ( isset( $cached['timestamp'] ) ) { + $site_status['timestamp'] = (int) $cached['timestamp']; + } + } + + set_transient( 'health-check-site-status-result', wp_json_encode( $site_status ) ); wp_send_json_success(); } diff --git a/src/wp-admin/includes/class-wp-site-health.php b/src/wp-admin/includes/class-wp-site-health.php index b9ce4f472834f..9a02dcb785765 100644 --- a/src/wp-admin/includes/class-wp-site-health.php +++ b/src/wp-admin/includes/class-wp-site-health.php @@ -116,9 +116,20 @@ public function enqueue_scripts() { $issue_counts = get_transient( 'health-check-site-status-result' ); if ( false !== $issue_counts ) { - $issue_counts = json_decode( $issue_counts ); + $issue_counts = json_decode( $issue_counts, true ); - $health_check_js_variables['site_status']['issues'] = $issue_counts; + /* + * The cached result also stores the full test results and a timestamp. + * Only the aggregate counts are needed on the client, so avoid localizing + * the rest of the payload. + */ + if ( is_array( $issue_counts ) ) { + $health_check_js_variables['site_status']['issues'] = array( + 'good' => isset( $issue_counts['good'] ) ? (int) $issue_counts['good'] : 0, + 'recommended' => isset( $issue_counts['recommended'] ) ? (int) $issue_counts['recommended'] : 0, + 'critical' => isset( $issue_counts['critical'] ) ? (int) $issue_counts['critical'] : 0, + ); + } } if ( 'site-health' === $screen->id && ( ! isset( $_GET['tab'] ) || empty( $_GET['tab'] ) ) ) { @@ -3350,6 +3361,9 @@ public function maybe_create_scheduled_event() { * Runs the scheduled event to check and update the latest site health status for the website. * * @since 5.4.0 + * @since 7.1.0 The cached result also stores the full test results under `results` + * and a `timestamp` indicating when they were collected, in addition + * to the aggregate `good`, `recommended`, and `critical` counts. */ public function wp_cron_scheduled_check() { // Bootstrap wp-admin, as WP_Cron doesn't do this for us. @@ -3445,6 +3459,10 @@ public function wp_cron_scheduled_check() { } foreach ( $results as $result ) { + if ( ! is_array( $result ) || ! isset( $result['status'] ) ) { + continue; + } + if ( 'critical' === $result['status'] ) { ++$site_status['critical']; } elseif ( 'recommended' === $result['status'] ) { @@ -3454,6 +3472,14 @@ public function wp_cron_scheduled_check() { } } + /* + * Cache the full results alongside the aggregate counts so consumers can read + * the detailed Site Health status without re-running the tests, and record when + * the results were collected so their freshness can be evaluated. + */ + $site_status['results'] = $results; + $site_status['timestamp'] = time(); + set_transient( 'health-check-site-status-result', wp_json_encode( $site_status ) ); } diff --git a/tests/phpunit/tests/admin/wpSiteHealth.php b/tests/phpunit/tests/admin/wpSiteHealth.php index e325c917b50ff..518efbaaa3283 100644 --- a/tests/phpunit/tests/admin/wpSiteHealth.php +++ b/tests/phpunit/tests/admin/wpSiteHealth.php @@ -742,4 +742,115 @@ public function test_get_test_theme_version_with_no_installed_themes() { $this->assertSame( 'good', $result['status'] ); $this->assertStringContainsString( 'Your site does not have any installed themes.', $result['description'] ); } + + /** + * Ensures the scheduled check caches the full results and a timestamp. + * + * The cached `health-check-site-status-result` transient must contain the + * aggregate counts, the complete (unreduced) test results, and the time the + * results were collected, so consumers can read the detailed Site Health + * status without re-running the tests. + * + * @ticket 65232 + * + * @covers ::wp_cron_scheduled_check + */ + public function test_wp_cron_scheduled_check_caches_full_results() { + $tests = array( + 'direct' => array( + 'fake_critical' => array( + 'label' => 'Fake critical', + 'test' => static function () { + return array( + 'label' => 'Critical label', + 'status' => 'critical', + 'badge' => array( + 'label' => 'Security', + 'color' => 'red', + ), + 'description' => '

Critical description.

', + 'actions' => '', + 'test' => 'fake_critical', + ); + }, + ), + 'fake_recommended' => array( + 'label' => 'Fake recommended', + 'test' => static function () { + return array( + 'label' => 'Recommended label', + 'status' => 'recommended', + 'description' => '

Recommended description.

', + 'test' => 'fake_recommended', + ); + }, + ), + 'fake_good' => array( + 'label' => 'Fake good', + 'test' => static function () { + return array( + 'label' => 'Good label', + 'status' => 'good', + 'description' => '

Good description.

', + 'test' => 'fake_good', + ); + }, + ), + ), + 'async' => array(), + ); + + $filter = static function () use ( $tests ) { + return $tests; + }; + + add_filter( 'site_status_tests', $filter ); + + delete_transient( 'health-check-site-status-result' ); + + $before = time(); + $this->instance->wp_cron_scheduled_check(); + $after = time(); + + remove_filter( 'site_status_tests', $filter ); + + $cached = json_decode( get_transient( 'health-check-site-status-result' ), true ); + + $this->assertIsArray( $cached, 'The cached result should decode to an array.' ); + + // Aggregate counts are preserved at the top level. + $this->assertSame( 1, $cached['good'], 'There should be one good result.' ); + $this->assertSame( 1, $cached['recommended'], 'There should be one recommended result.' ); + $this->assertSame( 1, $cached['critical'], 'There should be one critical result.' ); + + // The full results are cached, including the passing (good) result. + $this->assertArrayHasKey( 'results', $cached, 'The full results should be cached.' ); + $this->assertCount( 3, $cached['results'], 'All test results should be cached, not just actionable ones.' ); + + $results_by_test = array(); + foreach ( $cached['results'] as $result ) { + $results_by_test[ $result['test'] ] = $result; + } + + $this->assertSame( + array( 'fake_critical', 'fake_recommended', 'fake_good' ), + array_keys( $results_by_test ), + 'Every test result should be cached.' + ); + + // The complete result is stored as produced, without stripping HTML. + $this->assertSame( 'critical', $results_by_test['fake_critical']['status'] ); + $this->assertSame( + '

Critical description.

', + $results_by_test['fake_critical']['description'], + 'The full result should be cached without reducing or stripping it.' + ); + $this->assertArrayHasKey( 'badge', $results_by_test['fake_critical'], 'All result fields should be cached.' ); + + // A timestamp records when the results were collected. + $this->assertArrayHasKey( 'timestamp', $cached, 'A collection timestamp should be cached.' ); + $this->assertIsInt( $cached['timestamp'] ); + $this->assertGreaterThanOrEqual( $before, $cached['timestamp'] ); + $this->assertLessThanOrEqual( $after, $cached['timestamp'] ); + } } diff --git a/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php b/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php new file mode 100644 index 0000000000000..020b341acaa4c --- /dev/null +++ b/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php @@ -0,0 +1,179 @@ +_last_response = ''; + + try { + $this->_handleAjax( self::TRANSIENT ); + } catch ( WPAjaxDieContinueException $e ) { + unset( $e ); + } + + return json_decode( $this->_last_response, true ); + } + + /** + * The browser only refreshes the counts, so the full results and timestamp + * cached by the scheduled check must be preserved. + * + * @ticket 65232 + */ + public function test_refreshing_counts_preserves_cached_results_and_timestamp() { + $timestamp = 1715714399; + $results = array( + array( + 'test' => 'fake_critical', + 'label' => 'Critical label', + 'status' => 'critical', + 'description' => '

Critical description.

', + ), + ); + + set_transient( + self::TRANSIENT, + wp_json_encode( + array( + 'good' => 5, + 'recommended' => 0, + 'critical' => 1, + 'results' => $results, + 'timestamp' => $timestamp, + ) + ) + ); + + $this->_setRole( 'administrator' ); + $_POST['_wpnonce'] = wp_create_nonce( self::TRANSIENT ); + $_POST['counts'] = array( + 'good' => 6, + 'recommended' => 2, + 'critical' => 0, + ); + + $response = $this->dispatch_result_request(); + + $this->assertTrue( $response['success'] ); + + $cached = json_decode( get_transient( self::TRANSIENT ), true ); + + // The aggregate counts are refreshed from the request. + $this->assertSame( 6, $cached['good'] ); + $this->assertSame( 2, $cached['recommended'] ); + $this->assertSame( 0, $cached['critical'] ); + + // The results collected by the scheduled check and their timestamp are kept intact. + $this->assertSame( $results, $cached['results'], 'Cached results should be preserved.' ); + $this->assertSame( $timestamp, $cached['timestamp'], 'The timestamp should not be changed by a counts update.' ); + } + + /** + * When nothing has been cached yet, only the counts are stored. + * + * @ticket 65232 + */ + public function test_storing_counts_without_cached_results() { + delete_transient( self::TRANSIENT ); + + $this->_setRole( 'administrator' ); + $_POST['_wpnonce'] = wp_create_nonce( self::TRANSIENT ); + $_POST['counts'] = array( + 'good' => 3, + 'recommended' => 1, + 'critical' => 0, + ); + + $response = $this->dispatch_result_request(); + + $this->assertTrue( $response['success'] ); + + $cached = json_decode( get_transient( self::TRANSIENT ), true ); + + $this->assertSame( 3, $cached['good'] ); + $this->assertSame( 1, $cached['recommended'] ); + $this->assertSame( 0, $cached['critical'] ); + $this->assertArrayNotHasKey( 'results', $cached ); + $this->assertArrayNotHasKey( 'timestamp', $cached ); + } + + /** + * Non-array counts are rejected and leave the cached result untouched. + * + * @ticket 65232 + */ + public function test_invalid_counts_return_error_and_leave_cache_untouched() { + $existing = array( 'good' => 9 ); + set_transient( self::TRANSIENT, wp_json_encode( $existing ) ); + + $this->_setRole( 'administrator' ); + $_POST['_wpnonce'] = wp_create_nonce( self::TRANSIENT ); + // No 'counts' are supplied. + + $response = $this->dispatch_result_request(); + + $this->assertFalse( $response['success'] ); + + $cached = json_decode( get_transient( self::TRANSIENT ), true ); + $this->assertSame( $existing, $cached, 'The cached result should be untouched.' ); + } + + /** + * Users without the capability cannot write to the cache. + * + * @ticket 65232 + */ + public function test_user_without_capability_cannot_write_cache() { + delete_transient( self::TRANSIENT ); + + $this->_setRole( 'subscriber' ); + $_POST['_wpnonce'] = wp_create_nonce( self::TRANSIENT ); + $_POST['counts'] = array( + 'good' => 1, + 'recommended' => 1, + 'critical' => 1, + ); + + $response = $this->dispatch_result_request(); + + $this->assertFalse( $response['success'] ); + $this->assertFalse( get_transient( self::TRANSIENT ), 'No cache should be written for an unauthorized user.' ); + } +} From 4eac8ca8abd191094fe2a30ed3cdfb60d6cab3bd Mon Sep 17 00:00:00 2001 From: Grzegorz Ziolkowski Date: Mon, 15 Jun 2026 16:49:51 +0200 Subject: [PATCH 02/51] Tests: Fix Site Health AJAX tests on multisite --- .../wpAjaxHealthCheckSiteStatusResult.php | 37 +++++++++++++++++-- 1 file changed, 34 insertions(+), 3 deletions(-) diff --git a/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php b/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php index 020b341acaa4c..63fefc2f7c739 100644 --- a/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php +++ b/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php @@ -24,6 +24,13 @@ class Tests_Ajax_wpAjaxHealthCheckSiteStatusResult extends WP_Ajax_UnitTestCase */ const TRANSIENT = 'health-check-site-status-result'; + /** + * User ID granted super admin privileges during a multisite test. + * + * @var int + */ + private $super_admin_user_id = 0; + /** * Sets up the test fixture. */ @@ -34,6 +41,30 @@ public function set_up() { add_action( 'wp_ajax_' . self::TRANSIENT, 'wp_ajax_health_check_site_status_result', 1 ); } + /** + * Cleans up the test fixture. + */ + public function tear_down() { + if ( is_multisite() && $this->super_admin_user_id ) { + revoke_super_admin( $this->super_admin_user_id ); + $this->super_admin_user_id = 0; + } + + parent::tear_down(); + } + + /** + * Sets the current user to one that can view Site Health checks. + */ + private function set_user_with_site_health_capability() { + $this->_setRole( 'administrator' ); + + if ( is_multisite() ) { + $this->super_admin_user_id = get_current_user_id(); + grant_super_admin( $this->super_admin_user_id ); + } + } + /** * Dispatches the Ajax request and returns the decoded JSON response. * @@ -81,7 +112,7 @@ public function test_refreshing_counts_preserves_cached_results_and_timestamp() ) ); - $this->_setRole( 'administrator' ); + $this->set_user_with_site_health_capability(); $_POST['_wpnonce'] = wp_create_nonce( self::TRANSIENT ); $_POST['counts'] = array( 'good' => 6, @@ -113,7 +144,7 @@ public function test_refreshing_counts_preserves_cached_results_and_timestamp() public function test_storing_counts_without_cached_results() { delete_transient( self::TRANSIENT ); - $this->_setRole( 'administrator' ); + $this->set_user_with_site_health_capability(); $_POST['_wpnonce'] = wp_create_nonce( self::TRANSIENT ); $_POST['counts'] = array( 'good' => 3, @@ -143,7 +174,7 @@ public function test_invalid_counts_return_error_and_leave_cache_untouched() { $existing = array( 'good' => 9 ); set_transient( self::TRANSIENT, wp_json_encode( $existing ) ); - $this->_setRole( 'administrator' ); + $this->set_user_with_site_health_capability(); $_POST['_wpnonce'] = wp_create_nonce( self::TRANSIENT ); // No 'counts' are supplied. From 2f40735096d6bfc6603119dbf398b55c4c95617f Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Mon, 15 Jun 2026 11:37:03 -0700 Subject: [PATCH 03/51] Fix PHPStan `argument.type` error for mixed being passed to `json_encode()` --- src/wp-admin/includes/class-wp-site-health.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/wp-admin/includes/class-wp-site-health.php b/src/wp-admin/includes/class-wp-site-health.php index 9a02dcb785765..1d5763036de57 100644 --- a/src/wp-admin/includes/class-wp-site-health.php +++ b/src/wp-admin/includes/class-wp-site-health.php @@ -115,7 +115,7 @@ public function enqueue_scripts() { $issue_counts = get_transient( 'health-check-site-status-result' ); - if ( false !== $issue_counts ) { + if ( is_string( $issue_counts ) ) { $issue_counts = json_decode( $issue_counts, true ); /* From 1bbc163a3708da055853c2e4691ad58ce4b2ee7e Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Mon, 15 Jun 2026 11:40:28 -0700 Subject: [PATCH 04/51] Fix PHPStan `argument.type` error for `wp_unslash()` expecting `array|string`, but `mixed` given. --- src/wp-admin/includes/ajax-actions.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/wp-admin/includes/ajax-actions.php b/src/wp-admin/includes/ajax-actions.php index 767a1e2973faf..9af93caa56ab2 100644 --- a/src/wp-admin/includes/ajax-actions.php +++ b/src/wp-admin/includes/ajax-actions.php @@ -5459,7 +5459,7 @@ function wp_ajax_health_check_site_status_result() { wp_send_json_error(); } - $counts = isset( $_POST['counts'] ) ? wp_unslash( $_POST['counts'] ) : null; + $counts = isset( $_POST['counts'] ) && is_array( $_POST['counts'] ) ? wp_unslash( $_POST['counts'] ) : null; if ( ! is_array( $counts ) ) { wp_send_json_error(); From f3a5c6a0124094fea02d9ac74942967d7fb85605 Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Mon, 15 Jun 2026 11:41:48 -0700 Subject: [PATCH 05/51] Simply accessing counts --- src/wp-admin/includes/ajax-actions.php | 6 +++--- src/wp-admin/includes/class-wp-site-health.php | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/wp-admin/includes/ajax-actions.php b/src/wp-admin/includes/ajax-actions.php index 9af93caa56ab2..1b508acde6a11 100644 --- a/src/wp-admin/includes/ajax-actions.php +++ b/src/wp-admin/includes/ajax-actions.php @@ -5466,9 +5466,9 @@ function wp_ajax_health_check_site_status_result() { } $site_status = array( - 'good' => isset( $counts['good'] ) ? (int) $counts['good'] : 0, - 'recommended' => isset( $counts['recommended'] ) ? (int) $counts['recommended'] : 0, - 'critical' => isset( $counts['critical'] ) ? (int) $counts['critical'] : 0, + 'good' => (int) ( $counts['good'] ?? 0 ), + 'recommended' => (int) ( $counts['recommended'] ?? 0 ), + 'critical' => (int) ( $counts['critical'] ?? 0 ), ); /* diff --git a/src/wp-admin/includes/class-wp-site-health.php b/src/wp-admin/includes/class-wp-site-health.php index 1d5763036de57..7702aab1c3dba 100644 --- a/src/wp-admin/includes/class-wp-site-health.php +++ b/src/wp-admin/includes/class-wp-site-health.php @@ -125,9 +125,9 @@ public function enqueue_scripts() { */ if ( is_array( $issue_counts ) ) { $health_check_js_variables['site_status']['issues'] = array( - 'good' => isset( $issue_counts['good'] ) ? (int) $issue_counts['good'] : 0, - 'recommended' => isset( $issue_counts['recommended'] ) ? (int) $issue_counts['recommended'] : 0, - 'critical' => isset( $issue_counts['critical'] ) ? (int) $issue_counts['critical'] : 0, + 'good' => (int) ( $issue_counts['good'] ?? 0 ), + 'recommended' => (int) ( $issue_counts['recommended'] ?? 0 ), + 'critical' => (int) ( $issue_counts['critical'] ?? 0 ), ); } } From 8e4e45ad5137a0384250efaaf3986f20c95d25e0 Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Mon, 15 Jun 2026 11:49:59 -0700 Subject: [PATCH 06/51] Add void return type hints --- tests/phpunit/tests/admin/wpSiteHealth.php | 2 +- .../ajax/wpAjaxHealthCheckSiteStatusResult.php | 14 +++++++------- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/tests/phpunit/tests/admin/wpSiteHealth.php b/tests/phpunit/tests/admin/wpSiteHealth.php index 518efbaaa3283..2db7b90cbac76 100644 --- a/tests/phpunit/tests/admin/wpSiteHealth.php +++ b/tests/phpunit/tests/admin/wpSiteHealth.php @@ -755,7 +755,7 @@ public function test_get_test_theme_version_with_no_installed_themes() { * * @covers ::wp_cron_scheduled_check */ - public function test_wp_cron_scheduled_check_caches_full_results() { + public function test_wp_cron_scheduled_check_caches_full_results(): void { $tests = array( 'direct' => array( 'fake_critical' => array( diff --git a/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php b/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php index 63fefc2f7c739..d791352046172 100644 --- a/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php +++ b/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php @@ -34,7 +34,7 @@ class Tests_Ajax_wpAjaxHealthCheckSiteStatusResult extends WP_Ajax_UnitTestCase /** * Sets up the test fixture. */ - public function set_up() { + public function set_up(): void { parent::set_up(); // This Ajax action is not part of the core actions registered by the base test case. @@ -44,7 +44,7 @@ public function set_up() { /** * Cleans up the test fixture. */ - public function tear_down() { + public function tear_down(): void { if ( is_multisite() && $this->super_admin_user_id ) { revoke_super_admin( $this->super_admin_user_id ); $this->super_admin_user_id = 0; @@ -56,7 +56,7 @@ public function tear_down() { /** * Sets the current user to one that can view Site Health checks. */ - private function set_user_with_site_health_capability() { + private function set_user_with_site_health_capability(): void { $this->_setRole( 'administrator' ); if ( is_multisite() ) { @@ -88,7 +88,7 @@ private function dispatch_result_request() { * * @ticket 65232 */ - public function test_refreshing_counts_preserves_cached_results_and_timestamp() { + public function test_refreshing_counts_preserves_cached_results_and_timestamp(): void { $timestamp = 1715714399; $results = array( array( @@ -141,7 +141,7 @@ public function test_refreshing_counts_preserves_cached_results_and_timestamp() * * @ticket 65232 */ - public function test_storing_counts_without_cached_results() { + public function test_storing_counts_without_cached_results(): void { delete_transient( self::TRANSIENT ); $this->set_user_with_site_health_capability(); @@ -170,7 +170,7 @@ public function test_storing_counts_without_cached_results() { * * @ticket 65232 */ - public function test_invalid_counts_return_error_and_leave_cache_untouched() { + public function test_invalid_counts_return_error_and_leave_cache_untouched(): void { $existing = array( 'good' => 9 ); set_transient( self::TRANSIENT, wp_json_encode( $existing ) ); @@ -191,7 +191,7 @@ public function test_invalid_counts_return_error_and_leave_cache_untouched() { * * @ticket 65232 */ - public function test_user_without_capability_cannot_write_cache() { + public function test_user_without_capability_cannot_write_cache(): void { delete_transient( self::TRANSIENT ); $this->_setRole( 'subscriber' ); From cfdd9be8b116a87203f463873074dd24a82c3042 Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Mon, 15 Jun 2026 11:51:09 -0700 Subject: [PATCH 07/51] Update dispatch_result_request method to always return array --- .../phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php b/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php index d791352046172..9d2ac0245ea57 100644 --- a/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php +++ b/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php @@ -68,9 +68,9 @@ private function set_user_with_site_health_capability(): void { /** * Dispatches the Ajax request and returns the decoded JSON response. * - * @return array|null The decoded response, or null when no JSON was returned. + * @return array{ success: bool, ... } The decoded response. */ - private function dispatch_result_request() { + private function dispatch_result_request(): array { $this->_last_response = ''; try { From 68c44fd0c7c583462452622aeb4468e9936749be Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Mon, 15 Jun 2026 11:51:50 -0700 Subject: [PATCH 08/51] Use native property type hint --- .../phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php b/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php index 9d2ac0245ea57..0662d9b5c8ae9 100644 --- a/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php +++ b/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php @@ -26,10 +26,8 @@ class Tests_Ajax_wpAjaxHealthCheckSiteStatusResult extends WP_Ajax_UnitTestCase /** * User ID granted super admin privileges during a multisite test. - * - * @var int */ - private $super_admin_user_id = 0; + private int $super_admin_user_id = 0; /** * Sets up the test fixture. From 1bf29eae74f94531f4f030191984fa59d69a4eba Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Mon, 15 Jun 2026 11:53:09 -0700 Subject: [PATCH 09/51] fixup! Update dispatch_result_request method to always return array --- .../phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php b/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php index 0662d9b5c8ae9..bbf8e1e141d5e 100644 --- a/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php +++ b/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php @@ -77,7 +77,9 @@ private function dispatch_result_request(): array { unset( $e ); } - return json_decode( $this->_last_response, true ); + $response = json_decode( $this->_last_response, true ); + assert( is_array( $response ) ); + return $response; } /** From 226f71002dd5ced913f5edd579fc93ae1086df2e Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Mon, 15 Jun 2026 12:11:00 -0700 Subject: [PATCH 10/51] Fix PHPStan issues in tests --- tests/phpunit/tests/admin/wpSiteHealth.php | 11 ++++++++++- .../ajax/wpAjaxHealthCheckSiteStatusResult.php | 17 ++++++++++++++--- 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/tests/phpunit/tests/admin/wpSiteHealth.php b/tests/phpunit/tests/admin/wpSiteHealth.php index 2db7b90cbac76..cf10a419b89f6 100644 --- a/tests/phpunit/tests/admin/wpSiteHealth.php +++ b/tests/phpunit/tests/admin/wpSiteHealth.php @@ -814,9 +814,14 @@ public function test_wp_cron_scheduled_check_caches_full_results(): void { remove_filter( 'site_status_tests', $filter ); - $cached = json_decode( get_transient( 'health-check-site-status-result' ), true ); + $transient = get_transient( 'health-check-site-status-result' ); + $this->assertIsString( $transient ); + $cached = json_decode( $transient, true ); $this->assertIsArray( $cached, 'The cached result should decode to an array.' ); + $this->assertArrayHasKey( 'good', $cached ); + $this->assertArrayHasKey( 'recommended', $cached ); + $this->assertArrayHasKey( 'critical', $cached ); // Aggregate counts are preserved at the top level. $this->assertSame( 1, $cached['good'], 'There should be one good result.' ); @@ -825,10 +830,14 @@ public function test_wp_cron_scheduled_check_caches_full_results(): void { // The full results are cached, including the passing (good) result. $this->assertArrayHasKey( 'results', $cached, 'The full results should be cached.' ); + $this->assertIsArray( $cached['results'] ); $this->assertCount( 3, $cached['results'], 'All test results should be cached, not just actionable ones.' ); $results_by_test = array(); foreach ( $cached['results'] as $result ) { + $this->assertIsArray( $result ); + $this->assertArrayHasKey( 'test', $result ); + $this->assertIsString( $result['test'] ); $results_by_test[ $result['test'] ] = $result; } diff --git a/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php b/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php index bbf8e1e141d5e..4fc24ed5216a8 100644 --- a/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php +++ b/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php @@ -124,7 +124,10 @@ public function test_refreshing_counts_preserves_cached_results_and_timestamp(): $this->assertTrue( $response['success'] ); - $cached = json_decode( get_transient( self::TRANSIENT ), true ); + $transient = get_transient( self::TRANSIENT ); + $this->assertIsString( $transient ); + $cached = json_decode( $transient, true ); + $this->assertIsArray( $cached ); // The aggregate counts are refreshed from the request. $this->assertSame( 6, $cached['good'] ); @@ -156,7 +159,13 @@ public function test_storing_counts_without_cached_results(): void { $this->assertTrue( $response['success'] ); - $cached = json_decode( get_transient( self::TRANSIENT ), true ); + $transient = get_transient( self::TRANSIENT ); + $this->assertIsString( $transient ); + $cached = json_decode( $transient, true ); + $this->assertIsArray( $cached ); + $this->assertArrayHasKey( 'good', $cached ); + $this->assertArrayHasKey( 'recommended', $cached ); + $this->assertArrayHasKey( 'critical', $cached ); $this->assertSame( 3, $cached['good'] ); $this->assertSame( 1, $cached['recommended'] ); @@ -182,7 +191,9 @@ public function test_invalid_counts_return_error_and_leave_cache_untouched(): vo $this->assertFalse( $response['success'] ); - $cached = json_decode( get_transient( self::TRANSIENT ), true ); + $transient = get_transient( self::TRANSIENT ); + $this->assertIsString( $transient ); + $cached = json_decode( $transient, true ); $this->assertSame( $existing, $cached, 'The cached result should be untouched.' ); } From c9e97d4f42154412edb8886db56ec7e23475eab9 Mon Sep 17 00:00:00 2001 From: Grzegorz Ziolkowski Date: Tue, 16 Jun 2026 12:11:00 +0200 Subject: [PATCH 11/51] Site Health: Cache the full results in a dedicated, non-autoloaded transient. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Following review feedback, store only the aggregate counts in the autoloaded `health-check-site-status-result` transient and cache the full per-test results separately in `health-check-site-status-detail`, which has an expiration so the larger payload is not autoloaded on every request. The Site Health screen submits the full results — including the asynchronous tests that require JavaScript to run — and they are sanitized and cached as the authoritative detailed results. The scheduled check refreshes only missing or stale entries so it does not discard fresher results collected from the screen. Each result carries its own timestamp, and entries that have not been refreshed within a month are dropped. Adds WP_Site_Health::get_site_status_counts(), get_site_status_detail(), and merge_site_status_detail() as the canonical accessors, and updates the unit and Ajax tests accordingly. See #65232. Co-Authored-By: Claude Opus 4.8 (1M context) --- src/js/_enqueues/admin/site-health.js | 31 ++ src/wp-admin/includes/ajax-actions.php | 52 ++- .../includes/class-wp-site-health.php | 310 +++++++++++-- tests/phpunit/tests/admin/wpSiteHealth.php | 417 ++++++++++++++---- .../wpAjaxHealthCheckSiteStatusResult.php | 255 ++++++++--- 5 files changed, 860 insertions(+), 205 deletions(-) diff --git a/src/js/_enqueues/admin/site-health.js b/src/js/_enqueues/admin/site-health.js index 8d8c40c70c3e9..52b3ff2d81f40 100644 --- a/src/js/_enqueues/admin/site-health.js +++ b/src/js/_enqueues/admin/site-health.js @@ -165,6 +165,23 @@ jQuery( function( $ ) { issue.test = issue.status + count; } + /* + * Collect the full result so it can be cached server-side. These results + * include the asynchronous tests that only run in the browser. + */ + if ( 'undefined' === typeof SiteHealth.site_status.results ) { + SiteHealth.site_status.results = []; + } + + SiteHealth.site_status.results.push( { + test: issue.test, + label: issue.label, + status: issue.status, + badge: issue.badge, + description: issue.description, + actions: issue.actions + } ); + if ( 'critical' === issue.status ) { heading = sprintf( _n( '%s critical issue', '%s critical issues', count ), @@ -254,6 +271,7 @@ jQuery( function( $ ) { } if ( isStatusTab ) { + // Refresh the lightweight counts first, so a large detailed payload can't block them. $.post( ajaxurl, { @@ -263,6 +281,18 @@ jQuery( function( $ ) { } ); + // Send the full results separately, as a best-effort detailed cache update. + if ( 'undefined' !== typeof SiteHealth.site_status.results ) { + $.post( + ajaxurl, + { + 'action': 'health-check-site-status-result', + '_wpnonce': SiteHealth.nonce.site_status_result, + 'results': JSON.stringify( SiteHealth.site_status.results ) + } + ); + } + if ( 100 === val ) { $( '.site-status-all-clear' ).removeClass( 'hide' ); $( '.site-status-has-issues' ).addClass( 'hide' ); @@ -381,6 +411,7 @@ jQuery( function( $ ) { 'recommended': 0, 'critical': 0 }; + SiteHealth.site_status.results = []; } if ( 0 < SiteHealth.site_status.direct.length ) { diff --git a/src/wp-admin/includes/ajax-actions.php b/src/wp-admin/includes/ajax-actions.php index 1b508acde6a11..9212afd2036c6 100644 --- a/src/wp-admin/includes/ajax-actions.php +++ b/src/wp-admin/includes/ajax-actions.php @@ -5448,9 +5448,13 @@ function wp_ajax_health_check_loopback_requests() { /** * Handles site health check to update the result status via AJAX. * + * The aggregate counts and the full per-test results are sent as two independent + * requests, so a large results payload cannot prevent the lightweight counts from being + * refreshed. Each is handled on its own here, and either may be omitted. + * * @since 5.2.0 - * @since 7.1.0 The submitted counts are validated, and the full test results and - * collection timestamp cached by the scheduled check are preserved. + * @since 7.1.0 The submitted counts are validated, and the optional full per-test results + * are sanitized and cached separately as the authoritative detailed results. */ function wp_ajax_health_check_site_status_result() { check_ajax_referer( 'health-check-site-status-result' ); @@ -5459,37 +5463,37 @@ function wp_ajax_health_check_site_status_result() { wp_send_json_error(); } - $counts = isset( $_POST['counts'] ) && is_array( $_POST['counts'] ) ? wp_unslash( $_POST['counts'] ) : null; - - if ( ! is_array( $counts ) ) { - wp_send_json_error(); + if ( ! class_exists( 'WP_Site_Health' ) ) { + require_once ABSPATH . 'wp-admin/includes/class-wp-site-health.php'; } - $site_status = array( - 'good' => (int) ( $counts['good'] ?? 0 ), - 'recommended' => (int) ( $counts['recommended'] ?? 0 ), - 'critical' => (int) ( $counts['critical'] ?? 0 ), - ); + $updated = false; + + // Refresh the lightweight, autoloaded aggregate counts used by the admin menu and Dashboard. + if ( isset( $_POST['counts'] ) && is_array( $_POST['counts'] ) ) { + $counts = wp_unslash( $_POST['counts'] ); + WP_Site_Health::set_site_status_counts( $counts ); + + $updated = true; + } /* - * Only the aggregate counts are refreshed here. Preserve the full test results - * and the timestamp recorded by the scheduled check so they are not discarded - * when the counts are updated from the Site Health screen. + * Cache the full per-test results as the authoritative detailed results. These include + * the asynchronous tests that require JavaScript to run. The values are sanitized in + * WP_Site_Health::update_site_status_detail(). */ - $cached = get_transient( 'health-check-site-status-result' ); - $cached = is_string( $cached ) ? json_decode( $cached, true ) : null; - - if ( is_array( $cached ) ) { - if ( isset( $cached['results'] ) && is_array( $cached['results'] ) ) { - $site_status['results'] = $cached['results']; - } + if ( isset( $_POST['results'] ) && is_string( $_POST['results'] ) ) { + $results = json_decode( wp_unslash( $_POST['results'] ), true ); - if ( isset( $cached['timestamp'] ) ) { - $site_status['timestamp'] = (int) $cached['timestamp']; + if ( is_array( $results ) ) { + WP_Site_Health::update_site_status_detail( $results, true ); + $updated = true; } } - set_transient( 'health-check-site-status-result', wp_json_encode( $site_status ) ); + if ( ! $updated ) { + wp_send_json_error(); + } wp_send_json_success(); } diff --git a/src/wp-admin/includes/class-wp-site-health.php b/src/wp-admin/includes/class-wp-site-health.php index 7702aab1c3dba..f61ee7f8a8245 100644 --- a/src/wp-admin/includes/class-wp-site-health.php +++ b/src/wp-admin/includes/class-wp-site-health.php @@ -32,6 +32,26 @@ class WP_Site_Health { private $timeout_missed_cron = null; private $timeout_late_cron = null; + /** + * Transient name for the cached aggregate Site Health status counts. + * + * This value is small and read on the admin menu and Dashboard, so it remains + * autoloaded. + * + * @since 7.1.0 + */ + const STATUS_RESULT_TRANSIENT = 'health-check-site-status-result'; + + /** + * Transient name for the cached detailed Site Health test results. + * + * This value can be large, so it is stored with an expiration to keep it from + * being autoloaded on every request. + * + * @since 7.1.0 + */ + const STATUS_DETAIL_TRANSIENT = 'health-check-site-status-detail'; + /** * WP_Site_Health constructor. * @@ -113,24 +133,7 @@ public function enqueue_scripts() { ), ); - $issue_counts = get_transient( 'health-check-site-status-result' ); - - if ( is_string( $issue_counts ) ) { - $issue_counts = json_decode( $issue_counts, true ); - - /* - * The cached result also stores the full test results and a timestamp. - * Only the aggregate counts are needed on the client, so avoid localizing - * the rest of the payload. - */ - if ( is_array( $issue_counts ) ) { - $health_check_js_variables['site_status']['issues'] = array( - 'good' => (int) ( $issue_counts['good'] ?? 0 ), - 'recommended' => (int) ( $issue_counts['recommended'] ?? 0 ), - 'critical' => (int) ( $issue_counts['critical'] ?? 0 ), - ); - } - } + $health_check_js_variables['site_status']['issues'] = self::get_site_status_counts(); if ( 'site-health' === $screen->id && ( ! isset( $_GET['tab'] ) || empty( $_GET['tab'] ) ) ) { $tests = WP_Site_Health::get_tests(); @@ -3361,9 +3364,8 @@ public function maybe_create_scheduled_event() { * Runs the scheduled event to check and update the latest site health status for the website. * * @since 5.4.0 - * @since 7.1.0 The cached result also stores the full test results under `results` - * and a `timestamp` indicating when they were collected, in addition - * to the aggregate `good`, `recommended`, and `critical` counts. + * @since 7.1.0 The full test results are also cached in a separate detailed + * transient via WP_Site_Health::update_site_status_detail(). */ public function wp_cron_scheduled_check() { // Bootstrap wp-admin, as WP_Cron doesn't do this for us. @@ -3406,7 +3408,7 @@ public function wp_cron_scheduled_check() { } } - foreach ( $tests['async'] as $test ) { + foreach ( $tests['async'] as $test_name => $test ) { if ( ! empty( $test['skip_cron'] ) ) { continue; } @@ -3450,7 +3452,9 @@ public function wp_cron_scheduled_check() { if ( is_array( $result ) ) { $results[] = $result; } else { + // Include the test identifier so the result is counted and cached consistently. $results[] = array( + 'test' => $test_name, 'status' => 'recommended', 'label' => __( 'A test is unavailable' ), ); @@ -3459,28 +3463,272 @@ public function wp_cron_scheduled_check() { } foreach ( $results as $result ) { - if ( ! is_array( $result ) || ! isset( $result['status'] ) ) { + if ( ! is_array( $result ) ) { continue; } - if ( 'critical' === $result['status'] ) { + $status = isset( $result['status'] ) ? $result['status'] : ''; + + if ( 'critical' === $status ) { ++$site_status['critical']; - } elseif ( 'recommended' === $result['status'] ) { + } elseif ( 'recommended' === $status ) { ++$site_status['recommended']; } else { ++$site_status['good']; } } + self::set_site_status_counts( $site_status ); + /* - * Cache the full results alongside the aggregate counts so consumers can read - * the detailed Site Health status without re-running the tests, and record when - * the results were collected so their freshness can be evaluated. + * Cache the full results separately, keyed by test, so consumers can read the + * detailed Site Health status without re-running the tests. + * + * The scheduled check is not authoritative: it refreshes only missing or stale + * entries so it does not discard fresher results collected from the Site Health + * screen, which also include the asynchronous tests that require JavaScript to run. */ - $site_status['results'] = $results; - $site_status['timestamp'] = time(); + self::update_site_status_detail( $results, false ); + } + + /** + * Returns the cached aggregate Site Health status counts. + * + * @since 7.1.0 + * + * @return array{good: int, recommended: int, critical: int} Aggregate counts. Each + * value is `0` when no + * result has been cached. + */ + public static function get_site_status_counts(): array { + $counts = array( + 'good' => 0, + 'recommended' => 0, + 'critical' => 0, + ); + + $cached = get_transient( self::STATUS_RESULT_TRANSIENT ); + $cached = is_string( $cached ) ? json_decode( $cached, true ) : null; + + if ( ! is_array( $cached ) ) { + return $counts; + } + + $counts['good'] = (int) ( $cached['good'] ?? 0 ); + $counts['recommended'] = (int) ( $cached['recommended'] ?? 0 ); + $counts['critical'] = (int) ( $cached['critical'] ?? 0 ); + + return $counts; + } + + /** + * Caches the aggregate Site Health status counts. + * + * @since 7.1.0 + * + * @param array $counts Aggregate counts. + */ + public static function set_site_status_counts( array $counts ): void { + set_transient( + self::STATUS_RESULT_TRANSIENT, + wp_json_encode( + array( + 'good' => (int) ( $counts['good'] ?? 0 ), + 'recommended' => (int) ( $counts['recommended'] ?? 0 ), + 'critical' => (int) ( $counts['critical'] ?? 0 ), + ) + ) + ); + } + + /** + * Returns the cached detailed Site Health test results. + * + * The `counts` are derived from the cached `results`, so the two are always + * internally consistent. They may differ from WP_Site_Health::get_site_status_counts(), + * which reflects the latest run for the admin menu and Dashboard. Consumers that need a + * consistent view of counts and detailed results should read both from here. + * + * @since 7.1.0 + * + * @return array{ + * results: list>, + * counts: array{good: int, recommended: int, critical: int}, + * timestamp: int, + * } The cached results as a list, aggregate counts derived from those same results, and + * the time of the most recent update. `results` is empty, all counts are `0`, and + * `timestamp` is `0` when none are cached. + */ + public static function get_site_status_detail(): array { + $detail = array( + 'results' => array(), + 'counts' => array( + 'good' => 0, + 'recommended' => 0, + 'critical' => 0, + ), + 'timestamp' => 0, + ); + + $cached = get_transient( self::STATUS_DETAIL_TRANSIENT ); + $cached = is_string( $cached ) ? json_decode( $cached, true ) : null; + + if ( is_array( $cached ) && isset( $cached['results'] ) && is_array( $cached['results'] ) ) { + $detail['results'] = array_values( $cached['results'] ); + $detail['counts'] = self::count_site_status_results( $detail['results'] ); + $detail['timestamp'] = isset( $cached['timestamp'] ) ? (int) $cached['timestamp'] : 0; + } + + return $detail; + } + + /** + * Updates the detailed Site Health results cache. + * + * Results are normalized and sanitized, then stored keyed by test name with a + * per-result timestamp. Entries that have not been refreshed within a month are + * dropped, for example when the plugin that registered a test has been deactivated. + * + * @since 7.1.0 + * + * @param array $results List of raw Site Health test result arrays. + * @param bool $authoritative Whether to overwrite existing cached entries for the + * same test. The Site Health screen passes `true` because + * its results include the JavaScript-only asynchronous + * tests. The scheduled check passes `false` so it refreshes + * only missing or stale entries without discarding fresher + * results collected from the screen. + */ + public static function update_site_status_detail( array $results, bool $authoritative ): void { + $now = time(); + + $cached = get_transient( self::STATUS_DETAIL_TRANSIENT ); + $cached = is_string( $cached ) ? json_decode( $cached, true ) : null; + + $stored = ( is_array( $cached ) && isset( $cached['results'] ) && is_array( $cached['results'] ) ) + ? $cached['results'] + : array(); + + foreach ( $results as $result ) { + $sanitized = self::sanitize_site_status_result( $result ); + + if ( null === $sanitized ) { + continue; + } + + $test = $sanitized['test']; + + /* + * When not authoritative, keep a recent existing entry rather than overwriting + * it. This preserves results collected from the Site Health screen (including + * the asynchronous tests) when the scheduled check runs afterwards. + */ + if ( ! $authoritative + && isset( $stored[ $test ]['timestamp'] ) + && ( $now - (int) $stored[ $test ]['timestamp'] ) < WEEK_IN_SECONDS + ) { + continue; + } + + $sanitized['timestamp'] = $now; + $stored[ $test ] = $sanitized; + } + + // Drop results that have not been refreshed within the last month. + foreach ( $stored as $test => $result ) { + if ( ! isset( $result['timestamp'] ) || ( $now - (int) $result['timestamp'] ) > MONTH_IN_SECONDS ) { + unset( $stored[ $test ] ); + } + } + + if ( empty( $stored ) ) { + delete_transient( self::STATUS_DETAIL_TRANSIENT ); + return; + } + + set_transient( + self::STATUS_DETAIL_TRANSIENT, + wp_json_encode( + array( + 'results' => $stored, + // A counts snapshot derived from the same results, kept for self-describing cache reads. + 'counts' => self::count_site_status_results( array_values( $stored ) ), + 'timestamp' => $now, + ) + ), + MONTH_IN_SECONDS + ); + } + + /** + * Counts a set of Site Health results by status. + * + * @since 7.1.0 + * + * @param array> $results List of result arrays. + * @return array{good: int, recommended: int, critical: int} Aggregate counts. Any + * unrecognized status is + * counted as `good`. + */ + private static function count_site_status_results( array $results ): array { + $counts = array( + 'good' => 0, + 'recommended' => 0, + 'critical' => 0, + ); + + foreach ( $results as $result ) { + $status = isset( $result['status'] ) ? $result['status'] : ''; + + if ( 'critical' === $status ) { + ++$counts['critical']; + } elseif ( 'recommended' === $status ) { + ++$counts['recommended']; + } else { + ++$counts['good']; + } + } + + return $counts; + } + + /** + * Normalizes and sanitizes a single Site Health test result for caching. + * + * @since 7.1.0 + * + * @param mixed $result Raw test result data. + * @return array|null The sanitized result, or null when required fields are missing + * or the status is not recognized. + */ + private static function sanitize_site_status_result( $result ): ?array { + if ( ! is_array( $result ) ) { + return null; + } + + $test = isset( $result['test'] ) ? sanitize_text_field( (string) $result['test'] ) : ''; + $status = isset( $result['status'] ) ? sanitize_key( (string) $result['status'] ) : ''; + + if ( '' === $test || ! in_array( $status, array( 'good', 'recommended', 'critical' ), true ) ) { + return null; + } + + $sanitized = array( + 'test' => $test, + 'label' => isset( $result['label'] ) ? sanitize_text_field( (string) $result['label'] ) : '', + 'status' => $status, + 'description' => isset( $result['description'] ) ? wp_kses_post( (string) $result['description'] ) : '', + 'actions' => isset( $result['actions'] ) ? wp_kses_post( (string) $result['actions'] ) : '', + ); + + if ( isset( $result['badge'] ) && is_array( $result['badge'] ) ) { + $sanitized['badge'] = array( + 'label' => isset( $result['badge']['label'] ) ? sanitize_text_field( (string) $result['badge']['label'] ) : '', + 'color' => isset( $result['badge']['color'] ) ? sanitize_key( (string) $result['badge']['color'] ) : '', + ); + } - set_transient( 'health-check-site-status-result', wp_json_encode( $site_status ) ); + return $sanitized; } /** diff --git a/tests/phpunit/tests/admin/wpSiteHealth.php b/tests/phpunit/tests/admin/wpSiteHealth.php index cf10a419b89f6..965640a110cf7 100644 --- a/tests/phpunit/tests/admin/wpSiteHealth.php +++ b/tests/phpunit/tests/admin/wpSiteHealth.php @@ -744,69 +744,100 @@ public function test_get_test_theme_version_with_no_installed_themes() { } /** - * Ensures the scheduled check caches the full results and a timestamp. + * Registers a controlled set of direct Site Health tests via `site_status_tests`. * - * The cached `health-check-site-status-result` transient must contain the - * aggregate counts, the complete (unreduced) test results, and the time the - * results were collected, so consumers can read the detailed Site Health - * status without re-running the tests. + * @param array $direct Map of result arrays to return, keyed by test name. + * @return Closure The filter callback, so the caller can remove it. + */ + private function use_fake_site_status_tests( array $direct ): Closure { + $tests = array( + 'direct' => array(), + 'async' => array(), + ); + + foreach ( $direct as $name => $result ) { + $tests['direct'][ $name ] = array( + 'label' => $name, + 'test' => static function () use ( $result ) { + return $result; + }, + ); + } + + $filter = static function () use ( $tests ) { + return $tests; + }; + + add_filter( 'site_status_tests', $filter ); + + return $filter; + } + + /** + * Seeds the detailed Site Health results cache. + * + * @param array $results Map of result arrays keyed by test name. + * @param int $time Timestamp to store for the cache and each result. + */ + private function seed_site_status_detail( array $results, int $time ): void { + foreach ( $results as $test => $result ) { + $results[ $test ]['timestamp'] = $time; + } + + set_transient( + WP_Site_Health::STATUS_DETAIL_TRANSIENT, + wp_json_encode( + array( + 'results' => $results, + 'timestamp' => $time, + ) + ), + MONTH_IN_SECONDS + ); + } + + /** + * The scheduled check stores only the aggregate counts in the autoloaded transient + * and caches the full results separately. * * @ticket 65232 * * @covers ::wp_cron_scheduled_check + * @covers ::get_site_status_detail + * @covers ::set_site_status_counts + * @covers ::update_site_status_detail */ - public function test_wp_cron_scheduled_check_caches_full_results(): void { - $tests = array( - 'direct' => array( + public function test_scheduled_check_stores_counts_and_detail_separately(): void { + $filter = $this->use_fake_site_status_tests( + array( 'fake_critical' => array( - 'label' => 'Fake critical', - 'test' => static function () { - return array( - 'label' => 'Critical label', - 'status' => 'critical', - 'badge' => array( - 'label' => 'Security', - 'color' => 'red', - ), - 'description' => '

Critical description.

', - 'actions' => '', - 'test' => 'fake_critical', - ); - }, + 'test' => 'fake_critical', + 'label' => 'Critical label', + 'status' => 'critical', + 'badge' => array( + 'label' => 'Security', + 'color' => 'red', + ), + 'description' => '

Critical description.

', + 'actions' => '', ), 'fake_recommended' => array( - 'label' => 'Fake recommended', - 'test' => static function () { - return array( - 'label' => 'Recommended label', - 'status' => 'recommended', - 'description' => '

Recommended description.

', - 'test' => 'fake_recommended', - ); - }, + 'test' => 'fake_recommended', + 'label' => 'Recommended label', + 'status' => 'recommended', + 'description' => '

Recommended description.

', ), 'fake_good' => array( - 'label' => 'Fake good', - 'test' => static function () { - return array( - 'label' => 'Good label', - 'status' => 'good', - 'description' => '

Good description.

', - 'test' => 'fake_good', - ); - }, + 'test' => 'fake_good', + 'label' => 'Good label', + 'status' => 'good', + 'description' => '

Good description.

', ), - ), - 'async' => array(), + ) ); - $filter = static function () use ( $tests ) { - return $tests; - }; - - add_filter( 'site_status_tests', $filter ); - - delete_transient( 'health-check-site-status-result' ); + delete_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ); + delete_transient( WP_Site_Health::STATUS_DETAIL_TRANSIENT ); $before = time(); $this->instance->wp_cron_scheduled_check(); @@ -814,52 +845,276 @@ public function test_wp_cron_scheduled_check_caches_full_results(): void { remove_filter( 'site_status_tests', $filter ); - $transient = get_transient( 'health-check-site-status-result' ); + // The counts transient holds only the aggregate counts, so it stays small enough to autoload. + $transient = get_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ); $this->assertIsString( $transient ); - $cached = json_decode( $transient, true ); - - $this->assertIsArray( $cached, 'The cached result should decode to an array.' ); - $this->assertArrayHasKey( 'good', $cached ); - $this->assertArrayHasKey( 'recommended', $cached ); - $this->assertArrayHasKey( 'critical', $cached ); - - // Aggregate counts are preserved at the top level. - $this->assertSame( 1, $cached['good'], 'There should be one good result.' ); - $this->assertSame( 1, $cached['recommended'], 'There should be one recommended result.' ); - $this->assertSame( 1, $cached['critical'], 'There should be one critical result.' ); + $this->assertSame( + array( + 'good' => 1, + 'recommended' => 1, + 'critical' => 1, + ), + json_decode( $transient, true ), + 'The counts transient should contain only the aggregate counts.' + ); - // The full results are cached, including the passing (good) result. - $this->assertArrayHasKey( 'results', $cached, 'The full results should be cached.' ); - $this->assertIsArray( $cached['results'] ); - $this->assertCount( 3, $cached['results'], 'All test results should be cached, not just actionable ones.' ); + // The detailed cache holds every result, including the passing one. + $detail = WP_Site_Health::get_site_status_detail(); + $this->assertArrayHasKey( 'results', $detail ); + $this->assertCount( 3, $detail['results'], 'All results should be cached, not just actionable ones.' ); $results_by_test = array(); - foreach ( $cached['results'] as $result ) { - $this->assertIsArray( $result ); - $this->assertArrayHasKey( 'test', $result ); - $this->assertIsString( $result['test'] ); + foreach ( $detail['results'] as $result ) { $results_by_test[ $result['test'] ] = $result; } $this->assertSame( array( 'fake_critical', 'fake_recommended', 'fake_good' ), - array_keys( $results_by_test ), - 'Every test result should be cached.' + array_keys( $results_by_test ) ); - // The complete result is stored as produced, without stripping HTML. - $this->assertSame( 'critical', $results_by_test['fake_critical']['status'] ); + // Safe HTML in the description is preserved. $this->assertSame( '

Critical description.

', - $results_by_test['fake_critical']['description'], - 'The full result should be cached without reducing or stripping it.' + $results_by_test['fake_critical']['description'] + ); + $this->assertSame( + array( + 'label' => 'Security', + 'color' => 'red', + ), + $results_by_test['fake_critical']['badge'] + ); + + // Each result carries its own collection timestamp. + $this->assertGreaterThanOrEqual( $before, $results_by_test['fake_critical']['timestamp'] ); + $this->assertLessThanOrEqual( $after, $results_by_test['fake_critical']['timestamp'] ); + + // The detail cache exposes counts derived from its own results. + $this->assertSame( + array( + 'good' => 1, + 'recommended' => 1, + 'critical' => 1, + ), + $detail['counts'], + 'Detail counts should be derived from the cached detail results.' ); - $this->assertArrayHasKey( 'badge', $results_by_test['fake_critical'], 'All result fields should be cached.' ); + } + + /** + * An asynchronous test that is unavailable during the scheduled check is cached under + * its own identifier, so the counts and the detailed results stay consistent. + * + * @ticket 65232 + * + * @covers ::wp_cron_scheduled_check + */ + public function test_scheduled_check_caches_unavailable_async_test_with_identifier(): void { + // Force the asynchronous remote request to fail so the fallback path runs. + $http = static function () { + return new WP_Error( 'unavailable', 'Service unavailable.' ); + }; + add_filter( 'pre_http_request', $http ); + + $filter = static function () { + return array( + 'direct' => array(), + 'async' => array( + 'my_async' => array( + 'label' => 'My async test', + 'test' => 'https://example.invalid/site-health', + 'has_rest' => true, + ), + ), + ); + }; + add_filter( 'site_status_tests', $filter ); + + delete_transient( WP_Site_Health::STATUS_DETAIL_TRANSIENT ); + + $this->instance->wp_cron_scheduled_check(); + + remove_filter( 'site_status_tests', $filter ); + remove_filter( 'pre_http_request', $http ); + + $detail = WP_Site_Health::get_site_status_detail(); + $results_by_id = array(); + foreach ( $detail['results'] as $result ) { + $results_by_id[ $result['test'] ] = $result; + } - // A timestamp records when the results were collected. - $this->assertArrayHasKey( 'timestamp', $cached, 'A collection timestamp should be cached.' ); - $this->assertIsInt( $cached['timestamp'] ); - $this->assertGreaterThanOrEqual( $before, $cached['timestamp'] ); - $this->assertLessThanOrEqual( $after, $cached['timestamp'] ); + $this->assertArrayHasKey( 'my_async', $results_by_id, 'The unavailable async test should be cached under its identifier.' ); + $this->assertSame( 'recommended', $results_by_id['my_async']['status'] ); + $this->assertSame( 1, $detail['counts']['recommended'], 'The unavailable async test should also be reflected in the detail counts.' ); + } + + /** + * The scheduled check does not overwrite recently cached results, preserving the + * authoritative results collected from the Site Health screen (including async tests). + * + * @ticket 65232 + * + * @covers ::wp_cron_scheduled_check + * @covers ::update_site_status_detail + */ + public function test_scheduled_check_preserves_fresh_results(): void { + $this->seed_site_status_detail( + array( + 'fake_async' => array( + 'test' => 'fake_async', + 'label' => 'Async', + 'status' => 'good', + 'description' => '

From the browser.

', + ), + ), + time() + ); + + $filter = $this->use_fake_site_status_tests( + array( + 'fake_async' => array( + 'test' => 'fake_async', + 'label' => 'Async', + 'status' => 'critical', + 'description' => '

From cron.

', + ), + ) + ); + + $this->instance->wp_cron_scheduled_check(); + + remove_filter( 'site_status_tests', $filter ); + + $detail = WP_Site_Health::get_site_status_detail(); + $this->assertCount( 1, $detail['results'] ); + $this->assertSame( 'good', $detail['results'][0]['status'], 'The fresh browser result should be preserved.' ); + $this->assertSame( '

From the browser.

', $detail['results'][0]['description'] ); + } + + /** + * The scheduled check refreshes results that are older than the cron cadence. + * + * @ticket 65232 + * + * @covers ::wp_cron_scheduled_check + * @covers ::update_site_status_detail + */ + public function test_scheduled_check_refreshes_stale_results(): void { + $this->seed_site_status_detail( + array( + 'fake_test' => array( + 'test' => 'fake_test', + 'label' => 'Test', + 'status' => 'good', + 'description' => '

Stale.

', + ), + ), + time() - 2 * WEEK_IN_SECONDS + ); + + $filter = $this->use_fake_site_status_tests( + array( + 'fake_test' => array( + 'test' => 'fake_test', + 'label' => 'Test', + 'status' => 'critical', + 'description' => '

Refreshed by cron.

', + ), + ) + ); + + $this->instance->wp_cron_scheduled_check(); + + remove_filter( 'site_status_tests', $filter ); + + $detail = WP_Site_Health::get_site_status_detail(); + $this->assertCount( 1, $detail['results'] ); + $this->assertSame( 'critical', $detail['results'][0]['status'], 'A stale result should be refreshed by cron.' ); + $this->assertSame( '

Refreshed by cron.

', $detail['results'][0]['description'] ); + } + + /** + * Results that have not been refreshed within a month are dropped. + * + * @ticket 65232 + * + * @covers ::update_site_status_detail + */ + public function test_update_site_status_detail_drops_stale_entries(): void { + $now = time(); + + set_transient( + WP_Site_Health::STATUS_DETAIL_TRANSIENT, + wp_json_encode( + array( + 'results' => array( + 'recent' => array( + 'test' => 'recent', + 'status' => 'good', + 'timestamp' => $now, + ), + 'old' => array( + 'test' => 'old', + 'status' => 'good', + 'timestamp' => $now - 2 * MONTH_IN_SECONDS, + ), + ), + 'timestamp' => $now, + ) + ), + MONTH_IN_SECONDS + ); + + // Update with nothing new; the stale-entry pruning still runs. + WP_Site_Health::update_site_status_detail( array(), true ); + + $detail = WP_Site_Health::get_site_status_detail(); + $this->assertCount( 1, $detail['results'] ); + $this->assertSame( 'recent', $detail['results'][0]['test'] ); + } + + /** + * The counts accessor returns zeroed counts when nothing is cached. + * + * @ticket 65232 + * + * @covers ::get_site_status_counts + */ + public function test_get_site_status_counts_defaults_when_uncached(): void { + delete_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ); + + $this->assertSame( + array( + 'good' => 0, + 'recommended' => 0, + 'critical' => 0, + ), + WP_Site_Health::get_site_status_counts() + ); + } + + /** + * The detail accessor returns an empty array when nothing is cached. + * + * @ticket 65232 + * + * @covers ::get_site_status_detail + */ + public function test_get_site_status_detail_empty_when_uncached(): void { + delete_transient( WP_Site_Health::STATUS_DETAIL_TRANSIENT ); + + $this->assertSame( + array( + 'results' => array(), + 'counts' => array( + 'good' => 0, + 'recommended' => 0, + 'critical' => 0, + ), + 'timestamp' => 0, + ), + WP_Site_Health::get_site_status_detail() + ); } } diff --git a/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php b/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php index 4fc24ed5216a8..105469efadee6 100644 --- a/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php +++ b/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php @@ -4,9 +4,10 @@ * Admin Ajax functions to be tested. */ require_once ABSPATH . 'wp-admin/includes/ajax-actions.php'; +require_once ABSPATH . 'wp-admin/includes/class-wp-site-health.php'; /** - * Tests the Ajax handler that persists Site Health check result counts. + * Tests the Ajax handler that persists Site Health check results. * * @package WordPress * @subpackage UnitTests @@ -20,9 +21,9 @@ class Tests_Ajax_wpAjaxHealthCheckSiteStatusResult extends WP_Ajax_UnitTestCase { /** - * The Site Health result transient and nonce action name. + * The nonce action used by the Site Health result Ajax request. */ - const TRANSIENT = 'health-check-site-status-result'; + const ACTION = 'health-check-site-status-result'; /** * User ID granted super admin privileges during a multisite test. @@ -36,7 +37,7 @@ public function set_up(): void { parent::set_up(); // This Ajax action is not part of the core actions registered by the base test case. - add_action( 'wp_ajax_' . self::TRANSIENT, 'wp_ajax_health_check_site_status_result', 1 ); + add_action( 'wp_ajax_' . self::ACTION, 'wp_ajax_health_check_site_status_result', 1 ); } /** @@ -72,7 +73,7 @@ private function dispatch_result_request(): array { $this->_last_response = ''; try { - $this->_handleAjax( self::TRANSIENT ); + $this->_handleAjax( self::ACTION ); } catch ( WPAjaxDieContinueException $e ) { unset( $e ); } @@ -83,75 +84,178 @@ private function dispatch_result_request(): array { } /** - * The browser only refreshes the counts, so the full results and timestamp - * cached by the scheduled check must be preserved. + * Returns the detailed cached results keyed by test name. + * + * @return array + */ + private function get_detail_results_by_test(): array { + $detail = WP_Site_Health::get_site_status_detail(); + + if ( empty( $detail['results'] ) ) { + return array(); + } + + $by_test = array(); + foreach ( $detail['results'] as $result ) { + $by_test[ $result['test'] ] = $result; + } + + return $by_test; + } + + /** + * The aggregate counts are cached on their own, while the full results submitted by + * the Site Health screen are sanitized and cached separately. * * @ticket 65232 */ - public function test_refreshing_counts_preserves_cached_results_and_timestamp(): void { - $timestamp = 1715714399; - $results = array( - array( - 'test' => 'fake_critical', - 'label' => 'Critical label', - 'status' => 'critical', - 'description' => '

Critical description.

', - ), - ); + public function test_posting_counts_and_results_caches_them_separately(): void { + delete_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ); + delete_transient( WP_Site_Health::STATUS_DETAIL_TRANSIENT ); - set_transient( - self::TRANSIENT, + $this->set_user_with_site_health_capability(); + $_POST['_wpnonce'] = wp_create_nonce( self::ACTION ); + $_POST['counts'] = array( + 'good' => 5, + 'recommended' => 1, + 'critical' => 2, + ); + $_POST['results'] = wp_slash( wp_json_encode( array( - 'good' => 5, - 'recommended' => 0, - 'critical' => 1, - 'results' => $results, - 'timestamp' => $timestamp, + array( + 'test' => 'a', + 'label' => 'A', + 'status' => 'critical', + 'description' => '

Bad

', + 'actions' => '', + ), + array( + 'test' => 'b', + 'label' => 'B', + 'status' => 'recommended', + 'description' => '

B

', + ), + array( + 'test' => 'c', + 'label' => 'C', + 'status' => 'good', + 'description' => '

C

', + ), + array( + // An unrecognized status is dropped. + 'test' => 'd', + 'label' => 'D', + 'status' => 'bogus', + 'description' => '

D

', + ), ) ) ); + $response = $this->dispatch_result_request(); + + $this->assertTrue( $response['success'] ); + + // The counts transient holds only the aggregate counts. + $transient = get_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ); + $this->assertIsString( $transient ); + $this->assertSame( + array( + 'good' => 5, + 'recommended' => 1, + 'critical' => 2, + ), + json_decode( $transient, true ) + ); + + // Only results with a recognized status are cached. + $results = $this->get_detail_results_by_test(); + $this->assertSame( array( 'a', 'b', 'c' ), array_keys( $results ) ); + + // Disallowed HTML is stripped from the cached description. + $this->assertStringNotContainsString( '', - 'actions' => '', + 'a' => array( + 'status' => 'critical', ), - array( - 'test' => 'b', - 'label' => 'B', - 'status' => 'recommended', - 'description' => '

B

', + 'b' => array( + 'status' => 'recommended', ), - array( - 'test' => 'c', - 'label' => 'C', - 'status' => 'good', - 'description' => '

C

', + 'c' => array( + 'status' => 'good', ), - array( - // An unrecognized status is dropped. - 'test' => 'd', - 'label' => 'D', - 'status' => 'bogus', - 'description' => '

D

', + 'd' => array( + // An unrecognized status is rejected. + 'status' => 'bogus', ), ) ) ); $response = $this->dispatch_result_request(); + $this->assertFalse( $response['success'] ); + $_POST['results'] = wp_slash( + wp_json_encode( + array( + 'a' => array( + 'status' => 'critical', + ), + 'b' => array( + 'status' => 'recommended', + ), + 'c' => array( + 'status' => 'good', + ), + ) + ) + ); + + $response = $this->dispatch_result_request(); $this->assertTrue( $response['success'] ); // The counts transient holds only the aggregate counts. @@ -154,8 +159,8 @@ public function test_posting_counts_and_results_caches_them_separately(): void { $this->assertSame( array( 'a', 'b', 'c' ), array_keys( $results ) ); // Only locale-independent fields are cached: the test name, status, and timestamp. - $this->assertSame( - array( 'test', 'status', 'timestamp' ), + $this->assertSameSets( + array( 'status', 'timestamp' ), array_keys( $results['a'] ), 'No translated or HTML fields should be cached.' ); @@ -190,9 +195,7 @@ public function test_posting_results_only_updates_detail_without_counts(): void $_POST['results'] = wp_slash( wp_json_encode( array( - array( - 'test' => 'a', - 'label' => 'A', + 'a' => array( 'status' => 'critical', ), ) @@ -224,11 +227,11 @@ public function test_posting_counts_only_leaves_detail_intact(): void { array( 'results' => array( 'seeded' => array( - 'test' => 'seeded', 'status' => 'good', 'timestamp' => $now, ), ), + 'counts' => array(), 'timestamp' => $now, ) ), From 518531fa11ea3c76b33acc2fce1d8d7599e390dc Mon Sep 17 00:00:00 2001 From: Grzegorz Ziolkowski Date: Fri, 24 Jul 2026 08:06:10 +0200 Subject: [PATCH 29/51] Site Health: Compute detailed status counts at runtime --- .../includes/class-wp-site-health.php | 77 +++++++++++-------- tests/phpunit/tests/admin/wpSiteHealth.php | 37 ++++++++- .../wpAjaxHealthCheckSiteStatusResult.php | 1 - 3 files changed, 77 insertions(+), 38 deletions(-) diff --git a/src/wp-admin/includes/class-wp-site-health.php b/src/wp-admin/includes/class-wp-site-health.php index a9796cbfd5fb9..a7e3e82b29f0f 100644 --- a/src/wp-admin/includes/class-wp-site-health.php +++ b/src/wp-admin/includes/class-wp-site-health.php @@ -21,7 +21,11 @@ * } * @phpstan-type Stored_Test_Results array{ * results: array, - * counts: Test_Status_Counts, // TODO: This is redundant. + * timestamp: non-negative-int, + * } + * @phpstan-type Site_Status_Detail array{ + * results: array, + * counts: Test_Status_Counts, * timestamp: non-negative-int, * } */ @@ -49,6 +53,24 @@ class WP_Site_Health { private const VALID_STATUS_VALUES = array( 'good', 'recommended', 'critical' ); + private const STATUS_COUNTS_SCHEMA = array( + 'type' => 'object', + 'properties' => array( + 'good' => array( + 'type' => 'integer', + 'minimum' => 0, + ), + 'recommended' => array( + 'type' => 'integer', + 'minimum' => 0, + ), + 'critical' => array( + 'type' => 'integer', + 'minimum' => 0, + ), + ), + ); + private const STORED_STATUS_SCHEMA = array( 'type' => 'object', 'properties' => array( @@ -70,30 +92,12 @@ class WP_Site_Health { 'additionalProperties' => false, ), ), - // TODO: This counts is redundant. Why store it? It can be computed at runtime from the results. - 'counts' => array( - 'type' => 'object', - 'properties' => array( - 'good' => array( - 'type' => 'integer', - 'minimum' => 0, - ), - 'recommended' => array( - 'type' => 'integer', - 'minimum' => 0, - ), - 'critical' => array( - 'type' => 'integer', - 'minimum' => 0, - ), - ), - ), 'timestamp' => array( 'type' => 'integer', 'minimum' => 1, ), ), - 'required' => array( 'results', 'counts' ), + 'required' => array( 'results' ), ); /** @@ -3588,7 +3592,16 @@ public function wp_cron_scheduled_check() { * @return Test_Status_Counts Aggregate counts. Each value is `0` when no result has been cached. */ public static function get_site_status_counts(): array { - return self::read_status_cache( self::STATUS_RESULT_TRANSIENT )['counts']; + $counts = get_transient( self::STATUS_RESULT_TRANSIENT ); + if ( is_string( $counts ) ) { + $counts = json_decode( $counts, true ); + } + + if ( ! is_array( $counts ) || is_wp_error( rest_validate_value_from_schema( $counts, self::STATUS_COUNTS_SCHEMA ) ) ) { + $counts = array(); + } + + return self::normalize_status_counts( $counts ); } /** @@ -3600,7 +3613,7 @@ public static function get_site_status_counts(): array { * @return true|WP_Error True when the counts were saved, or WP_Error on failure. */ public static function set_site_status_counts( array $counts ) { - $validity = rest_validate_value_from_schema( $counts, self::STORED_STATUS_SCHEMA['properties']['counts'] ); + $validity = rest_validate_value_from_schema( $counts, self::STATUS_COUNTS_SCHEMA ); if ( is_wp_error( $validity ) ) { return $validity; } @@ -3631,10 +3644,16 @@ public static function set_site_status_counts( array $counts ) { * @return array The cached results as a list, aggregate counts derived from those same results, and * the time of the most recent update. `results` is empty, all counts are `0`, and * `timestamp` is `0` when none are cached. - * @phpstan-return Stored_Test_Results + * @phpstan-return Site_Status_Detail */ public static function get_site_status_detail(): array { - return self::read_status_cache( self::STATUS_DETAIL_TRANSIENT ); + $cached = self::read_status_cache( self::STATUS_DETAIL_TRANSIENT ); + + return array( + 'results' => $cached['results'], + 'counts' => self::count_site_status_results( array_values( $cached['results'] ) ), + 'timestamp' => $cached['timestamp'], + ); } /** @@ -3707,8 +3726,6 @@ public static function update_site_status_detail( array $results, bool $includes $stored_value = wp_json_encode( array( 'results' => $cached['results'], - // A counts snapshot derived from the same results, kept for self-describing cache reads. - 'counts' => self::count_site_status_results( array_values( $cached['results'] ) ), 'timestamp' => $now, ) ); @@ -3746,18 +3763,10 @@ private static function read_status_cache( string $transient ): array { if ( true !== $validity ) { $cached = array( 'results' => array(), - 'counts' => array(), 'timestamp' => 0, ); } - foreach ( array_keys( self::STORED_STATUS_SCHEMA['properties']['counts']['properties'] ) as $key ) { - /** @var array{ counts: array, ... } $cached */ - if ( ! isset( $cached['counts'][ $key ] ) ) { - $cached['counts'][ $key ] = 0; - } - } - /** @var Stored_Test_Results $cached */ return $cached; } diff --git a/tests/phpunit/tests/admin/wpSiteHealth.php b/tests/phpunit/tests/admin/wpSiteHealth.php index 3e4601819ab89..59d441642c379 100644 --- a/tests/phpunit/tests/admin/wpSiteHealth.php +++ b/tests/phpunit/tests/admin/wpSiteHealth.php @@ -846,18 +846,31 @@ public function test_scheduled_check_stores_counts_and_detail_separately(): void remove_filter( 'site_status_tests', $filter ); // The counts transient holds only the aggregate counts, so it stays small enough to autoload. - $transient = get_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ); - $this->assertIsString( $transient ); + $counts_transient = get_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ); + $this->assertIsString( $counts_transient ); + $stored_counts = json_decode( $counts_transient, true ); + $this->assertIsArray( $stored_counts ); $this->assertSame( array( 'good' => 1, 'recommended' => 1, 'critical' => 1, ), - json_decode( $transient, true ), + $stored_counts, 'The counts transient should contain only the aggregate counts.' ); + // The detail transient stores only results and a timestamp; counts are derived when it is read. + $detail_transient = get_transient( WP_Site_Health::STATUS_DETAIL_TRANSIENT ); + $this->assertIsString( $detail_transient ); + $stored_detail = json_decode( $detail_transient, true ); + $this->assertIsArray( $stored_detail ); + $this->assertSameSets( + array( 'results', 'timestamp' ), + array_keys( $stored_detail ), + 'The detail transient should contain only the results and timestamp.' + ); + // The detailed cache holds every result, including the passing one. $detail = WP_Site_Health::get_site_status_detail(); $this->assertArrayHasKey( 'results', $detail ); @@ -1071,6 +1084,24 @@ public function test_get_site_status_counts_defaults_when_uncached(): void { ); } + /** + * The counts accessor returns the cached aggregate counts. + * + * @ticket 65232 + * + * @covers ::get_site_status_counts + */ + public function test_get_site_status_counts_returns_cached_counts(): void { + $counts = array( + 'good' => 3, + 'recommended' => 2, + 'critical' => 1, + ); + set_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT, wp_json_encode( $counts ) ); + + $this->assertSame( $counts, WP_Site_Health::get_site_status_counts() ); + } + /** * The detail accessor returns an empty array when nothing is cached. * diff --git a/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php b/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php index 7b6d881450980..b51b96d8ff483 100644 --- a/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php +++ b/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php @@ -231,7 +231,6 @@ public function test_posting_counts_only_leaves_detail_intact(): void { 'timestamp' => $now, ), ), - 'counts' => array(), 'timestamp' => $now, ) ), From 1875dd48a8c434ae35aeef74aeb906f6e75bc5b1 Mon Sep 17 00:00:00 2001 From: Grzegorz Ziolkowski Date: Fri, 24 Jul 2026 08:30:09 +0200 Subject: [PATCH 30/51] Site Health: Specialize the detailed status cache reader --- src/wp-admin/includes/class-wp-site-health.php | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/src/wp-admin/includes/class-wp-site-health.php b/src/wp-admin/includes/class-wp-site-health.php index a7e3e82b29f0f..fc1c30807b24d 100644 --- a/src/wp-admin/includes/class-wp-site-health.php +++ b/src/wp-admin/includes/class-wp-site-health.php @@ -3647,7 +3647,7 @@ public static function set_site_status_counts( array $counts ) { * @phpstan-return Site_Status_Detail */ public static function get_site_status_detail(): array { - $cached = self::read_status_cache( self::STATUS_DETAIL_TRANSIENT ); + $cached = self::read_site_status_detail_cache(); return array( 'results' => $cached['results'], @@ -3678,7 +3678,7 @@ public static function get_site_status_detail(): array { public static function update_site_status_detail( array $results, bool $includes_async ) { $now = time(); - $cached = self::read_status_cache( self::STATUS_DETAIL_TRANSIENT ); + $cached = self::read_site_status_detail_cache(); foreach ( $results as $test => $result ) { $test = sanitize_text_field( $test ); @@ -3740,17 +3740,15 @@ public static function update_site_status_detail( array $results, bool $includes } /** - * Reads and decodes a cached Site Health transient. + * Reads and decodes the cached detailed Site Health test results. * * @since 7.1.0 - * @todo Why is the $transient a parameter for this function? It can read the constant directly. * - * @param string $transient Transient name. * @return array The stored status. * @phpstan-return Stored_Test_Results */ - private static function read_status_cache( string $transient ): array { - $cached = get_transient( $transient ); + private static function read_site_status_detail_cache(): array { + $cached = get_transient( self::STATUS_DETAIL_TRANSIENT ); if ( is_string( $cached ) ) { $cached = json_decode( $cached, true ); } From 728c2270689473640f124f1986cf482288696f84 Mon Sep 17 00:00:00 2001 From: Grzegorz Ziolkowski Date: Fri, 24 Jul 2026 09:22:26 +0200 Subject: [PATCH 31/51] Site Health: Fix storing test results in JavaScript --- src/js/_enqueues/admin/site-health.js | 2 +- tests/qunit/index.html | 20 ++++++++++++++++++++ tests/qunit/wp-admin/js/site-health.js | 24 ++++++++++++++++++++++++ 3 files changed, 45 insertions(+), 1 deletion(-) create mode 100644 tests/qunit/wp-admin/js/site-health.js diff --git a/src/js/_enqueues/admin/site-health.js b/src/js/_enqueues/admin/site-health.js index 88d75f9306d86..b133025d51e77 100644 --- a/src/js/_enqueues/admin/site-health.js +++ b/src/js/_enqueues/admin/site-health.js @@ -170,7 +170,7 @@ jQuery( function( $ ) { * include the asynchronous tests that only run in the browser. Labels are left * out on purpose, as they are translated and the cache is shared across locales. */ - SiteHealth.site_status[ issue.test ] = { + SiteHealth.site_status.results[ issue.test ] = { status: issue.status }; diff --git a/tests/qunit/index.html b/tests/qunit/index.html index f9033a776151c..b49ce973f6822 100644 --- a/tests/qunit/index.html +++ b/tests/qunit/index.html @@ -89,9 +89,11 @@ + + @@ -134,6 +136,23 @@ + + @@ -186,6 +205,7 @@ + diff --git a/tests/qunit/wp-admin/js/site-health.js b/tests/qunit/wp-admin/js/site-health.js new file mode 100644 index 0000000000000..2e9d7a114b668 --- /dev/null +++ b/tests/qunit/wp-admin/js/site-health.js @@ -0,0 +1,24 @@ +/* global SiteHealth */ + +QUnit.module( 'Site Health', function() { + QUnit.test( 'updates state after running direct tests', function( assert ) { + assert.deepEqual( + SiteHealth.site_status.results, + { + direct_test: { + status: 'good' + } + }, + 'The test results contain locale-independent data.' + ); + assert.deepEqual( + SiteHealth.site_status.issues, + { + critical: 0, + good: 1, + recommended: 0 + }, + 'The issue counts reflect the test results.' + ); + } ); +} ); From c4a295dce11d1d57d547a5eaa671c53747947f53 Mon Sep 17 00:00:00 2001 From: Grzegorz Ziolkowski Date: Fri, 24 Jul 2026 10:04:08 +0200 Subject: [PATCH 32/51] Site Health: Clarify detailed result documentation --- .../includes/class-wp-site-health.php | 24 ++++++++++--------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/src/wp-admin/includes/class-wp-site-health.php b/src/wp-admin/includes/class-wp-site-health.php index fc1c30807b24d..bcfece6026d9d 100644 --- a/src/wp-admin/includes/class-wp-site-health.php +++ b/src/wp-admin/includes/class-wp-site-health.php @@ -3641,9 +3641,9 @@ public static function set_site_status_counts( array $counts ) { * @since 7.1.0 * @todo This method is now not used. * - * @return array The cached results as a list, aggregate counts derived from those same results, and - * the time of the most recent update. `results` is empty, all counts are `0`, and - * `timestamp` is `0` when none are cached. + * @return array The cached results as a map keyed by test name, aggregate counts derived + * from those same results, and the time of the most recent update. `results` + * is empty, all counts are `0`, and `timestamp` is `0` when none are cached. * @phpstan-return Site_Status_Detail */ public static function get_site_status_detail(): array { @@ -3665,14 +3665,16 @@ public static function get_site_status_detail(): array { * * @since 7.1.0 * - * @param mixed[] $results List of raw Site Health test result arrays. - * @param bool $includes_async Whether the results include the JavaScript-only - * asynchronous tests. The Site Health screen passes `true` - * because it collects those tests in the browser, so its - * entries take precedence over existing cached ones. The - * scheduled check passes `false` since it cannot run the - * asynchronous tests, so it only fills in missing or stale - * entries without discarding fresher results from the screen. + * @param array $results Map of raw Site Health test result arrays, + * keyed by test name. + * @param bool $includes_async Whether the results include the JavaScript-only + * asynchronous tests. The Site Health screen passes + * `true` because it collects those tests in the browser, + * so its entries take precedence over existing cached + * ones. The scheduled check passes `false` since it cannot + * run the asynchronous tests, so it only fills in missing + * or stale entries without discarding fresher results from + * the screen. * @return true|WP_Error True on success, WP_Error on failure. */ public static function update_site_status_detail( array $results, bool $includes_async ) { From 1862d0459ada7c4ab089144cfeb6e77f6a6402d6 Mon Sep 17 00:00:00 2001 From: Grzegorz Ziolkowski Date: Fri, 24 Jul 2026 11:18:24 +0200 Subject: [PATCH 33/51] Site Health: Validate scheduled test results --- .../includes/class-wp-site-health.php | 38 +++++------ tests/phpunit/tests/admin/wpSiteHealth.php | 67 +++++++++++++++++++ 2 files changed, 82 insertions(+), 23 deletions(-) diff --git a/src/wp-admin/includes/class-wp-site-health.php b/src/wp-admin/includes/class-wp-site-health.php index bcfece6026d9d..62fa9ce25c794 100644 --- a/src/wp-admin/includes/class-wp-site-health.php +++ b/src/wp-admin/includes/class-wp-site-health.php @@ -3460,12 +3460,6 @@ public function wp_cron_scheduled_check() { $results = array(); - $site_status = array( - 'good' => 0, - 'recommended' => 0, - 'critical' => 0, - ); - // Don't run https test on development environments. if ( $this->is_development_environment() ) { unset( $tests['async']['https_status'] ); @@ -3547,23 +3541,29 @@ public function wp_cron_scheduled_check() { } } + $results_to_count = array(); + $results_to_store = array(); foreach ( $results as $result ) { + // Filters may return unexpected values, so require the fields used by both caches. if ( ! is_array( $result ) ) { continue; } - $status = $result['status'] ?? ''; - - if ( 'critical' === $status ) { - ++$site_status['critical']; - } elseif ( 'recommended' === $status ) { - ++$site_status['recommended']; - } else { - ++$site_status['good']; + $test = $result['test'] ?? null; + $status = $result['status'] ?? null; + if ( + ! is_string( $test ) + || '' === sanitize_text_field( $test ) + || ! in_array( $status, self::VALID_STATUS_VALUES, true ) + ) { + continue; } + + $results_to_count[] = array( 'status' => $status ); + $results_to_store[ $test ] = array( 'status' => $status ); } - self::set_site_status_counts( $site_status ); + self::set_site_status_counts( self::count_site_status_results( $results_to_count ) ); /* * Cache the full results separately, keyed by test, so consumers can read the @@ -3573,14 +3573,6 @@ public function wp_cron_scheduled_check() { * entries so it does not discard fresher results collected from the Site Health * screen, which also include the asynchronous tests that require JavaScript to run. */ - $results_to_store = array(); - foreach ( $results as $result ) { - $test = $result['test'] ?? null; - if ( is_string( $test ) ) { - unset( $result['test'] ); - $results_to_store[ $test ] = wp_array_slice_assoc( $result, array( 'status', 'timestamp' ) ); - } - } self::update_site_status_detail( $results_to_store, false ); } diff --git a/tests/phpunit/tests/admin/wpSiteHealth.php b/tests/phpunit/tests/admin/wpSiteHealth.php index 59d441642c379..2b6057c57aa67 100644 --- a/tests/phpunit/tests/admin/wpSiteHealth.php +++ b/tests/phpunit/tests/admin/wpSiteHealth.php @@ -907,6 +907,73 @@ public function test_scheduled_check_stores_counts_and_detail_separately(): void ); } + /** + * The scheduled check ignores invalid results returned by the result filter, + * allowing valid results from other tests to be counted and cached. + * + * @ticket 65232 + * + * @covers ::wp_cron_scheduled_check + */ + public function test_scheduled_check_uses_only_valid_filtered_results(): void { + $invalid_results = array( + 'non_array_result' => new WP_Error( 'invalid_result' ), + 'missing_test' => array( 'status' => 'good' ), + 'empty_test' => array( + 'test' => '', + 'status' => 'good', + ), + 'invalid_test' => array( + 'test' => array(), + 'status' => 'good', + ), + 'missing_status' => array( 'test' => 'missing_status' ), + 'invalid_status' => array( + 'test' => 'invalid_status', + 'status' => 'invalid', + ), + ); + $test_results = array(); + foreach ( array_merge( array_keys( $invalid_results ), array( 'valid_result' ) ) as $test ) { + $test_results[ $test ] = array( + 'test' => $test, + 'status' => 'good', + ); + } + + $tests_filter = $this->use_fake_site_status_tests( $test_results ); + $result_filter = static function ( $result ) use ( $invalid_results ) { + if ( is_array( $result ) && isset( $invalid_results[ $result['test'] ] ) ) { + return $invalid_results[ $result['test'] ]; + } + + return $result; + }; + add_filter( 'site_status_test_result', $result_filter ); + + delete_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ); + delete_transient( WP_Site_Health::STATUS_DETAIL_TRANSIENT ); + + try { + $this->instance->wp_cron_scheduled_check(); + } finally { + remove_filter( 'site_status_test_result', $result_filter ); + remove_filter( 'site_status_tests', $tests_filter ); + } + + $detail = WP_Site_Health::get_site_status_detail(); + $this->assertSame( array( 'valid_result' ), array_keys( $detail['results'] ) ); + $this->assertSame( + array( + 'good' => 1, + 'recommended' => 0, + 'critical' => 0, + ), + $detail['counts'] + ); + $this->assertSame( $detail['counts'], WP_Site_Health::get_site_status_counts() ); + } + /** * An asynchronous test that is unavailable during the scheduled check is cached under * its own identifier, so the counts and the detailed results stay consistent. From 295432253c65b1cf06110122a6f47293d30e6116 Mon Sep 17 00:00:00 2001 From: Grzegorz Ziolkowski Date: Fri, 24 Jul 2026 11:37:27 +0200 Subject: [PATCH 34/51] Site Health: Compare detail cache with correct transient --- src/wp-admin/includes/class-wp-site-health.php | 2 +- tests/phpunit/tests/admin/wpSiteHealth.php | 14 ++++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/wp-admin/includes/class-wp-site-health.php b/src/wp-admin/includes/class-wp-site-health.php index 62fa9ce25c794..c40768c509c91 100644 --- a/src/wp-admin/includes/class-wp-site-health.php +++ b/src/wp-admin/includes/class-wp-site-health.php @@ -3723,7 +3723,7 @@ public static function update_site_status_detail( array $results, bool $includes 'timestamp' => $now, ) ); - if ( get_transient( self::STATUS_RESULT_TRANSIENT ) === $stored_value ) { + if ( get_transient( self::STATUS_DETAIL_TRANSIENT ) === $stored_value ) { return true; } diff --git a/tests/phpunit/tests/admin/wpSiteHealth.php b/tests/phpunit/tests/admin/wpSiteHealth.php index 2b6057c57aa67..b43d255f7b125 100644 --- a/tests/phpunit/tests/admin/wpSiteHealth.php +++ b/tests/phpunit/tests/admin/wpSiteHealth.php @@ -839,12 +839,26 @@ public function test_scheduled_check_stores_counts_and_detail_separately(): void delete_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ); delete_transient( WP_Site_Health::STATUS_DETAIL_TRANSIENT ); + $counts_reads_before = did_filter( 'pre_transient_' . WP_Site_Health::STATUS_RESULT_TRANSIENT ); + $detail_reads_before = did_filter( 'pre_transient_' . WP_Site_Health::STATUS_DETAIL_TRANSIENT ); + $before = time(); $this->instance->wp_cron_scheduled_check(); $after = time(); remove_filter( 'site_status_tests', $filter ); + $this->assertSame( + 1, + did_filter( 'pre_transient_' . WP_Site_Health::STATUS_RESULT_TRANSIENT ) - $counts_reads_before, + 'The counts transient should be read once during the scheduled check.' + ); + $this->assertSame( + 2, + did_filter( 'pre_transient_' . WP_Site_Health::STATUS_DETAIL_TRANSIENT ) - $detail_reads_before, + 'The detail transient should be read twice during the scheduled check.' + ); + // The counts transient holds only the aggregate counts, so it stays small enough to autoload. $counts_transient = get_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ); $this->assertIsString( $counts_transient ); From 661e87e08c9ac065afdd4dad376dea0f9ce64c6b Mon Sep 17 00:00:00 2001 From: Grzegorz Ziolkowski Date: Fri, 24 Jul 2026 11:41:06 +0200 Subject: [PATCH 35/51] Site Health: Ignore results without test identifiers --- src/js/_enqueues/admin/site-health.js | 5 ----- tests/qunit/index.html | 5 +++++ tests/qunit/wp-admin/js/site-health.js | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/js/_enqueues/admin/site-health.js b/src/js/_enqueues/admin/site-health.js index b133025d51e77..1641a77b8044e 100644 --- a/src/js/_enqueues/admin/site-health.js +++ b/src/js/_enqueues/admin/site-health.js @@ -160,11 +160,6 @@ jQuery( function( $ ) { count = SiteHealth.site_status.issues[ issue.status ]; - // If no test name is supplied, append a placeholder for markup references. - if ( typeof issue.test === 'undefined' ) { - issue.test = issue.status + count; - } - /* * Collect the test name and status so they can be cached server-side. These * include the asynchronous tests that only run in the browser. Labels are left diff --git a/tests/qunit/index.html b/tests/qunit/index.html index b49ce973f6822..16c0275606fe7 100644 --- a/tests/qunit/index.html +++ b/tests/qunit/index.html @@ -146,6 +146,11 @@ label: 'A test label', status: 'good', test: 'direct_test' + }, + { + description: 'An invalid test description.', + label: 'An invalid test without an identifier', + status: 'critical' } ], results: {} diff --git a/tests/qunit/wp-admin/js/site-health.js b/tests/qunit/wp-admin/js/site-health.js index 2e9d7a114b668..8d3c17d8ec9f3 100644 --- a/tests/qunit/wp-admin/js/site-health.js +++ b/tests/qunit/wp-admin/js/site-health.js @@ -1,7 +1,7 @@ /* global SiteHealth */ QUnit.module( 'Site Health', function() { - QUnit.test( 'updates state after running direct tests', function( assert ) { + QUnit.test( 'updates state only for valid direct tests', function( assert ) { assert.deepEqual( SiteHealth.site_status.results, { From 58079e3c4f162ba3002d2bb2d5be4f25698b6b8d Mon Sep 17 00:00:00 2001 From: Grzegorz Ziolkowski Date: Fri, 24 Jul 2026 11:45:23 +0200 Subject: [PATCH 36/51] Site Health: Clarify detail result validation --- .../includes/class-wp-site-health.php | 3 +-- tests/phpunit/tests/admin/wpSiteHealth.php | 19 ++++++++++++++++--- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/src/wp-admin/includes/class-wp-site-health.php b/src/wp-admin/includes/class-wp-site-health.php index c40768c509c91..e652258f020cd 100644 --- a/src/wp-admin/includes/class-wp-site-health.php +++ b/src/wp-admin/includes/class-wp-site-health.php @@ -3680,9 +3680,8 @@ public static function update_site_status_detail( array $results, bool $includes return new WP_Error( 'invalid_test' ); } - // TODO: Return as error. $validity = rest_validate_value_from_schema( $result, self::STORED_STATUS_SCHEMA['properties']['results']['additionalProperties'] ); - if ( true !== $validity ) { + if ( is_wp_error( $validity ) ) { return $validity; } /** @var Stored_Test_Result $result */ diff --git a/tests/phpunit/tests/admin/wpSiteHealth.php b/tests/phpunit/tests/admin/wpSiteHealth.php index b43d255f7b125..d99bdba426f08 100644 --- a/tests/phpunit/tests/admin/wpSiteHealth.php +++ b/tests/phpunit/tests/admin/wpSiteHealth.php @@ -922,14 +922,15 @@ public function test_scheduled_check_stores_counts_and_detail_separately(): void } /** - * The scheduled check ignores invalid results returned by the result filter, - * allowing valid results from other tests to be counted and cached. + * Only valid results are cached. The scheduled check ignores invalid results + * returned by the result filter, while direct updates return a validation error. * * @ticket 65232 * * @covers ::wp_cron_scheduled_check + * @covers ::update_site_status_detail */ - public function test_scheduled_check_uses_only_valid_filtered_results(): void { + public function test_only_valid_results_are_cached(): void { $invalid_results = array( 'non_array_result' => new WP_Error( 'invalid_result' ), 'missing_test' => array( 'status' => 'good' ), @@ -986,6 +987,18 @@ public function test_scheduled_check_uses_only_valid_filtered_results(): void { $detail['counts'] ); $this->assertSame( $detail['counts'], WP_Site_Health::get_site_status_counts() ); + + $result = WP_Site_Health::update_site_status_detail( + array( + 'invalid_status' => array( + 'status' => 'invalid', + ), + ), + true + ); + + $this->assertWPError( $result ); + $this->assertSame( array( 'valid_result' ), array_keys( WP_Site_Health::get_site_status_detail()['results'] ) ); } /** From 02dfa09bcae326597e775dfddebacea7949107f4 Mon Sep 17 00:00:00 2001 From: Grzegorz Ziolkowski Date: Fri, 24 Jul 2026 12:00:43 +0200 Subject: [PATCH 37/51] Site Health: Return first AJAX save error --- src/wp-admin/includes/ajax-actions.php | 2 +- tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/wp-admin/includes/ajax-actions.php b/src/wp-admin/includes/ajax-actions.php index 84b658ebfa009..a36b9d1ae4a7c 100644 --- a/src/wp-admin/includes/ajax-actions.php +++ b/src/wp-admin/includes/ajax-actions.php @@ -5495,7 +5495,7 @@ function wp_ajax_health_check_site_status_result() { $errors = array_filter( $save_results, 'is_wp_error' ); if ( count( $errors ) > 0 ) { - wp_send_json_error( $errors ); + wp_send_json_error( reset( $errors ) ); } wp_send_json_success(); diff --git a/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php b/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php index b51b96d8ff483..a64520decb187 100644 --- a/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php +++ b/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php @@ -122,6 +122,7 @@ public function test_posting_counts_and_results_caches_them_separately(): void { $response = $this->dispatch_result_request(); $this->assertFalse( $response['success'] ); + $this->assertSame( 'rest_not_in_enum', $response['data'][0]['code'] ); $_POST['results'] = wp_slash( wp_json_encode( From 5bcbea0d832c56041e5e2d187ee32b2205e34148 Mon Sep 17 00:00:00 2001 From: Grzegorz Ziolkowski Date: Fri, 24 Jul 2026 12:16:12 +0200 Subject: [PATCH 38/51] Site Health: Require detailed status timestamps --- .../includes/class-wp-site-health.php | 14 ++--- tests/phpunit/tests/admin/wpSiteHealth.php | 61 +++++++++++++++---- 2 files changed, 56 insertions(+), 19 deletions(-) diff --git a/src/wp-admin/includes/class-wp-site-health.php b/src/wp-admin/includes/class-wp-site-health.php index e652258f020cd..5e49e8b73c6fe 100644 --- a/src/wp-admin/includes/class-wp-site-health.php +++ b/src/wp-admin/includes/class-wp-site-health.php @@ -88,7 +88,7 @@ class WP_Site_Health { 'minimum' => 1, ), ), - 'required' => array( 'status' ), + 'required' => array( 'status', 'timestamp' ), 'additionalProperties' => false, ), ), @@ -97,7 +97,7 @@ class WP_Site_Health { 'minimum' => 1, ), ), - 'required' => array( 'results' ), + 'required' => array( 'results', 'timestamp' ), ); /** @@ -3680,6 +3680,10 @@ public static function update_site_status_detail( array $results, bool $includes return new WP_Error( 'invalid_test' ); } + if ( is_array( $result ) ) { + $result['timestamp'] = $now; + } + $validity = rest_validate_value_from_schema( $result, self::STORED_STATUS_SCHEMA['properties']['results']['additionalProperties'] ); if ( is_wp_error( $validity ) ) { return $validity; @@ -3700,7 +3704,6 @@ public static function update_site_status_detail( array $results, bool $includes continue; } - $result['timestamp'] = $now; $cached['results'][ $test ] = $result; } @@ -3711,11 +3714,6 @@ public static function update_site_status_detail( array $results, bool $includes } } - if ( empty( $cached['results'] ) ) { - delete_transient( self::STATUS_DETAIL_TRANSIENT ); - return true; - } - $stored_value = wp_json_encode( array( 'results' => $cached['results'], diff --git a/tests/phpunit/tests/admin/wpSiteHealth.php b/tests/phpunit/tests/admin/wpSiteHealth.php index d99bdba426f08..3688274a03568 100644 --- a/tests/phpunit/tests/admin/wpSiteHealth.php +++ b/tests/phpunit/tests/admin/wpSiteHealth.php @@ -1197,26 +1197,65 @@ public function test_get_site_status_counts_returns_cached_counts(): void { } /** - * The detail accessor returns an empty array when nothing is cached. + * The detail accessor distinguishes a valid empty cache from a missing or malformed cache. * * @ticket 65232 * * @covers ::get_site_status_detail + * @covers ::update_site_status_detail */ - public function test_get_site_status_detail_empty_when_uncached(): void { + public function test_get_site_status_detail_distinguishes_empty_from_missing_or_malformed_cache(): void { delete_transient( WP_Site_Health::STATUS_DETAIL_TRANSIENT ); - $this->assertSame( - array( - 'results' => array(), - 'counts' => array( - 'good' => 0, - 'recommended' => 0, - 'critical' => 0, + $detail = WP_Site_Health::get_site_status_detail(); + $this->assertSame( array(), $detail['results'] ); + $this->assertSame( 0, $detail['timestamp'] ); + + $before = time(); + $this->assertTrue( WP_Site_Health::update_site_status_detail( array(), true ) ); + $after = time(); + + $detail = WP_Site_Health::get_site_status_detail(); + $this->assertSame( array(), $detail['results'] ); + $this->assertGreaterThanOrEqual( $before, $detail['timestamp'] ); + $this->assertLessThanOrEqual( $after, $detail['timestamp'] ); + $this->assertIsString( get_transient( WP_Site_Health::STATUS_DETAIL_TRANSIENT ) ); + + $now = time(); + set_transient( + WP_Site_Health::STATUS_DETAIL_TRANSIENT, + wp_json_encode( + array( + 'results' => array( + 'missing_timestamp' => array( 'status' => 'good' ), + ), + 'timestamp' => $now, + ) + ), + MONTH_IN_SECONDS + ); + + $detail = WP_Site_Health::get_site_status_detail(); + $this->assertSame( array(), $detail['results'] ); + $this->assertSame( 0, $detail['timestamp'] ); + + set_transient( + WP_Site_Health::STATUS_DETAIL_TRANSIENT, + wp_json_encode( + array( + 'results' => array( + 'missing_cache_timestamp' => array( + 'status' => 'good', + 'timestamp' => $now, + ), + ), ), - 'timestamp' => 0, ), - WP_Site_Health::get_site_status_detail() + MONTH_IN_SECONDS ); + + $detail = WP_Site_Health::get_site_status_detail(); + $this->assertSame( array(), $detail['results'] ); + $this->assertSame( 0, $detail['timestamp'] ); } } From d4824e0d6c962ab99dd0efc985a6814cdad581cc Mon Sep 17 00:00:00 2001 From: Grzegorz Ziolkowski Date: Fri, 24 Jul 2026 12:38:07 +0200 Subject: [PATCH 39/51] Site Health: Store freshest verified results --- src/wp-admin/includes/ajax-actions.php | 2 +- .../includes/class-wp-site-health.php | 50 ++++-------- tests/phpunit/tests/admin/wpSiteHealth.php | 76 ++++++------------- 3 files changed, 40 insertions(+), 88 deletions(-) diff --git a/src/wp-admin/includes/ajax-actions.php b/src/wp-admin/includes/ajax-actions.php index a36b9d1ae4a7c..d8cfcd905a525 100644 --- a/src/wp-admin/includes/ajax-actions.php +++ b/src/wp-admin/includes/ajax-actions.php @@ -5485,7 +5485,7 @@ function wp_ajax_health_check_site_status_result() { $results = json_decode( wp_unslash( $_POST['results'] ), true ); if ( is_array( $results ) ) { - $save_results[] = WP_Site_Health::update_site_status_detail( $results, true ); + $save_results[] = WP_Site_Health::update_site_status_detail( $results ); } } diff --git a/src/wp-admin/includes/class-wp-site-health.php b/src/wp-admin/includes/class-wp-site-health.php index 5e49e8b73c6fe..cdece17627bf6 100644 --- a/src/wp-admin/includes/class-wp-site-health.php +++ b/src/wp-admin/includes/class-wp-site-health.php @@ -3458,7 +3458,8 @@ public function wp_cron_scheduled_check() { $tests = WP_Site_Health::get_tests(); - $results = array(); + $results = array(); + $unavailable_tests = array(); // Don't run https test on development environments. if ( $this->is_development_environment() ) { @@ -3531,8 +3532,9 @@ public function wp_cron_scheduled_check() { if ( is_array( $result ) ) { $results[] = $result; } else { - // Include the test identifier so the result is counted and cached consistently. - $results[] = array( + // Include the test identifier so the unavailable result is counted consistently. + $unavailable_tests[ $test_name ] = true; + $results[] = array( 'test' => $test_name, 'status' => 'recommended', 'label' => __( 'A test is unavailable' ), @@ -3559,8 +3561,10 @@ public function wp_cron_scheduled_check() { continue; } - $results_to_count[] = array( 'status' => $status ); - $results_to_store[ $test ] = array( 'status' => $status ); + $results_to_count[] = array( 'status' => $status ); + if ( ! isset( $unavailable_tests[ $test ] ) ) { + $results_to_store[ $test ] = array( 'status' => $status ); + } } self::set_site_status_counts( self::count_site_status_results( $results_to_count ) ); @@ -3569,11 +3573,11 @@ public function wp_cron_scheduled_check() { * Cache the full results separately, keyed by test, so consumers can read the * detailed Site Health status without re-running the tests. * - * The scheduled check is not authoritative: it refreshes only missing or stale - * entries so it does not discard fresher results collected from the Site Health - * screen, which also include the asynchronous tests that require JavaScript to run. + * Only verified results are included. An unavailable asynchronous test is still + * reflected in the aggregate counts, but does not replace a previously verified + * detailed result. */ - self::update_site_status_detail( $results_to_store, false ); + self::update_site_status_detail( $results_to_store ); } /** @@ -3657,19 +3661,11 @@ public static function get_site_status_detail(): array { * * @since 7.1.0 * - * @param array $results Map of raw Site Health test result arrays, - * keyed by test name. - * @param bool $includes_async Whether the results include the JavaScript-only - * asynchronous tests. The Site Health screen passes - * `true` because it collects those tests in the browser, - * so its entries take precedence over existing cached - * ones. The scheduled check passes `false` since it cannot - * run the asynchronous tests, so it only fills in missing - * or stale entries without discarding fresher results from - * the screen. + * @param array $results Map of raw Site Health test result arrays, + * keyed by test name. * @return true|WP_Error True on success, WP_Error on failure. */ - public static function update_site_status_detail( array $results, bool $includes_async ) { + public static function update_site_status_detail( array $results ) { $now = time(); $cached = self::read_site_status_detail_cache(); @@ -3690,20 +3686,6 @@ public static function update_site_status_detail( array $results, bool $includes } /** @var Stored_Test_Result $result */ - /* - * When the results omit the asynchronous tests, keep a recent existing entry - * rather than overwriting it. This preserves results collected from the Site - * Health screen (including the asynchronous tests) when the scheduled check - * runs afterwards. - */ - if ( - ! $includes_async - && isset( $cached['results'][ $test ] ) - && ( $now - $cached['results'][ $test ]['timestamp'] ) < WEEK_IN_SECONDS - ) { - continue; - } - $cached['results'][ $test ] = $result; } diff --git a/tests/phpunit/tests/admin/wpSiteHealth.php b/tests/phpunit/tests/admin/wpSiteHealth.php index 3688274a03568..de7ccfe3dd3e8 100644 --- a/tests/phpunit/tests/admin/wpSiteHealth.php +++ b/tests/phpunit/tests/admin/wpSiteHealth.php @@ -993,8 +993,7 @@ public function test_only_valid_results_are_cached(): void { 'invalid_status' => array( 'status' => 'invalid', ), - ), - true + ) ); $this->assertWPError( $result ); @@ -1002,14 +1001,24 @@ public function test_only_valid_results_are_cached(): void { } /** - * An asynchronous test that is unavailable during the scheduled check is cached under - * its own identifier, so the counts and the detailed results stay consistent. + * An unavailable asynchronous test is counted but does not replace a previously + * verified detailed result. * * @ticket 65232 * * @covers ::wp_cron_scheduled_check */ - public function test_scheduled_check_caches_unavailable_async_test_with_identifier(): void { + public function test_scheduled_check_preserves_verified_result_when_async_test_is_unavailable(): void { + $cached_at = time() - 2 * WEEK_IN_SECONDS; + $this->seed_site_status_detail( + array( + 'my_async' => array( + 'status' => 'good', + ), + ), + $cached_at + ); + // Force the asynchronous remote request to fail so the fallback path runs. $http = static function () { return new WP_Error( 'unavailable', 'Service unavailable.' ); @@ -1030,8 +1039,6 @@ public function test_scheduled_check_caches_unavailable_async_test_with_identifi }; add_filter( 'site_status_tests', $filter ); - delete_transient( WP_Site_Health::STATUS_DETAIL_TRANSIENT ); - $this->instance->wp_cron_scheduled_check(); remove_filter( 'site_status_tests', $filter ); @@ -1040,21 +1047,21 @@ public function test_scheduled_check_caches_unavailable_async_test_with_identifi $detail = WP_Site_Health::get_site_status_detail(); $results_by_id = $detail['results']; - $this->assertArrayHasKey( 'my_async', $results_by_id, 'The unavailable async test should be cached under its identifier.' ); - $this->assertSame( 'recommended', $results_by_id['my_async']['status'] ); - $this->assertSame( 1, $detail['counts']['recommended'], 'The unavailable async test should also be reflected in the detail counts.' ); + $this->assertArrayHasKey( 'my_async', $results_by_id ); + $this->assertSame( 'good', $results_by_id['my_async']['status'] ); + $this->assertSame( $cached_at, $results_by_id['my_async']['timestamp'] ); + $this->assertSame( 1, WP_Site_Health::get_site_status_counts()['recommended'] ); } /** - * The scheduled check does not overwrite recently cached results, preserving the - * authoritative results collected from the Site Health screen (including async tests). + * The scheduled check overwrites an existing result when it collects a newer verified result. * * @ticket 65232 * * @covers ::wp_cron_scheduled_check * @covers ::update_site_status_detail */ - public function test_scheduled_check_preserves_fresh_results(): void { + public function test_scheduled_check_stores_freshest_verified_result(): void { $this->seed_site_status_detail( array( 'fake_async' => array( @@ -1080,44 +1087,7 @@ public function test_scheduled_check_preserves_fresh_results(): void { $detail = WP_Site_Health::get_site_status_detail(); $this->assertCount( 1, $detail['results'] ); - $this->assertSame( 'good', array_first( $detail['results'] )['status'], 'The fresh browser result should be preserved, not overwritten by cron.' ); - } - - /** - * The scheduled check refreshes results that are older than the cron cadence. - * - * @ticket 65232 - * - * @covers ::wp_cron_scheduled_check - * @covers ::update_site_status_detail - */ - public function test_scheduled_check_refreshes_stale_results(): void { - $this->seed_site_status_detail( - array( - 'fake_test' => array( - 'test' => 'fake_test', - 'status' => 'good', - ), - ), - time() - 2 * WEEK_IN_SECONDS - ); - - $filter = $this->use_fake_site_status_tests( - array( - 'fake_test' => array( - 'test' => 'fake_test', - 'status' => 'critical', - ), - ) - ); - - $this->instance->wp_cron_scheduled_check(); - - remove_filter( 'site_status_tests', $filter ); - - $detail = WP_Site_Health::get_site_status_detail(); - $this->assertCount( 1, $detail['results'] ); - $this->assertSame( 'critical', array_first( $detail['results'] )['status'], 'A stale result should be refreshed by cron.' ); + $this->assertSame( 'critical', array_first( $detail['results'] )['status'] ); } /** @@ -1151,7 +1121,7 @@ public function test_update_site_status_detail_drops_stale_entries(): void { ); // Update with nothing new; the stale-entry pruning still runs. - WP_Site_Health::update_site_status_detail( array(), true ); + WP_Site_Health::update_site_status_detail( array() ); $detail = WP_Site_Health::get_site_status_detail(); $this->assertCount( 1, $detail['results'] ); @@ -1212,7 +1182,7 @@ public function test_get_site_status_detail_distinguishes_empty_from_missing_or_ $this->assertSame( 0, $detail['timestamp'] ); $before = time(); - $this->assertTrue( WP_Site_Health::update_site_status_detail( array(), true ) ); + $this->assertTrue( WP_Site_Health::update_site_status_detail( array() ) ); $after = time(); $detail = WP_Site_Health::get_site_status_detail(); From a7119280769e9756358b7394a8d8861d5b245246 Mon Sep 17 00:00:00 2001 From: Grzegorz Ziolkowski Date: Fri, 24 Jul 2026 12:49:11 +0200 Subject: [PATCH 40/51] Site Health: Add status cache error messages --- src/wp-admin/includes/class-wp-site-health.php | 6 +++--- tests/phpunit/tests/admin/wpSiteHealth.php | 12 ++++++++++++ 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/src/wp-admin/includes/class-wp-site-health.php b/src/wp-admin/includes/class-wp-site-health.php index cdece17627bf6..dfbae38389d6a 100644 --- a/src/wp-admin/includes/class-wp-site-health.php +++ b/src/wp-admin/includes/class-wp-site-health.php @@ -3620,7 +3620,7 @@ public static function set_site_status_counts( array $counts ) { } if ( ! set_transient( self::STATUS_RESULT_TRANSIENT, wp_json_encode( $counts ) ) ) { - return new WP_Error( 'set_transient_error' ); + return new WP_Error( 'set_transient_error', __( 'The Site Health status counts could not be saved.' ) ); } return true; @@ -3673,7 +3673,7 @@ public static function update_site_status_detail( array $results ) { foreach ( $results as $test => $result ) { $test = sanitize_text_field( $test ); if ( '' === $test ) { - return new WP_Error( 'invalid_test' ); + return new WP_Error( 'invalid_test', __( 'The Site Health test identifier is invalid.' ) ); } if ( is_array( $result ) ) { @@ -3707,7 +3707,7 @@ public static function update_site_status_detail( array $results ) { } if ( ! set_transient( self::STATUS_DETAIL_TRANSIENT, $stored_value, MONTH_IN_SECONDS ) ) { - return new WP_Error( 'set_transient_error' ); + return new WP_Error( 'set_transient_error', __( 'The detailed Site Health status could not be saved.' ) ); } return true; } diff --git a/tests/phpunit/tests/admin/wpSiteHealth.php b/tests/phpunit/tests/admin/wpSiteHealth.php index de7ccfe3dd3e8..796ae47ce4cc7 100644 --- a/tests/phpunit/tests/admin/wpSiteHealth.php +++ b/tests/phpunit/tests/admin/wpSiteHealth.php @@ -997,6 +997,18 @@ public function test_only_valid_results_are_cached(): void { ); $this->assertWPError( $result ); + + $result = WP_Site_Health::update_site_status_detail( + array( + '' => array( + 'status' => 'good', + ), + ) + ); + + $this->assertWPError( $result ); + $this->assertSame( 'invalid_test', $result->get_error_code() ); + $this->assertNotSame( '', $result->get_error_message() ); $this->assertSame( array( 'valid_result' ), array_keys( WP_Site_Health::get_site_status_detail()['results'] ) ); } From 1a0d531a91aab9830b58e8d4195fede7fe48fcb5 Mon Sep 17 00:00:00 2001 From: Grzegorz Ziolkowski Date: Fri, 30 Oct 2026 16:15:38 +0100 Subject: [PATCH 41/51] Site Health: Document the distinct roles of both status caches. --- src/wp-admin/includes/ajax-actions.php | 6 +++++- src/wp-admin/includes/class-wp-site-health.php | 4 ++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/src/wp-admin/includes/ajax-actions.php b/src/wp-admin/includes/ajax-actions.php index d8cfcd905a525..eae9a20952406 100644 --- a/src/wp-admin/includes/ajax-actions.php +++ b/src/wp-admin/includes/ajax-actions.php @@ -5470,7 +5470,11 @@ function wp_ajax_health_check_site_status_result() { $save_results = array(); // Refresh the lightweight, autoloaded aggregate counts used by the admin menu and Dashboard. - // TODO: We don't need to keep this anymore. We can just obtain the counts at runtime from the stored results. + /* + * Keep the latest run's counts in the small, autoloaded cache for the admin menu + * and Dashboard. The separate, non-autoloaded detail cache retains verified + * results across runs, so deriving these counts from it would change their meaning. + */ if ( isset( $_POST['counts'] ) && is_array( $_POST['counts'] ) ) { $counts = wp_unslash( $_POST['counts'] ); $save_results[] = WP_Site_Health::set_site_status_counts( $counts ); diff --git a/src/wp-admin/includes/class-wp-site-health.php b/src/wp-admin/includes/class-wp-site-health.php index dfbae38389d6a..1f5306525a408 100644 --- a/src/wp-admin/includes/class-wp-site-health.php +++ b/src/wp-admin/includes/class-wp-site-health.php @@ -104,7 +104,8 @@ class WP_Site_Health { * Transient name for the cached aggregate Site Health status counts. * * This value is small and read on the admin menu and Dashboard, so it remains - * autoloaded. + * autoloaded. It reflects the latest run, including unavailable tests, while + * the separate detail cache retains the latest verified result for each test. * * @since 7.1.0 */ @@ -3635,7 +3636,6 @@ public static function set_site_status_counts( array $counts ) { * consistent view of counts and detailed results should read both from here. * * @since 7.1.0 - * @todo This method is now not used. * * @return array The cached results as a map keyed by test name, aggregate counts derived * from those same results, and the time of the most recent update. `results` From 97153260de3300e02b2468e8ea4f7d49961fd892 Mon Sep 17 00:00:00 2001 From: Grzegorz Ziolkowski Date: Fri, 30 Oct 2026 16:17:20 +0100 Subject: [PATCH 42/51] Site Health: Remove redundant async test type check. --- .../includes/class-wp-site-health.php | 74 +++++++++---------- 1 file changed, 36 insertions(+), 38 deletions(-) diff --git a/src/wp-admin/includes/class-wp-site-health.php b/src/wp-admin/includes/class-wp-site-health.php index 1f5306525a408..e1c2655dd752a 100644 --- a/src/wp-admin/includes/class-wp-site-health.php +++ b/src/wp-admin/includes/class-wp-site-health.php @@ -3501,46 +3501,44 @@ public function wp_cron_scheduled_check() { continue; } - if ( is_string( $test['test'] ) ) { - // Check if this test has a REST API endpoint. - if ( isset( $test['has_rest'] ) && $test['has_rest'] ) { - $result_fetch = wp_remote_get( - $test['test'], - array( - 'body' => array( - '_wpnonce' => wp_create_nonce( 'wp_rest' ), - ), - ) - ); - } else { - $result_fetch = wp_remote_post( - admin_url( 'admin-ajax.php' ), - array( - 'body' => array( - 'action' => $test['test'], - '_wpnonce' => wp_create_nonce( 'health-check-site-status' ), - ), - ) - ); - } + // Check if this test has a REST API endpoint. + if ( isset( $test['has_rest'] ) && $test['has_rest'] ) { + $result_fetch = wp_remote_get( + $test['test'], + array( + 'body' => array( + '_wpnonce' => wp_create_nonce( 'wp_rest' ), + ), + ) + ); + } else { + $result_fetch = wp_remote_post( + admin_url( 'admin-ajax.php' ), + array( + 'body' => array( + 'action' => $test['test'], + '_wpnonce' => wp_create_nonce( 'health-check-site-status' ), + ), + ) + ); + } - if ( ! is_wp_error( $result_fetch ) && 200 === wp_remote_retrieve_response_code( $result_fetch ) ) { - $result = json_decode( wp_remote_retrieve_body( $result_fetch ), true ); - } else { - $result = false; - } + if ( ! is_wp_error( $result_fetch ) && 200 === wp_remote_retrieve_response_code( $result_fetch ) ) { + $result = json_decode( wp_remote_retrieve_body( $result_fetch ), true ); + } else { + $result = false; + } - if ( is_array( $result ) ) { - $results[] = $result; - } else { - // Include the test identifier so the unavailable result is counted consistently. - $unavailable_tests[ $test_name ] = true; - $results[] = array( - 'test' => $test_name, - 'status' => 'recommended', - 'label' => __( 'A test is unavailable' ), - ); - } + if ( is_array( $result ) ) { + $results[] = $result; + } else { + // Include the test identifier so the unavailable result is counted consistently. + $unavailable_tests[ $test_name ] = true; + $results[] = array( + 'test' => $test_name, + 'status' => 'recommended', + 'label' => __( 'A test is unavailable' ), + ); } } From 24baaa539421168bae4acb52483b433528613e12 Mon Sep 17 00:00:00 2001 From: Grzegorz Ziolkowski Date: Fri, 30 Oct 2026 16:33:36 +0100 Subject: [PATCH 43/51] Site Health: Consolidate status counts and verified results in one cache. --- src/js/_enqueues/admin/site-health.js | 17 +- src/wp-admin/includes/ajax-actions.php | 52 ++-- .../includes/class-wp-site-health.php | 161 +++++----- tests/phpunit/tests/admin/wpSiteHealth.php | 279 +++++++++--------- .../wpAjaxHealthCheckSiteStatusResult.php | 244 ++++++--------- 5 files changed, 350 insertions(+), 403 deletions(-) diff --git a/src/js/_enqueues/admin/site-health.js b/src/js/_enqueues/admin/site-health.js index 1641a77b8044e..b3dd959532a82 100644 --- a/src/js/_enqueues/admin/site-health.js +++ b/src/js/_enqueues/admin/site-health.js @@ -258,28 +258,17 @@ jQuery( function( $ ) { } if ( isStatusTab ) { - // Refresh the lightweight counts first, so a large detailed payload can't block them. + // Save counts and verified results together in the shared cache. $.post( ajaxurl, { 'action': 'health-check-site-status-result', '_wpnonce': SiteHealth.nonce.site_status_result, - 'counts': SiteHealth.site_status.issues + 'counts': SiteHealth.site_status.issues, + 'results': JSON.stringify( SiteHealth.site_status.results ) } ); - // Send the per-test results separately, as a best-effort detailed cache update. - if ( Object.keys( SiteHealth.site_status.results ).length > 0 ) { - $.post( - ajaxurl, - { - 'action': 'health-check-site-status-result', - '_wpnonce': SiteHealth.nonce.site_status_result, - 'results': JSON.stringify( SiteHealth.site_status.results ) - } - ); - } - if ( 100 === val ) { $( '.site-status-all-clear' ).removeClass( 'hide' ); $( '.site-status-has-issues' ).addClass( 'hide' ); diff --git a/src/wp-admin/includes/ajax-actions.php b/src/wp-admin/includes/ajax-actions.php index eae9a20952406..ffb23bc08f823 100644 --- a/src/wp-admin/includes/ajax-actions.php +++ b/src/wp-admin/includes/ajax-actions.php @@ -5448,13 +5448,12 @@ function wp_ajax_health_check_loopback_requests() { /** * Handles site health check to update the result status via AJAX. * - * The aggregate counts and the full per-test results are sent as two independent - * requests, so a large results payload cannot prevent the lightweight counts from being - * refreshed. Each is handled on its own here, and either may be omitted. + * Counts and compact per-test results are saved together. Counts-only requests + * remain supported for compatibility, and results-only requests preserve counts. * * @since 5.2.0 - * @since 7.1.0 The submitted counts are validated, and the optional full per-test results - * are sanitized and cached separately as the authoritative detailed results. + * @since 7.1.0 The submitted counts are validated, and optional per-test statuses + * and timestamps extend the existing transient. */ function wp_ajax_health_check_site_status_result() { check_ajax_referer( 'health-check-site-status-result' ); @@ -5467,39 +5466,36 @@ function wp_ajax_health_check_site_status_result() { require_once ABSPATH . 'wp-admin/includes/class-wp-site-health.php'; } - $save_results = array(); + $counts = null; + $results = null; - // Refresh the lightweight, autoloaded aggregate counts used by the admin menu and Dashboard. - /* - * Keep the latest run's counts in the small, autoloaded cache for the admin menu - * and Dashboard. The separate, non-autoloaded detail cache retains verified - * results across runs, so deriving these counts from it would change their meaning. - */ - if ( isset( $_POST['counts'] ) && is_array( $_POST['counts'] ) ) { - $counts = wp_unslash( $_POST['counts'] ); - $save_results[] = WP_Site_Health::set_site_status_counts( $counts ); + if ( isset( $_POST['counts'] ) ) { + if ( ! is_array( $_POST['counts'] ) ) { + wp_send_json_error(); + } + $counts = wp_unslash( $_POST['counts'] ); } - /* - * Cache the full per-test results as the authoritative detailed results. These include - * the asynchronous tests that require JavaScript to run. The values are sanitized in - * WP_Site_Health::update_site_status_detail(). - */ - if ( isset( $_POST['results'] ) && is_string( $_POST['results'] ) ) { + if ( isset( $_POST['results'] ) ) { + if ( ! is_string( $_POST['results'] ) ) { + wp_send_json_error(); + } $results = json_decode( wp_unslash( $_POST['results'] ), true ); - - if ( is_array( $results ) ) { - $save_results[] = WP_Site_Health::update_site_status_detail( $results ); + if ( ! is_array( $results ) ) { + wp_send_json_error(); } } - if ( count( $save_results ) === 0 ) { + if ( null !== $results ) { + $saved = WP_Site_Health::update_site_status_detail( $results, $counts ); + } elseif ( null !== $counts ) { + $saved = WP_Site_Health::set_site_status_counts( $counts ); + } else { wp_send_json_error(); } - $errors = array_filter( $save_results, 'is_wp_error' ); - if ( count( $errors ) > 0 ) { - wp_send_json_error( reset( $errors ) ); + if ( is_wp_error( $saved ) ) { + wp_send_json_error( $saved ); } wp_send_json_success(); diff --git a/src/wp-admin/includes/class-wp-site-health.php b/src/wp-admin/includes/class-wp-site-health.php index e1c2655dd752a..5c0b46d970a08 100644 --- a/src/wp-admin/includes/class-wp-site-health.php +++ b/src/wp-admin/includes/class-wp-site-health.php @@ -101,26 +101,16 @@ class WP_Site_Health { ); /** - * Transient name for the cached aggregate Site Health status counts. + * Transient name for the cached Site Health counts and verified test results. * - * This value is small and read on the admin menu and Dashboard, so it remains - * autoloaded. It reflects the latest run, including unavailable tests, while - * the separate detail cache retains the latest verified result for each test. + * The existing top-level counts describe the latest run, including unavailable + * tests. Compact, locale-independent results retain each test's latest verified + * status. This transient remains autoloaded for the admin menu and Dashboard. * * @since 7.1.0 */ const STATUS_RESULT_TRANSIENT = 'health-check-site-status-result'; - /** - * Transient name for the cached detailed Site Health test results. - * - * This value can be large, so it is stored with an expiration to keep it from - * being autoloaded on every request. - * - * @since 7.1.0 - */ - const STATUS_DETAIL_TRANSIENT = 'health-check-site-status-detail'; - /** * WP_Site_Health constructor. * @@ -3542,10 +3532,10 @@ public function wp_cron_scheduled_check() { } } - $results_to_count = array(); + $counts = self::normalize_status_counts( array() ); $results_to_store = array(); foreach ( $results as $result ) { - // Filters may return unexpected values, so require the fields used by both caches. + // Filters may return unexpected values, so require the fields used by counts and details. if ( ! is_array( $result ) ) { continue; } @@ -3560,23 +3550,21 @@ public function wp_cron_scheduled_check() { continue; } - $results_to_count[] = array( 'status' => $status ); + ++$counts[ $status ]; if ( ! isset( $unavailable_tests[ $test ] ) ) { $results_to_store[ $test ] = array( 'status' => $status ); } } - self::set_site_status_counts( self::count_site_status_results( $results_to_count ) ); - /* - * Cache the full results separately, keyed by test, so consumers can read the + * Cache the compact results, keyed by test, so consumers can read the * detailed Site Health status without re-running the tests. * * Only verified results are included. An unavailable asynchronous test is still * reflected in the aggregate counts, but does not replace a previously verified * detailed result. */ - self::update_site_status_detail( $results_to_store ); + self::update_site_status_detail( $results_to_store, $counts ); } /** @@ -3587,12 +3575,8 @@ public function wp_cron_scheduled_check() { * @return Test_Status_Counts Aggregate counts. Each value is `0` when no result has been cached. */ public static function get_site_status_counts(): array { - $counts = get_transient( self::STATUS_RESULT_TRANSIENT ); - if ( is_string( $counts ) ) { - $counts = json_decode( $counts, true ); - } - - if ( ! is_array( $counts ) || is_wp_error( rest_validate_value_from_schema( $counts, self::STATUS_COUNTS_SCHEMA ) ) ) { + $counts = self::read_site_status_cache(); + if ( is_wp_error( rest_validate_value_from_schema( $counts, self::STATUS_COUNTS_SCHEMA ) ) ) { $counts = array(); } @@ -3602,6 +3586,8 @@ public static function get_site_status_counts(): array { /** * Caches the aggregate Site Health status counts. * + * Preserves unexpired verified results and their collection timestamps. + * * @since 7.1.0 * * @param mixed[] $counts Aggregate counts. @@ -3613,16 +3599,9 @@ public static function set_site_status_counts( array $counts ) { return $validity; } - $stored_value = wp_json_encode( $counts ); - if ( get_transient( self::STATUS_RESULT_TRANSIENT ) === $stored_value ) { - return true; - } - - if ( ! set_transient( self::STATUS_RESULT_TRANSIENT, wp_json_encode( $counts ) ) ) { - return new WP_Error( 'set_transient_error', __( 'The Site Health status counts could not be saved.' ) ); - } - - return true; + return self::save_site_status_cache( + array_merge( self::normalize_status_counts( $counts ), self::normalize_site_status_detail( self::read_site_status_cache() ) ) + ); } /** @@ -3632,20 +3611,23 @@ public static function set_site_status_counts( array $counts ) { * internally consistent. They may differ from WP_Site_Health::get_site_status_counts(), * which reflects the latest run for the admin menu and Dashboard. Consumers that need a * consistent view of counts and detailed results should read both from here. + * Results older than a month are excluded even when no writer has refreshed + * the autoloaded transient. * * @since 7.1.0 * * @return array The cached results as a map keyed by test name, aggregate counts derived * from those same results, and the time of the most recent update. `results` - * is empty, all counts are `0`, and `timestamp` is `0` when none are cached. + * is empty and all counts are `0` when no unexpired results remain. The + * timestamp records the last detail update, or `0` if none is available. * @phpstan-return Site_Status_Detail */ public static function get_site_status_detail(): array { - $cached = self::read_site_status_detail_cache(); + $cached = self::normalize_site_status_detail( self::read_site_status_cache() ); return array( 'results' => $cached['results'], - 'counts' => self::count_site_status_results( array_values( $cached['results'] ) ), + 'counts' => self::count_site_status_results( $cached['results'] ), 'timestamp' => $cached['timestamp'], ); } @@ -3656,17 +3638,31 @@ public static function get_site_status_detail(): array { * Results are normalized and sanitized, then stored keyed by test name with a * per-result timestamp. Entries that have not been refreshed within a month are * dropped, for example when the plugin that registered a test has been deactivated. + * Optional latest-run counts are validated and saved in the same write. When + * omitted, the existing counts are preserved. * * @since 7.1.0 * * @param array $results Map of raw Site Health test result arrays, * keyed by test name. + * @param mixed[]|null $counts Optional latest-run counts to save with the results. * @return true|WP_Error True on success, WP_Error on failure. */ - public static function update_site_status_detail( array $results ) { + public static function update_site_status_detail( array $results, ?array $counts = null ) { + if ( null !== $counts ) { + $validity = rest_validate_value_from_schema( $counts, self::STATUS_COUNTS_SCHEMA ); + if ( is_wp_error( $validity ) ) { + return $validity; + } + } + $now = time(); - $cached = self::read_site_status_detail_cache(); + $stored = self::read_site_status_cache(); + $cached = self::normalize_site_status_detail( $stored ); + if ( null === $counts ) { + $counts = is_wp_error( rest_validate_value_from_schema( $stored, self::STATUS_COUNTS_SCHEMA ) ) ? array() : $stored; + } foreach ( $results as $test => $result ) { $test = sanitize_text_field( $test ); @@ -3687,49 +3683,64 @@ public static function update_site_status_detail( array $results ) { $cached['results'][ $test ] = $result; } - // Drop results that have not been refreshed within the last month. - foreach ( $cached['results'] as $test => $result ) { - if ( ! isset( $result['timestamp'] ) || ( $now - (int) $result['timestamp'] ) > MONTH_IN_SECONDS ) { - unset( $cached['results'][ $test ] ); - } - } - - $stored_value = wp_json_encode( - array( - 'results' => $cached['results'], - 'timestamp' => $now, + return self::save_site_status_cache( + array_merge( + self::normalize_status_counts( $counts ), + array( + 'results' => $cached['results'], + 'timestamp' => $now, + ) ) ); - if ( get_transient( self::STATUS_DETAIL_TRANSIENT ) === $stored_value ) { - return true; - } + } - if ( ! set_transient( self::STATUS_DETAIL_TRANSIENT, $stored_value, MONTH_IN_SECONDS ) ) { - return new WP_Error( 'set_transient_error', __( 'The detailed Site Health status could not be saved.' ) ); + /** + * Saves the counts and compact results together in the autoloaded transient. + * + * @since 7.1.0 + * + * @param array $status Combined counts and detailed results. + * @return true|WP_Error True on success, WP_Error on failure. + */ + private static function save_site_status_cache( array $status ) { + $stored_value = wp_json_encode( $status ); + + // An unchanged option also returns false, so only read back after a failed write. + if ( ! set_transient( self::STATUS_RESULT_TRANSIENT, $stored_value ) && + get_transient( self::STATUS_RESULT_TRANSIENT ) !== $stored_value + ) { + return new WP_Error( 'set_transient_error', __( 'The Site Health status could not be saved.' ) ); } return true; } /** - * Reads and decodes the cached detailed Site Health test results. + * Reads and decodes the shared Site Health cache. * * @since 7.1.0 * - * @return array The stored status. - * @phpstan-return Stored_Test_Results + * @return mixed[] The decoded cache, or an empty array when unavailable. */ - private static function read_site_status_detail_cache(): array { - $cached = get_transient( self::STATUS_DETAIL_TRANSIENT ); + private static function read_site_status_cache(): array { + $cached = get_transient( self::STATUS_RESULT_TRANSIENT ); if ( is_string( $cached ) ) { $cached = json_decode( $cached, true ); } - $validity = false; - if ( is_array( $cached ) ) { - $validity = rest_validate_value_from_schema( $cached, self::STORED_STATUS_SCHEMA ); - } + return is_array( $cached ) ? $cached : array(); + } - if ( true !== $validity ) { + /** + * Validates detailed results and excludes expired entries from a cache snapshot. + * + * @since 7.1.0 + * + * @param mixed[] $cached The decoded cache. + * @return array The unexpired results and the last detail-update timestamp. + * @phpstan-return Stored_Test_Results + */ + private static function normalize_site_status_detail( array $cached ): array { + if ( is_wp_error( rest_validate_value_from_schema( $cached, self::STORED_STATUS_SCHEMA ) ) ) { $cached = array( 'results' => array(), 'timestamp' => 0, @@ -3737,7 +3748,17 @@ private static function read_site_status_detail_cache(): array { } /** @var Stored_Test_Results $cached */ - return $cached; + $expires_before = time() - MONTH_IN_SECONDS; + foreach ( $cached['results'] as $test => $result ) { + if ( $result['timestamp'] < $expires_before ) { + unset( $cached['results'][ $test ] ); + } + } + + return array( + 'results' => $cached['results'], + 'timestamp' => $cached['timestamp'], + ); } /** @@ -3762,7 +3783,7 @@ private static function normalize_status_counts( array $counts ): array { * * @since 7.1.0 * - * @param list $results List of result arrays, each with a status. + * @param array $results Result arrays, each with a status. * @return array Aggregate counts, one bucket per status. A status other than `recommended` or `critical` counts as `good`. * @phpstan-return Test_Status_Counts */ diff --git a/tests/phpunit/tests/admin/wpSiteHealth.php b/tests/phpunit/tests/admin/wpSiteHealth.php index 796ae47ce4cc7..649bac75bef9a 100644 --- a/tests/phpunit/tests/admin/wpSiteHealth.php +++ b/tests/phpunit/tests/admin/wpSiteHealth.php @@ -513,7 +513,6 @@ static function () { ); } - /** * @group ms-required * @ticket 56040 @@ -785,29 +784,26 @@ private function seed_site_status_detail( array $results, int $time ): void { } set_transient( - WP_Site_Health::STATUS_DETAIL_TRANSIENT, + WP_Site_Health::STATUS_RESULT_TRANSIENT, wp_json_encode( array( 'results' => $results, 'timestamp' => $time, ) - ), - MONTH_IN_SECONDS + ) ); } /** - * The scheduled check stores only the aggregate counts in the autoloaded transient - * and caches the per-test results separately. + * The scheduled check extends the autoloaded counts transient with compact results. * * @ticket 65232 * * @covers ::wp_cron_scheduled_check * @covers ::get_site_status_detail - * @covers ::set_site_status_counts * @covers ::update_site_status_detail */ - public function test_scheduled_check_stores_counts_and_detail_separately(): void { + public function test_scheduled_check_stores_counts_and_detail_together(): void { $filter = $this->use_fake_site_status_tests( array( 'fake_critical' => array( @@ -837,10 +833,6 @@ public function test_scheduled_check_stores_counts_and_detail_separately(): void ); delete_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ); - delete_transient( WP_Site_Health::STATUS_DETAIL_TRANSIENT ); - - $counts_reads_before = did_filter( 'pre_transient_' . WP_Site_Health::STATUS_RESULT_TRANSIENT ); - $detail_reads_before = did_filter( 'pre_transient_' . WP_Site_Health::STATUS_DETAIL_TRANSIENT ); $before = time(); $this->instance->wp_cron_scheduled_check(); @@ -848,47 +840,21 @@ public function test_scheduled_check_stores_counts_and_detail_separately(): void remove_filter( 'site_status_tests', $filter ); - $this->assertSame( - 1, - did_filter( 'pre_transient_' . WP_Site_Health::STATUS_RESULT_TRANSIENT ) - $counts_reads_before, - 'The counts transient should be read once during the scheduled check.' - ); - $this->assertSame( - 2, - did_filter( 'pre_transient_' . WP_Site_Health::STATUS_DETAIL_TRANSIENT ) - $detail_reads_before, - 'The detail transient should be read twice during the scheduled check.' - ); - - // The counts transient holds only the aggregate counts, so it stays small enough to autoload. - $counts_transient = get_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ); - $this->assertIsString( $counts_transient ); - $stored_counts = json_decode( $counts_transient, true ); - $this->assertIsArray( $stored_counts ); - $this->assertSame( - array( - 'good' => 1, - 'recommended' => 1, - 'critical' => 1, - ), - $stored_counts, - 'The counts transient should contain only the aggregate counts.' - ); - - // The detail transient stores only results and a timestamp; counts are derived when it is read. - $detail_transient = get_transient( WP_Site_Health::STATUS_DETAIL_TRANSIENT ); - $this->assertIsString( $detail_transient ); - $stored_detail = json_decode( $detail_transient, true ); - $this->assertIsArray( $stored_detail ); + $transient = get_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ); + $this->assertIsString( $transient ); + $stored = json_decode( $transient, true ); $this->assertSameSets( - array( 'results', 'timestamp' ), - array_keys( $stored_detail ), - 'The detail transient should contain only the results and timestamp.' + array( 'good', 'recommended', 'critical', 'results', 'timestamp' ), + array_keys( $stored ) ); + $this->assertSame( 1, $stored['good'] ); + $this->assertSame( 1, $stored['recommended'] ); + $this->assertSame( 1, $stored['critical'] ); + $this->assertArrayHasKey( '_transient_' . WP_Site_Health::STATUS_RESULT_TRANSIENT, wp_load_alloptions() ); + $this->assertFalse( get_option( '_transient_timeout_' . WP_Site_Health::STATUS_RESULT_TRANSIENT ) ); // The detailed cache holds every result, including the passing one. $detail = WP_Site_Health::get_site_status_detail(); - $this->assertArrayHasKey( 'results', $detail ); - $this->assertCount( 3, $detail['results'], 'All results should be cached, not just actionable ones.' ); $results_by_test = $detail['results']; @@ -967,7 +933,6 @@ public function test_only_valid_results_are_cached(): void { add_filter( 'site_status_test_result', $result_filter ); delete_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ); - delete_transient( WP_Site_Health::STATUS_DETAIL_TRANSIENT ); try { $this->instance->wp_cron_scheduled_check(); @@ -988,16 +953,6 @@ public function test_only_valid_results_are_cached(): void { ); $this->assertSame( $detail['counts'], WP_Site_Health::get_site_status_counts() ); - $result = WP_Site_Health::update_site_status_detail( - array( - 'invalid_status' => array( - 'status' => 'invalid', - ), - ) - ); - - $this->assertWPError( $result ); - $result = WP_Site_Health::update_site_status_detail( array( '' => array( @@ -1077,8 +1032,7 @@ public function test_scheduled_check_stores_freshest_verified_result(): void { $this->seed_site_status_detail( array( 'fake_async' => array( - 'status' => 'good', - 'timestamp' => time(), + 'status' => 'good', ), ), time() @@ -1103,53 +1057,16 @@ public function test_scheduled_check_stores_freshest_verified_result(): void { } /** - * Results that have not been refreshed within a month are dropped. - * - * @ticket 65232 - * - * @covers ::update_site_status_detail - */ - public function test_update_site_status_detail_drops_stale_entries(): void { - $now = time(); - - set_transient( - WP_Site_Health::STATUS_DETAIL_TRANSIENT, - wp_json_encode( - array( - 'results' => array( - 'recent' => array( - 'status' => 'good', - 'timestamp' => $now, - ), - 'old' => array( - 'status' => 'good', - 'timestamp' => $now - 2 * MONTH_IN_SECONDS, - ), - ), - 'timestamp' => $now, - ) - ), - MONTH_IN_SECONDS - ); - - // Update with nothing new; the stale-entry pruning still runs. - WP_Site_Health::update_site_status_detail( array() ); - - $detail = WP_Site_Health::get_site_status_detail(); - $this->assertCount( 1, $detail['results'] ); - $this->assertArrayHasKey( 'recent', $detail['results'] ); - } - - /** - * The counts accessor returns zeroed counts when nothing is cached. + * The detail accessor distinguishes a valid empty cache from a missing or malformed cache. * * @ticket 65232 * + * @covers ::get_site_status_detail * @covers ::get_site_status_counts + * @covers ::update_site_status_detail */ - public function test_get_site_status_counts_defaults_when_uncached(): void { + public function test_get_site_status_detail_distinguishes_empty_from_missing_or_malformed_cache(): void { delete_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ); - $this->assertSame( array( 'good' => 0, @@ -1158,36 +1075,6 @@ public function test_get_site_status_counts_defaults_when_uncached(): void { ), WP_Site_Health::get_site_status_counts() ); - } - - /** - * The counts accessor returns the cached aggregate counts. - * - * @ticket 65232 - * - * @covers ::get_site_status_counts - */ - public function test_get_site_status_counts_returns_cached_counts(): void { - $counts = array( - 'good' => 3, - 'recommended' => 2, - 'critical' => 1, - ); - set_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT, wp_json_encode( $counts ) ); - - $this->assertSame( $counts, WP_Site_Health::get_site_status_counts() ); - } - - /** - * The detail accessor distinguishes a valid empty cache from a missing or malformed cache. - * - * @ticket 65232 - * - * @covers ::get_site_status_detail - * @covers ::update_site_status_detail - */ - public function test_get_site_status_detail_distinguishes_empty_from_missing_or_malformed_cache(): void { - delete_transient( WP_Site_Health::STATUS_DETAIL_TRANSIENT ); $detail = WP_Site_Health::get_site_status_detail(); $this->assertSame( array(), $detail['results'] ); @@ -1201,11 +1088,11 @@ public function test_get_site_status_detail_distinguishes_empty_from_missing_or_ $this->assertSame( array(), $detail['results'] ); $this->assertGreaterThanOrEqual( $before, $detail['timestamp'] ); $this->assertLessThanOrEqual( $after, $detail['timestamp'] ); - $this->assertIsString( get_transient( WP_Site_Health::STATUS_DETAIL_TRANSIENT ) ); + $this->assertIsString( get_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ) ); $now = time(); set_transient( - WP_Site_Health::STATUS_DETAIL_TRANSIENT, + WP_Site_Health::STATUS_RESULT_TRANSIENT, wp_json_encode( array( 'results' => array( @@ -1213,8 +1100,7 @@ public function test_get_site_status_detail_distinguishes_empty_from_missing_or_ ), 'timestamp' => $now, ) - ), - MONTH_IN_SECONDS + ) ); $detail = WP_Site_Health::get_site_status_detail(); @@ -1222,7 +1108,7 @@ public function test_get_site_status_detail_distinguishes_empty_from_missing_or_ $this->assertSame( 0, $detail['timestamp'] ); set_transient( - WP_Site_Health::STATUS_DETAIL_TRANSIENT, + WP_Site_Health::STATUS_RESULT_TRANSIENT, wp_json_encode( array( 'results' => array( @@ -1232,12 +1118,127 @@ public function test_get_site_status_detail_distinguishes_empty_from_missing_or_ ), ), ), - ), - MONTH_IN_SECONDS + ) ); $detail = WP_Site_Health::get_site_status_detail(); $this->assertSame( array(), $detail['results'] ); $this->assertSame( 0, $detail['timestamp'] ); } + + /** + * Old counts-only values can be extended without changing the existing counts. + * + * @ticket 65232 + * @covers ::update_site_status_detail + * @covers ::set_site_status_counts + * @covers ::get_site_status_counts + */ + public function test_extending_legacy_counts_preserves_each_kind_of_data(): void { + $counts = array( + 'good' => 9, + 'recommended' => 2, + 'critical' => 1, + ); + set_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT, wp_json_encode( $counts ) ); + $this->assertSame( $counts, WP_Site_Health::get_site_status_counts() ); + $this->assertSame( 0, WP_Site_Health::get_site_status_detail()['timestamp'] ); + + $reads_before = did_filter( 'pre_transient_' . WP_Site_Health::STATUS_RESULT_TRANSIENT ); + $this->assertTrue( WP_Site_Health::update_site_status_detail( array( 'verified' => array( 'status' => 'good' ) ) ) ); + $this->assertSame( 1, did_filter( 'pre_transient_' . WP_Site_Health::STATUS_RESULT_TRANSIENT ) - $reads_before, 'A results-only update should read the shared cache once.' ); + $this->assertSame( $counts, WP_Site_Health::get_site_status_counts() ); + $detail = WP_Site_Health::get_site_status_detail(); + + $counts['critical'] = 3; + $this->assertTrue( WP_Site_Health::set_site_status_counts( $counts ) ); + $this->assertSame( $detail, WP_Site_Health::get_site_status_detail() ); + $this->assertSame( $counts, WP_Site_Health::get_site_status_counts() ); + } + + /** + * Details expire even without a scheduled update; latest-run counts are retained. + * + * @ticket 65232 + * @covers ::get_site_status_detail + * @covers ::update_site_status_detail + * @covers ::set_site_status_counts + */ + public function test_reading_expired_details_preserves_counts(): void { + $counts = array( + 'good' => 4, + 'recommended' => 1, + 'critical' => 0, + ); + $old = time() - MONTH_IN_SECONDS - 10; + $status = array_merge( + $counts, + array( + 'results' => array( + 'old' => array( + 'status' => 'critical', + 'timestamp' => $old, + ), + 'new' => array( + 'status' => 'good', + 'timestamp' => time(), + ), + ), + 'timestamp' => time(), + ) + ); + set_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT, wp_json_encode( $status ) ); + $detail = WP_Site_Health::get_site_status_detail(); + $this->assertSame( array( 'new' ), array_keys( $detail['results'] ) ); + $this->assertSame( 1, $detail['counts']['good'] ); + $this->assertSame( 0, $detail['counts']['critical'] ); + + $this->assertTrue( WP_Site_Health::update_site_status_detail( array() ) ); + $stored = json_decode( get_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ), true ); + $this->assertSame( array( 'new' ), array_keys( $stored['results'] ), 'A detail update must persist pruning, even with no new results.' ); + + $status['results']['new']['timestamp'] = $old; + $status['timestamp'] = $old; + set_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT, wp_json_encode( $status ) ); + $this->assertSame( array(), WP_Site_Health::get_site_status_detail()['results'] ); + $this->assertSame( $old, WP_Site_Health::get_site_status_detail()['timestamp'] ); + $this->assertSame( $counts, WP_Site_Health::get_site_status_counts() ); + + // A counts-only update must prune expired details without refreshing their age. + $this->assertTrue( WP_Site_Health::set_site_status_counts( $counts ) ); + $stored = json_decode( get_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ), true ); + $this->assertSame( array(), $stored['results'] ); + $this->assertSame( $old, $stored['timestamp'] ); + } + + /** + * An unchanged cache is a success, but a failed write must still report an error. + * + * @ticket 65232 + * @covers ::set_site_status_counts + */ + public function test_cache_write_failure_returns_error(): void { + $counts = array( + 'good' => 1, + 'recommended' => 0, + 'critical' => 0, + ); + $this->assertTrue( WP_Site_Health::set_site_status_counts( $counts ) ); + $this->assertTrue( WP_Site_Health::set_site_status_counts( $counts ) ); + $before = get_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ); + $prevent_write = static function ( $value, $old_value ) { + return $old_value; + }; + $filter = 'pre_update_option__transient_' . WP_Site_Health::STATUS_RESULT_TRANSIENT; + add_filter( $filter, $prevent_write, 10, 2 ); + $counts['good'] = 2; + try { + $result = WP_Site_Health::set_site_status_counts( $counts ); + } finally { + remove_filter( $filter, $prevent_write ); + } + $this->assertWPError( $result ); + $this->assertSame( 'set_transient_error', $result->get_error_code() ); + $this->assertSame( $before, get_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ) ); + } } diff --git a/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php b/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php index a64520decb187..d7bfd35aae641 100644 --- a/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php +++ b/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php @@ -84,15 +84,12 @@ private function dispatch_result_request(): array { } /** - * The aggregate counts are cached on their own, while the results submitted by - * the Site Health screen are sanitized and cached separately. + * The request stores both parts in one write, without deriving latest-run counts from details. * * @ticket 65232 */ - public function test_posting_counts_and_results_caches_them_separately(): void { + public function test_posting_counts_and_results_caches_them_together(): void { delete_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ); - delete_transient( WP_Site_Health::STATUS_DETAIL_TRANSIENT ); - $this->set_user_with_site_health_capability(); $_POST['_wpnonce'] = wp_create_nonce( self::ACTION ); $_POST['counts'] = array( @@ -100,108 +97,36 @@ public function test_posting_counts_and_results_caches_them_separately(): void { 'recommended' => 1, 'critical' => 2, ); - $_POST['results'] = wp_slash( - wp_json_encode( - array( - 'a' => array( - 'status' => 'critical', - ), - 'b' => array( - 'status' => 'recommended', - ), - 'c' => array( - 'status' => 'good', - ), - 'd' => array( - // An unrecognized status is rejected. - 'status' => 'bogus', - ), - ) - ) - ); - - $response = $this->dispatch_result_request(); - $this->assertFalse( $response['success'] ); - $this->assertSame( 'rest_not_in_enum', $response['data'][0]['code'] ); - - $_POST['results'] = wp_slash( - wp_json_encode( - array( - 'a' => array( - 'status' => 'critical', - ), - 'b' => array( - 'status' => 'recommended', - ), - 'c' => array( - 'status' => 'good', - ), - ) - ) - ); - - $response = $this->dispatch_result_request(); - $this->assertTrue( $response['success'] ); - - // The counts transient holds only the aggregate counts. - $transient = get_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ); - $this->assertIsString( $transient ); + $_POST['results'] = wp_slash( wp_json_encode( array( 'a' => array( 'status' => 'critical' ) ) ) ); + + $writes_before = did_action( 'set_transient_' . WP_Site_Health::STATUS_RESULT_TRANSIENT ); + $this->assertTrue( $this->dispatch_result_request()['success'] ); + $this->assertSame( 1, did_action( 'set_transient_' . WP_Site_Health::STATUS_RESULT_TRANSIENT ) - $writes_before ); + $this->assertSame( $_POST['counts'], WP_Site_Health::get_site_status_counts() ); + $detail = WP_Site_Health::get_site_status_detail(); + $this->assertSame( array( 'a' ), array_keys( $detail['results'] ) ); + $this->assertSame( 'critical', $detail['results']['a']['status'] ); $this->assertSame( array( - 'good' => 5, - 'recommended' => 1, - 'critical' => 2, - ), - json_decode( $transient, true ) - ); - - // Only results with a recognized status are cached. - $results = WP_Site_Health::get_site_status_detail()['results']; - $this->assertSame( array( 'a', 'b', 'c' ), array_keys( $results ) ); - - // Only locale-independent fields are cached: the test name, status, and timestamp. - $this->assertSameSets( - array( 'status', 'timestamp' ), - array_keys( $results['a'] ), - 'No translated or HTML fields should be cached.' - ); - $this->assertSame( 'critical', $results['a']['status'] ); - - // Each cached result carries a timestamp. - $this->assertIsInt( $results['a']['timestamp'] ); - $this->assertGreaterThan( 0, $results['a']['timestamp'] ); - - // The detail cache exposes counts derived from its own (sanitized) results. - $this->assertSame( - array( - 'good' => 1, - 'recommended' => 1, + 'good' => 0, + 'recommended' => 0, 'critical' => 1, ), - WP_Site_Health::get_site_status_detail()['counts'] + $detail['counts'] ); } /** - * Posting only the results updates the detailed cache without touching the counts cache. + * Posting only the results updates the detailed cache without changing the latest-run counts. * * @ticket 65232 */ public function test_posting_results_only_updates_detail_without_counts(): void { delete_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ); - delete_transient( WP_Site_Health::STATUS_DETAIL_TRANSIENT ); $this->set_user_with_site_health_capability(); $_POST['_wpnonce'] = wp_create_nonce( self::ACTION ); - $_POST['results'] = wp_slash( - wp_json_encode( - array( - 'a' => array( - 'status' => 'critical', - ), - ) - ) - ); + $_POST['results'] = wp_slash( wp_json_encode( array( 'a' => array( 'status' => 'critical' ) ) ) ); $response = $this->dispatch_result_request(); @@ -211,32 +136,25 @@ public function test_posting_results_only_updates_detail_without_counts(): void $results = WP_Site_Health::get_site_status_detail()['results']; $this->assertSame( array( 'a' ), array_keys( $results ) ); - // The counts cache is not written by a results-only request. - $this->assertFalse( get_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ) ); + // Results-only requests preserve the default counts. + $this->assertSame( + array( + 'good' => 0, + 'recommended' => 0, + 'critical' => 0, + ), + WP_Site_Health::get_site_status_counts() + ); } /** - * Posting only counts refreshes the counts cache and leaves the detailed cache intact. + * Posting only counts refreshes the counts and leaves verified results intact. * * @ticket 65232 */ public function test_posting_counts_only_leaves_detail_intact(): void { - $now = time(); - set_transient( - WP_Site_Health::STATUS_DETAIL_TRANSIENT, - wp_json_encode( - array( - 'results' => array( - 'seeded' => array( - 'status' => 'good', - 'timestamp' => $now, - ), - ), - 'timestamp' => $now, - ) - ), - MONTH_IN_SECONDS - ); + WP_Site_Health::update_site_status_detail( array( 'seeded' => array( 'status' => 'good' ) ) ); + $detail = WP_Site_Health::get_site_status_detail(); $this->set_user_with_site_health_capability(); $_POST['_wpnonce'] = wp_create_nonce( self::ACTION ); @@ -250,52 +168,25 @@ public function test_posting_counts_only_leaves_detail_intact(): void { $this->assertTrue( $response['success'] ); - $transient = get_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ); - $this->assertIsString( $transient ); $this->assertSame( array( 'good' => 3, 'recommended' => 0, 'critical' => 0, ), - json_decode( $transient, true ) + WP_Site_Health::get_site_status_counts() ); - $results = WP_Site_Health::get_site_status_detail()['results']; - $this->assertSame( array( 'seeded' ), array_keys( $results ), 'The detailed cache should be untouched.' ); - } - - /** - * Non-array counts are rejected and leave both caches untouched. - * - * @ticket 65232 - */ - public function test_invalid_counts_return_error_and_write_nothing(): void { - $existing = array( 'good' => 9 ); - set_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT, wp_json_encode( $existing ) ); - - $this->set_user_with_site_health_capability(); - $_POST['_wpnonce'] = wp_create_nonce( self::ACTION ); - // No 'counts' are supplied. - - $response = $this->dispatch_result_request(); - - $this->assertFalse( $response['success'] ); - - $transient = get_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ); - $this->assertIsString( $transient ); - $this->assertSame( $existing, json_decode( $transient, true ), 'The counts cache should be untouched.' ); - $this->assertFalse( get_transient( WP_Site_Health::STATUS_DETAIL_TRANSIENT ) ); + $this->assertSame( $detail, WP_Site_Health::get_site_status_detail(), 'Verified results and timestamps should be untouched.' ); } /** - * Users without the capability cannot write to either cache. + * Users without the capability cannot write to the cache. * * @ticket 65232 */ public function test_user_without_capability_cannot_write_cache(): void { delete_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ); - delete_transient( WP_Site_Health::STATUS_DETAIL_TRANSIENT ); $this->_setRole( 'subscriber' ); $_POST['_wpnonce'] = wp_create_nonce( self::ACTION ); @@ -304,22 +195,71 @@ public function test_user_without_capability_cannot_write_cache(): void { 'recommended' => 1, 'critical' => 1, ); - $_POST['results'] = wp_slash( - wp_json_encode( - array( - array( - 'test' => 'a', - 'label' => 'A', - 'status' => 'critical', - ), - ) - ) - ); + $_POST['results'] = wp_slash( wp_json_encode( array( 'a' => array( 'status' => 'critical' ) ) ) ); $response = $this->dispatch_result_request(); $this->assertFalse( $response['success'] ); $this->assertFalse( get_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ) ); - $this->assertFalse( get_transient( WP_Site_Health::STATUS_DETAIL_TRANSIENT ) ); + } + + /** + * Invalid requests must not partially overwrite the shared cache. + * + * @ticket 65232 + * @dataProvider data_invalid_cache_requests + * + * @param array $request Submitted fields, excluding the nonce. + * @param string|null $error_code Expected validation error code, if provided. + */ + public function test_invalid_request_preserves_existing_cache( array $request, ?string $error_code ): void { + $this->set_user_with_site_health_capability(); + WP_Site_Health::update_site_status_detail( + array( 'existing' => array( 'status' => 'good' ) ), + array( + 'good' => 1, + 'recommended' => 0, + 'critical' => 0, + ) + ); + $before = get_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ); + $_POST = wp_slash( $request ); + $_POST['_wpnonce'] = wp_create_nonce( self::ACTION ); + $response = $this->dispatch_result_request(); + $this->assertFalse( $response['success'] ); + if ( null !== $error_code ) { + $this->assertSame( $error_code, $response['data'][0]['code'] ); + } + $this->assertSame( $before, get_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ) ); + } + + /** + * @return array Named invalid requests and their expected error codes. + */ + public static function data_invalid_cache_requests(): array { + return array( + 'no fields' => array( array(), null ), + 'invalid counts with valid results' => array( + array( + 'counts' => array( 'good' => -1 ), + 'results' => '{"new":{"status":"critical"}}', + ), + 'rest_out_of_bounds', + ), + 'valid counts with malformed JSON' => array( + array( + 'counts' => array( 'good' => 2 ), + 'results' => '{invalid json', + ), + null, + ), + 'valid counts with invalid status' => array( + array( + 'counts' => array( 'good' => 2 ), + 'results' => '{"new":{"status":"invalid"}}', + ), + 'rest_not_in_enum', + ), + ); } } From 2a465498a2bc67f83eb75a2788242e16ac9cfe86 Mon Sep 17 00:00:00 2001 From: Grzegorz Ziolkowski Date: Fri, 30 Oct 2026 16:55:09 +0100 Subject: [PATCH 44/51] Site Health: Limit stored status results and target 7.3.0. Cap the detailed results in the autoloaded transient at 500 entries. When over the limit, keep critical results first, then recommended, then good, and newer results before older ones within each status. Core registers about 30 tests, so this only guards against runaway growth. Also update the version tags to 7.3.0, since trunk is past the 7.2 feature freeze, and fix a docblock that still mentioned a separate detail transient. Co-Authored-By: Claude Opus 5.5 --- src/wp-admin/includes/ajax-actions.php | 2 +- .../includes/class-wp-site-health.php | 51 +++++++++++++---- tests/phpunit/tests/admin/wpSiteHealth.php | 56 +++++++++++++++++++ .../wpAjaxHealthCheckSiteStatusResult.php | 2 +- 4 files changed, 98 insertions(+), 13 deletions(-) diff --git a/src/wp-admin/includes/ajax-actions.php b/src/wp-admin/includes/ajax-actions.php index ffb23bc08f823..c7c7fecc0f1d5 100644 --- a/src/wp-admin/includes/ajax-actions.php +++ b/src/wp-admin/includes/ajax-actions.php @@ -5452,7 +5452,7 @@ function wp_ajax_health_check_loopback_requests() { * remain supported for compatibility, and results-only requests preserve counts. * * @since 5.2.0 - * @since 7.1.0 The submitted counts are validated, and optional per-test statuses + * @since 7.3.0 The submitted counts are validated, and optional per-test statuses * and timestamps extend the existing transient. */ function wp_ajax_health_check_site_status_result() { diff --git a/src/wp-admin/includes/class-wp-site-health.php b/src/wp-admin/includes/class-wp-site-health.php index 5c0b46d970a08..589bc8022f000 100644 --- a/src/wp-admin/includes/class-wp-site-health.php +++ b/src/wp-admin/includes/class-wp-site-health.php @@ -53,6 +53,14 @@ class WP_Site_Health { private const VALID_STATUS_VALUES = array( 'good', 'recommended', 'critical' ); + /* + * Maximum number of detailed results kept in the autoloaded transient. Core + * registers about 30 tests, so real sites stay far below this limit. It only + * guards against runaway growth. Each entry takes about 60 bytes, so the + * results stay around 30 KB at most. + */ + private const MAX_STORED_RESULTS = 500; + private const STATUS_COUNTS_SCHEMA = array( 'type' => 'object', 'properties' => array( @@ -107,7 +115,7 @@ class WP_Site_Health { * tests. Compact, locale-independent results retain each test's latest verified * status. This transient remains autoloaded for the admin menu and Dashboard. * - * @since 7.1.0 + * @since 7.3.0 */ const STATUS_RESULT_TRANSIENT = 'health-check-site-status-result'; @@ -3440,7 +3448,7 @@ public function maybe_create_scheduled_event() { * Runs the scheduled event to check and update the latest site health status for the website. * * @since 5.4.0 - * @since 7.1.0 The full test results are also cached in a separate detailed + * @since 7.3.0 Compact verified test results are saved with the counts in the same * transient via WP_Site_Health::update_site_status_detail(). */ public function wp_cron_scheduled_check() { @@ -3570,7 +3578,7 @@ public function wp_cron_scheduled_check() { /** * Returns the cached aggregate Site Health status counts. * - * @since 7.1.0 + * @since 7.3.0 * * @return Test_Status_Counts Aggregate counts. Each value is `0` when no result has been cached. */ @@ -3588,7 +3596,7 @@ public static function get_site_status_counts(): array { * * Preserves unexpired verified results and their collection timestamps. * - * @since 7.1.0 + * @since 7.3.0 * * @param mixed[] $counts Aggregate counts. * @return true|WP_Error True when the counts were saved, or WP_Error on failure. @@ -3614,7 +3622,7 @@ public static function set_site_status_counts( array $counts ) { * Results older than a month are excluded even when no writer has refreshed * the autoloaded transient. * - * @since 7.1.0 + * @since 7.3.0 * * @return array The cached results as a map keyed by test name, aggregate counts derived * from those same results, and the time of the most recent update. `results` @@ -3638,10 +3646,12 @@ public static function get_site_status_detail(): array { * Results are normalized and sanitized, then stored keyed by test name with a * per-result timestamp. Entries that have not been refreshed within a month are * dropped, for example when the plugin that registered a test has been deactivated. + * At most 500 results are kept. When there are more, critical results are kept + * first, then recommended, then good, and the newest results within each status. * Optional latest-run counts are validated and saved in the same write. When * omitted, the existing counts are preserved. * - * @since 7.1.0 + * @since 7.3.0 * * @param array $results Map of raw Site Health test result arrays, * keyed by test name. @@ -3683,6 +3693,25 @@ public static function update_site_status_detail( array $results, ?array $counts $cached['results'][ $test ] = $result; } + /* + * Keep the autoloaded transient small. When over the limit, drop the least useful + * results first: good before recommended before critical, and older before newer. + * The original order breaks ties, so the outcome does not depend on the sort algorithm. + */ + if ( count( $cached['results'] ) > self::MAX_STORED_RESULTS ) { + $unsorted = $cached['results']; + $priority = array_flip( array( 'critical', 'recommended', 'good' ) ); + $position = array_flip( array_keys( $unsorted ) ); + uksort( + $cached['results'], + static function ( $a, $b ) use ( $unsorted, $priority, $position ) { + return array( $priority[ $unsorted[ $a ]['status'] ], $unsorted[ $b ]['timestamp'], $position[ $a ] ) + <=> array( $priority[ $unsorted[ $b ]['status'] ], $unsorted[ $a ]['timestamp'], $position[ $b ] ); + } + ); + $cached['results'] = array_slice( $cached['results'], 0, self::MAX_STORED_RESULTS, true ); + } + return self::save_site_status_cache( array_merge( self::normalize_status_counts( $counts ), @@ -3697,7 +3726,7 @@ public static function update_site_status_detail( array $results, ?array $counts /** * Saves the counts and compact results together in the autoloaded transient. * - * @since 7.1.0 + * @since 7.3.0 * * @param array $status Combined counts and detailed results. * @return true|WP_Error True on success, WP_Error on failure. @@ -3717,7 +3746,7 @@ private static function save_site_status_cache( array $status ) { /** * Reads and decodes the shared Site Health cache. * - * @since 7.1.0 + * @since 7.3.0 * * @return mixed[] The decoded cache, or an empty array when unavailable. */ @@ -3733,7 +3762,7 @@ private static function read_site_status_cache(): array { /** * Validates detailed results and excludes expired entries from a cache snapshot. * - * @since 7.1.0 + * @since 7.3.0 * * @param mixed[] $cached The decoded cache. * @return array The unexpired results and the last detail-update timestamp. @@ -3764,7 +3793,7 @@ private static function normalize_site_status_detail( array $cached ): array { /** * Normalizes a set of aggregate status counts to integers. * - * @since 7.1.0 + * @since 7.3.0 * * @param mixed[] $counts Raw counts that may be missing keys or hold non-integer values. * @return array The good, recommended, and critical counts. @@ -3781,7 +3810,7 @@ private static function normalize_status_counts( array $counts ): array { /** * Counts a set of Site Health results by status. * - * @since 7.1.0 + * @since 7.3.0 * * @param array $results Result arrays, each with a status. * @return array Aggregate counts, one bucket per status. A status other than `recommended` or `critical` counts as `good`. diff --git a/tests/phpunit/tests/admin/wpSiteHealth.php b/tests/phpunit/tests/admin/wpSiteHealth.php index 649bac75bef9a..c71dfd73f9b33 100644 --- a/tests/phpunit/tests/admin/wpSiteHealth.php +++ b/tests/phpunit/tests/admin/wpSiteHealth.php @@ -1211,6 +1211,62 @@ public function test_reading_expired_details_preserves_counts(): void { $this->assertSame( $old, $stored['timestamp'] ); } + /** + * When over the limit, the least useful results are dropped first. + * + * Critical results are kept before recommended ones, and recommended before good. + * Within each status, newer results are kept before older ones. + * + * @ticket 65232 + * @covers ::update_site_status_detail + */ + public function test_update_site_status_detail_limits_stored_results(): void { + $cached = array(); + for ( $i = 0; $i < 500; $i++ ) { + $cached[ "cached_$i" ] = array( + 'status' => 0 === $i ? 'critical' : 'good', + 'timestamp' => time() - 1000 + $i, + ); + } + set_transient( + WP_Site_Health::STATUS_RESULT_TRANSIENT, + wp_json_encode( + array( + 'results' => $cached, + 'timestamp' => time(), + ) + ) + ); + + $this->assertTrue( + WP_Site_Health::update_site_status_detail( + array( + 'cached_2' => array( 'status' => 'recommended' ), + 'submitted' => array( 'status' => 'recommended' ), + ) + ) + ); + $results = WP_Site_Health::get_site_status_detail()['results']; + $this->assertCount( 500, $results ); + $this->assertArrayHasKey( 'cached_0', $results, 'An old critical result must be kept.' ); + $this->assertArrayNotHasKey( 'cached_1', $results, 'The oldest good result must be dropped.' ); + $this->assertSame( 'recommended', $results['cached_2']['status'] ); + $this->assertArrayHasKey( 'submitted', $results ); + + $submitted = array(); + for ( $i = 0; $i < 500; $i++ ) { + $submitted[ "submitted_$i" ] = array( 'status' => 'good' ); + } + $submitted['submitted_critical'] = array( 'status' => 'critical' ); + $this->assertTrue( WP_Site_Health::update_site_status_detail( $submitted ) ); + + $expected = array_merge( + array( 'submitted_critical', 'cached_0', 'cached_2', 'submitted' ), + array_slice( array_keys( $submitted ), 0, 496 ) + ); + $this->assertSame( $expected, array_keys( WP_Site_Health::get_site_status_detail()['results'] ) ); + } + /** * An unchanged cache is a success, but a failed write must still report an error. * diff --git a/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php b/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php index d7bfd35aae641..3ddc082715aac 100644 --- a/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php +++ b/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php @@ -11,7 +11,7 @@ * * @package WordPress * @subpackage UnitTests - * @since 7.1.0 + * @since 7.3.0 * * @group ajax * @group site-health From d3e2cf06817c4759b6ab469c1ef7f74fce88fc22 Mon Sep 17 00:00:00 2001 From: Grzegorz Ziolkowski Date: Fri, 30 Oct 2026 16:59:23 +0100 Subject: [PATCH 45/51] Site Health: Make status cache tests work with an object cache. With an external object cache, transients are not stored in the options table. Only check autoloading when the database stores the transient, and skip the write failure test, which blocks an option update. Co-Authored-By: Claude Opus 5.5 --- tests/phpunit/tests/admin/wpSiteHealth.php | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/tests/phpunit/tests/admin/wpSiteHealth.php b/tests/phpunit/tests/admin/wpSiteHealth.php index c71dfd73f9b33..023e075245722 100644 --- a/tests/phpunit/tests/admin/wpSiteHealth.php +++ b/tests/phpunit/tests/admin/wpSiteHealth.php @@ -850,8 +850,11 @@ public function test_scheduled_check_stores_counts_and_detail_together(): void { $this->assertSame( 1, $stored['good'] ); $this->assertSame( 1, $stored['recommended'] ); $this->assertSame( 1, $stored['critical'] ); - $this->assertArrayHasKey( '_transient_' . WP_Site_Health::STATUS_RESULT_TRANSIENT, wp_load_alloptions() ); - $this->assertFalse( get_option( '_transient_timeout_' . WP_Site_Health::STATUS_RESULT_TRANSIENT ) ); + // An external object cache stores transients outside of the options table. + if ( ! wp_using_ext_object_cache() ) { + $this->assertArrayHasKey( '_transient_' . WP_Site_Health::STATUS_RESULT_TRANSIENT, wp_load_alloptions() ); + $this->assertFalse( get_option( '_transient_timeout_' . WP_Site_Health::STATUS_RESULT_TRANSIENT ) ); + } // The detailed cache holds every result, including the passing one. $detail = WP_Site_Health::get_site_status_detail(); @@ -1274,6 +1277,10 @@ public function test_update_site_status_detail_limits_stored_results(): void { * @covers ::set_site_status_counts */ public function test_cache_write_failure_returns_error(): void { + if ( wp_using_ext_object_cache() ) { + $this->markTestSkipped( 'This test requires that an external object cache is not in use.' ); + } + $counts = array( 'good' => 1, 'recommended' => 0, From cc46473a5dec190cca951eb72f354e74b9a126c6 Mon Sep 17 00:00:00 2001 From: Grzegorz Ziolkowski Date: Fri, 30 Oct 2026 17:02:52 +0100 Subject: [PATCH 46/51] Site Health: Move the status cache autoload check to its own test. The new test is skipped with an external object cache, so the scheduled check test no longer needs conditional assertions. Co-Authored-By: Claude Opus 5.5 --- tests/phpunit/tests/admin/wpSiteHealth.php | 31 ++++++++++++++++++---- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/tests/phpunit/tests/admin/wpSiteHealth.php b/tests/phpunit/tests/admin/wpSiteHealth.php index 023e075245722..2194495704295 100644 --- a/tests/phpunit/tests/admin/wpSiteHealth.php +++ b/tests/phpunit/tests/admin/wpSiteHealth.php @@ -850,11 +850,6 @@ public function test_scheduled_check_stores_counts_and_detail_together(): void { $this->assertSame( 1, $stored['good'] ); $this->assertSame( 1, $stored['recommended'] ); $this->assertSame( 1, $stored['critical'] ); - // An external object cache stores transients outside of the options table. - if ( ! wp_using_ext_object_cache() ) { - $this->assertArrayHasKey( '_transient_' . WP_Site_Health::STATUS_RESULT_TRANSIENT, wp_load_alloptions() ); - $this->assertFalse( get_option( '_transient_timeout_' . WP_Site_Health::STATUS_RESULT_TRANSIENT ) ); - } // The detailed cache holds every result, including the passing one. $detail = WP_Site_Health::get_site_status_detail(); @@ -890,6 +885,32 @@ public function test_scheduled_check_stores_counts_and_detail_together(): void { ); } + /** + * The shared transient has no expiration, so the database stores it as an autoloaded option. + * + * @ticket 65232 + * + * @covers ::update_site_status_detail + */ + public function test_status_cache_is_autoloaded_without_expiration(): void { + if ( wp_using_ext_object_cache() ) { + $this->markTestSkipped( 'This test requires that an external object cache is not in use.' ); + } + + $this->assertTrue( + WP_Site_Health::update_site_status_detail( + array( 'fake_good' => array( 'status' => 'good' ) ), + array( + 'good' => 1, + 'recommended' => 0, + 'critical' => 0, + ) + ) + ); + $this->assertArrayHasKey( '_transient_' . WP_Site_Health::STATUS_RESULT_TRANSIENT, wp_load_alloptions() ); + $this->assertFalse( get_option( '_transient_timeout_' . WP_Site_Health::STATUS_RESULT_TRANSIENT ) ); + } + /** * Only valid results are cached. The scheduled check ignores invalid results * returned by the result filter, while direct updates return a validation error. From af708b46d7618af2f6cca6eff7aab2e536ade08d Mon Sep 17 00:00:00 2001 From: Grzegorz Ziolkowski Date: Fri, 30 Oct 2026 17:09:01 +0100 Subject: [PATCH 47/51] Site Health: Reject unsupported statuses and string results in the cache. The screen now ignores results with a status other than good, recommended, or critical. Before, one such result made the server reject the whole cache update, so the counts were not saved either. The cache reader also checks that the stored results are an array. Schema validation accepts an empty string as an empty object, so a corrupted cache could cause a TypeError. Co-Authored-By: Claude Opus 5.5 --- src/js/_enqueues/admin/site-health.js | 8 ++++++++ src/wp-admin/includes/class-wp-site-health.php | 6 +++++- tests/phpunit/tests/admin/wpSiteHealth.php | 15 +++++++++++++++ tests/qunit/index.html | 6 ++++++ 4 files changed, 34 insertions(+), 1 deletion(-) diff --git a/src/js/_enqueues/admin/site-health.js b/src/js/_enqueues/admin/site-health.js index b3dd959532a82..f20ac9f42e5b7 100644 --- a/src/js/_enqueues/admin/site-health.js +++ b/src/js/_enqueues/admin/site-health.js @@ -107,6 +107,14 @@ jQuery( function( $ ) { return false; } + /* + * Only these statuses have a section on the screen and are accepted by the + * server-side cache. Any other status would make the whole cache update fail. + */ + if ( -1 === [ 'good', 'recommended', 'critical' ].indexOf( issue.status ) ) { + return false; + } + // Loop over expected data and match the data types. for ( key in minimumExpected ) { value = minimumExpected[ key ]; diff --git a/src/wp-admin/includes/class-wp-site-health.php b/src/wp-admin/includes/class-wp-site-health.php index 589bc8022f000..f290330dbc258 100644 --- a/src/wp-admin/includes/class-wp-site-health.php +++ b/src/wp-admin/includes/class-wp-site-health.php @@ -3769,7 +3769,11 @@ private static function read_site_status_cache(): array { * @phpstan-return Stored_Test_Results */ private static function normalize_site_status_detail( array $cached ): array { - if ( is_wp_error( rest_validate_value_from_schema( $cached, self::STORED_STATUS_SCHEMA ) ) ) { + // The schema validation accepts an empty string as an empty object, so check the type too. + if ( + is_wp_error( rest_validate_value_from_schema( $cached, self::STORED_STATUS_SCHEMA ) ) + || ! is_array( $cached['results'] ) + ) { $cached = array( 'results' => array(), 'timestamp' => 0, diff --git a/tests/phpunit/tests/admin/wpSiteHealth.php b/tests/phpunit/tests/admin/wpSiteHealth.php index 2194495704295..1c482f57d9c47 100644 --- a/tests/phpunit/tests/admin/wpSiteHealth.php +++ b/tests/phpunit/tests/admin/wpSiteHealth.php @@ -1131,6 +1131,21 @@ public function test_get_site_status_detail_distinguishes_empty_from_missing_or_ $this->assertSame( array(), $detail['results'] ); $this->assertSame( 0, $detail['timestamp'] ); + // The schema validation accepts an empty string as an object, but it must not reach the reader. + set_transient( + WP_Site_Health::STATUS_RESULT_TRANSIENT, + wp_json_encode( + array( + 'results' => '', + 'timestamp' => $now, + ) + ) + ); + + $detail = WP_Site_Health::get_site_status_detail(); + $this->assertSame( array(), $detail['results'] ); + $this->assertSame( 0, $detail['timestamp'] ); + set_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT, wp_json_encode( diff --git a/tests/qunit/index.html b/tests/qunit/index.html index 16c0275606fe7..d9d0f5ddabafa 100644 --- a/tests/qunit/index.html +++ b/tests/qunit/index.html @@ -151,6 +151,12 @@ description: 'An invalid test description.', label: 'An invalid test without an identifier', status: 'critical' + }, + { + description: 'An unsupported status description.', + label: 'An invalid test with an unsupported status', + status: 'info', + test: 'unsupported_status_test' } ], results: {} From 7e7e486b09cf8004a58eadd54739eb3d382b8eb6 Mon Sep 17 00:00:00 2001 From: Grzegorz Ziolkowski Date: Fri, 30 Oct 2026 17:16:40 +0100 Subject: [PATCH 48/51] Site Health: Clarify that the result limit does not bound cache bytes. --- src/wp-admin/includes/class-wp-site-health.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/wp-admin/includes/class-wp-site-health.php b/src/wp-admin/includes/class-wp-site-health.php index f290330dbc258..c67e369cff043 100644 --- a/src/wp-admin/includes/class-wp-site-health.php +++ b/src/wp-admin/includes/class-wp-site-health.php @@ -55,9 +55,9 @@ class WP_Site_Health { /* * Maximum number of detailed results kept in the autoloaded transient. Core - * registers about 30 tests, so real sites stay far below this limit. It only - * guards against runaway growth. Each entry takes about 60 bytes, so the - * results stay around 30 KB at most. + * registers about 30 tests. This limits growth in the number of entries, but + * does not impose a byte-size limit: the payload also depends on the length + * of test identifiers. */ private const MAX_STORED_RESULTS = 500; From e9d307bed15a28876310233536cb22e88a0071c8 Mon Sep 17 00:00:00 2001 From: Grzegorz Ziolkowski Date: Fri, 30 Oct 2026 17:19:34 +0100 Subject: [PATCH 49/51] Site Health: Simplify cache initialization and clarify eviction ordering. --- src/js/_enqueues/admin/site-health.js | 2 +- .../includes/class-wp-site-health.php | 32 +++++++++---------- 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/src/js/_enqueues/admin/site-health.js b/src/js/_enqueues/admin/site-health.js index f20ac9f42e5b7..05552fc7da87c 100644 --- a/src/js/_enqueues/admin/site-health.js +++ b/src/js/_enqueues/admin/site-health.js @@ -266,7 +266,7 @@ jQuery( function( $ ) { } if ( isStatusTab ) { - // Save counts and verified results together in the shared cache. + // One request avoids competing counts-only and results-only updates to the shared cache. $.post( ajaxurl, { diff --git a/src/wp-admin/includes/class-wp-site-health.php b/src/wp-admin/includes/class-wp-site-health.php index c67e369cff043..bf41436517691 100644 --- a/src/wp-admin/includes/class-wp-site-health.php +++ b/src/wp-admin/includes/class-wp-site-health.php @@ -192,17 +192,11 @@ public function enqueue_scripts() { 'site_status' => array( 'direct' => array(), 'async' => array(), - 'issues' => array( - 'good' => 0, - 'recommended' => 0, - 'critical' => 0, - ), + 'issues' => self::get_site_status_counts(), 'results' => new stdClass(), ), ); - $health_check_js_variables['site_status']['issues'] = self::get_site_status_counts(); - if ( 'site-health' === $screen->id && ( ! isset( $_GET['tab'] ) || empty( $_GET['tab'] ) ) ) { $tests = WP_Site_Health::get_tests(); @@ -3565,12 +3559,8 @@ public function wp_cron_scheduled_check() { } /* - * Cache the compact results, keyed by test, so consumers can read the - * detailed Site Health status without re-running the tests. - * - * Only verified results are included. An unavailable asynchronous test is still - * reflected in the aggregate counts, but does not replace a previously verified - * detailed result. + * An unavailable test affects this run's counts but must not replace a + * previously verified result, so only verified results are merged into details. */ self::update_site_status_detail( $results_to_store, $counts ); } @@ -3580,7 +3570,8 @@ public function wp_cron_scheduled_check() { * * @since 7.3.0 * - * @return Test_Status_Counts Aggregate counts. Each value is `0` when no result has been cached. + * @return array Aggregate counts. Each value is `0` when no result has been cached. + * @phpstan-return Test_Status_Counts */ public static function get_site_status_counts(): array { $counts = self::read_site_status_cache(); @@ -3705,8 +3696,17 @@ public static function update_site_status_detail( array $results, ?array $counts uksort( $cached['results'], static function ( $a, $b ) use ( $unsorted, $priority, $position ) { - return array( $priority[ $unsorted[ $a ]['status'] ], $unsorted[ $b ]['timestamp'], $position[ $a ] ) - <=> array( $priority[ $unsorted[ $b ]['status'] ], $unsorted[ $a ]['timestamp'], $position[ $b ] ); + $status_order = $priority[ $unsorted[ $a ]['status'] ] <=> $priority[ $unsorted[ $b ]['status'] ]; + if ( 0 !== $status_order ) { + return $status_order; + } + + $newest_first = $unsorted[ $b ]['timestamp'] <=> $unsorted[ $a ]['timestamp']; + if ( 0 !== $newest_first ) { + return $newest_first; + } + + return $position[ $a ] <=> $position[ $b ]; } ); $cached['results'] = array_slice( $cached['results'], 0, self::MAX_STORED_RESULTS, true ); From 8a4f63d2c2266ad4664d2374df1e70e504758789 Mon Sep 17 00:00:00 2001 From: Grzegorz Ziolkowski Date: Mon, 2 Nov 2026 15:56:53 +0100 Subject: [PATCH 50/51] Site Health: Derive displayed counts from cached results. --- src/wp-admin/includes/ajax-actions.php | 4 +- .../includes/class-wp-site-health.php | 32 +++-- src/wp-admin/includes/dashboard.php | 24 ++-- src/wp-admin/menu.php | 17 +-- tests/phpunit/tests/admin/wpSiteHealth.php | 112 ++++++++++++++++-- .../wpAjaxHealthCheckSiteStatusResult.php | 12 +- 6 files changed, 148 insertions(+), 53 deletions(-) diff --git a/src/wp-admin/includes/ajax-actions.php b/src/wp-admin/includes/ajax-actions.php index c7c7fecc0f1d5..5d87ac2d04182 100644 --- a/src/wp-admin/includes/ajax-actions.php +++ b/src/wp-admin/includes/ajax-actions.php @@ -5449,7 +5449,9 @@ function wp_ajax_health_check_loopback_requests() { * Handles site health check to update the result status via AJAX. * * Counts and compact per-test results are saved together. Counts-only requests - * remain supported for compatibility, and results-only requests preserve counts. + * remain supported for compatibility, and results-only requests preserve stored counts. + * Core readers calculate counts from valid, unexpired per-test results when available; + * the stored counts remain for consumers that read the transient directly. * * @since 5.2.0 * @since 7.3.0 The submitted counts are validated, and optional per-test statuses diff --git a/src/wp-admin/includes/class-wp-site-health.php b/src/wp-admin/includes/class-wp-site-health.php index bf41436517691..7e4c4c3f5e6a5 100644 --- a/src/wp-admin/includes/class-wp-site-health.php +++ b/src/wp-admin/includes/class-wp-site-health.php @@ -111,8 +111,9 @@ class WP_Site_Health { /** * Transient name for the cached Site Health counts and verified test results. * - * The existing top-level counts describe the latest run, including unavailable - * tests. Compact, locale-independent results retain each test's latest verified + * The top-level counts describe the latest run, including unavailable tests, + * and remain stored for consumers that read the transient directly. Core readers derive counts from + * the compact, locale-independent results, which retain each test's latest verified * status. This transient remains autoloaded for the admin menu and Dashboard. * * @since 7.3.0 @@ -3566,7 +3567,13 @@ public function wp_cron_scheduled_check() { } /** - * Returns the cached aggregate Site Health status counts. + * Calculates Site Health status counts from unexpired cached results. + * + * Stored aggregate counts are only used for caches without valid detailed results, + * including legacy counts-only values. An empty or fully expired set of valid + * detailed results returns zero counts instead of falling back to stored counts. + * The fallback preserves compatibility; it does not imply that stored counts + * are newer or more accurate than the detailed results. * * @since 7.3.0 * @@ -3575,6 +3582,11 @@ public function wp_cron_scheduled_check() { */ public static function get_site_status_counts(): array { $counts = self::read_site_status_cache(); + $detail = self::normalize_site_status_detail( $counts ); + if ( $detail['timestamp'] > 0 ) { + return self::count_site_status_results( $detail['results'] ); + } + if ( is_wp_error( rest_validate_value_from_schema( $counts, self::STATUS_COUNTS_SCHEMA ) ) ) { $counts = array(); } @@ -3586,6 +3598,8 @@ public static function get_site_status_counts(): array { * Caches the aggregate Site Health status counts. * * Preserves unexpired verified results and their collection timestamps. + * These stored counts are retained for backward compatibility; readers derive + * counts from valid detailed results when available. * * @since 7.3.0 * @@ -3607,9 +3621,9 @@ public static function set_site_status_counts( array $counts ) { * Returns the cached detailed Site Health test results. * * The `counts` are derived from the cached `results`, so the two are always - * internally consistent. They may differ from WP_Site_Health::get_site_status_counts(), - * which reflects the latest run for the admin menu and Dashboard. Consumers that need a - * consistent view of counts and detailed results should read both from here. + * internally consistent. WP_Site_Health::get_site_status_counts() uses the same + * calculation when valid detailed results are available, falling back to stored + * counts only for caches without valid details, including legacy counts-only values. * Results older than a month are excluded even when no writer has refreshed * the autoloaded transient. * @@ -3639,8 +3653,10 @@ public static function get_site_status_detail(): array { * dropped, for example when the plugin that registered a test has been deactivated. * At most 500 results are kept. When there are more, critical results are kept * first, then recommended, then good, and the newest results within each status. - * Optional latest-run counts are validated and saved in the same write. When - * omitted, the existing counts are preserved. + * Optional latest-run counts are validated and saved in the same write for + * consumers that read the transient directly. When omitted, the stored counts + * are preserved. Core readers calculate counts from the retained, unexpired + * results instead, so expiry and the storage limit also affect those counts. * * @since 7.3.0 * diff --git a/src/wp-admin/includes/dashboard.php b/src/wp-admin/includes/dashboard.php index 3e0d28d7f85f1..b5bdee537d505 100644 --- a/src/wp-admin/includes/dashboard.php +++ b/src/wp-admin/includes/dashboard.php @@ -2214,22 +2214,12 @@ function dashboard_php_nag_class( $classes ) { * @since 5.4.0 */ function wp_dashboard_site_health() { - $get_issues = get_transient( 'health-check-site-status-result' ); - - $issue_counts = array(); - - if ( false !== $get_issues ) { - $issue_counts = json_decode( $get_issues, true ); - } - - if ( ! is_array( $issue_counts ) || ! $issue_counts ) { - $issue_counts = array( - 'good' => 0, - 'recommended' => 0, - 'critical' => 0, - ); + if ( ! class_exists( 'WP_Site_Health' ) ) { + require_once ABSPATH . 'wp-admin/includes/class-wp-site-health.php'; } + $issue_counts = WP_Site_Health::get_site_status_counts(); + $has_results = array_sum( $issue_counts ) > 0; $issues_total = $issue_counts['recommended'] + $issue_counts['critical']; ?>
@@ -2241,7 +2231,7 @@ function wp_dashboard_site_health() {
- + @@ -2250,7 +2240,7 @@ function wp_dashboard_site_health() {
- +

- 0 && false !== $get_issues ) : ?> + 0 && $has_results ) : ?>

0, - 'recommended' => 0, - 'critical' => 0, - ); + if ( ! class_exists( 'WP_Site_Health' ) ) { + require_once ABSPATH . 'wp-admin/includes/class-wp-site-health.php'; } + $issue_counts = WP_Site_Health::get_site_status_counts(); $site_health_count = sprintf( '%s', diff --git a/tests/phpunit/tests/admin/wpSiteHealth.php b/tests/phpunit/tests/admin/wpSiteHealth.php index 1c482f57d9c47..25abb83dc6b26 100644 --- a/tests/phpunit/tests/admin/wpSiteHealth.php +++ b/tests/phpunit/tests/admin/wpSiteHealth.php @@ -1041,7 +1041,10 @@ public function test_scheduled_check_preserves_verified_result_when_async_test_i $this->assertArrayHasKey( 'my_async', $results_by_id ); $this->assertSame( 'good', $results_by_id['my_async']['status'] ); $this->assertSame( $cached_at, $results_by_id['my_async']['timestamp'] ); - $this->assertSame( 1, WP_Site_Health::get_site_status_counts()['recommended'] ); + $this->assertSame( 0, WP_Site_Health::get_site_status_counts()['recommended'] ); + $this->assertSame( $detail['counts'], WP_Site_Health::get_site_status_counts() ); + $stored = json_decode( get_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ), true ); + $this->assertSame( 1, $stored['recommended'], 'Unavailable tests remain in the stored counts for compatibility.' ); } /** @@ -1166,14 +1169,75 @@ public function test_get_site_status_detail_distinguishes_empty_from_missing_or_ } /** - * Old counts-only values can be extended without changing the existing counts. + * An empty detailed cache must not revive stored counts. + * + * @ticket 65232 + * @covers ::get_site_status_counts + */ + public function test_empty_details_override_stored_counts(): void { + $this->assertTrue( + WP_Site_Health::update_site_status_detail( + array(), + array( + 'good' => 5, + 'recommended' => 2, + 'critical' => 1, + ) + ) + ); + $this->assertSame( + array( + 'good' => 0, + 'recommended' => 0, + 'critical' => 0, + ), + WP_Site_Health::get_site_status_counts() + ); + } + + /** + * The Dashboard counts verified results and treats expired results as unavailable. + * + * @ticket 65232 + * @covers ::get_site_status_counts + * @covers ::get_site_status_detail + * @covers \wp_dashboard_site_health + */ + public function test_dashboard_uses_unexpired_result_counts(): void { + require_once ABSPATH . 'wp-admin/includes/dashboard.php'; + + $this->assertTrue( + WP_Site_Health::update_site_status_detail( + array( 'verified' => array( 'status' => 'critical' ) ), + array( + 'good' => 5, + 'recommended' => 0, + 'critical' => 0, + ) + ) + ); + $output = get_echo( 'wp_dashboard_site_health' ); + $this->assertStringContainsString( 'Your site has a critical issue', $output ); + $this->assertStringNotContainsString( 'Great job!', $output ); + + $stored = json_decode( get_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ), true ); + $stored['results']['verified']['timestamp'] = time() - MONTH_IN_SECONDS - 10; + set_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT, wp_json_encode( $stored ) ); + + $output = get_echo( 'wp_dashboard_site_health' ); + $this->assertStringContainsString( 'No information yet', $output ); + $this->assertStringNotContainsString( 'Great job!', $output ); + } + + /** + * Old counts remain stored for compatibility, but readers count detailed results once available. * * @ticket 65232 * @covers ::update_site_status_detail * @covers ::set_site_status_counts * @covers ::get_site_status_counts */ - public function test_extending_legacy_counts_preserves_each_kind_of_data(): void { + public function test_extending_legacy_counts_switches_readers_to_detailed_results(): void { $counts = array( 'good' => 9, 'recommended' => 2, @@ -1186,24 +1250,40 @@ public function test_extending_legacy_counts_preserves_each_kind_of_data(): void $reads_before = did_filter( 'pre_transient_' . WP_Site_Health::STATUS_RESULT_TRANSIENT ); $this->assertTrue( WP_Site_Health::update_site_status_detail( array( 'verified' => array( 'status' => 'good' ) ) ) ); $this->assertSame( 1, did_filter( 'pre_transient_' . WP_Site_Health::STATUS_RESULT_TRANSIENT ) - $reads_before, 'A results-only update should read the shared cache once.' ); - $this->assertSame( $counts, WP_Site_Health::get_site_status_counts() ); + $this->assertSame( + array( + 'good' => 1, + 'recommended' => 0, + 'critical' => 0, + ), + WP_Site_Health::get_site_status_counts() + ); $detail = WP_Site_Health::get_site_status_detail(); $counts['critical'] = 3; $this->assertTrue( WP_Site_Health::set_site_status_counts( $counts ) ); $this->assertSame( $detail, WP_Site_Health::get_site_status_detail() ); - $this->assertSame( $counts, WP_Site_Health::get_site_status_counts() ); + $this->assertSame( + array( + 'good' => 1, + 'recommended' => 0, + 'critical' => 0, + ), + WP_Site_Health::get_site_status_counts() + ); + $stored = json_decode( get_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ), true ); + $this->assertSame( $counts, array_intersect_key( $stored, $counts ) ); } /** - * Details expire even without a scheduled update; latest-run counts are retained. + * Counts exclude expired results even without a scheduled update. * * @ticket 65232 * @covers ::get_site_status_detail * @covers ::update_site_status_detail * @covers ::set_site_status_counts */ - public function test_reading_expired_details_preserves_counts(): void { + public function test_reading_expired_details_recalculates_counts(): void { $counts = array( 'good' => 4, 'recommended' => 1, @@ -1231,6 +1311,7 @@ public function test_reading_expired_details_preserves_counts(): void { $this->assertSame( array( 'new' ), array_keys( $detail['results'] ) ); $this->assertSame( 1, $detail['counts']['good'] ); $this->assertSame( 0, $detail['counts']['critical'] ); + $this->assertSame( $detail['counts'], WP_Site_Health::get_site_status_counts() ); $this->assertTrue( WP_Site_Health::update_site_status_detail( array() ) ); $stored = json_decode( get_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ), true ); @@ -1241,7 +1322,14 @@ public function test_reading_expired_details_preserves_counts(): void { set_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT, wp_json_encode( $status ) ); $this->assertSame( array(), WP_Site_Health::get_site_status_detail()['results'] ); $this->assertSame( $old, WP_Site_Health::get_site_status_detail()['timestamp'] ); - $this->assertSame( $counts, WP_Site_Health::get_site_status_counts() ); + $this->assertSame( + array( + 'good' => 0, + 'recommended' => 0, + 'critical' => 0, + ), + WP_Site_Health::get_site_status_counts() + ); // A counts-only update must prune expired details without refreshing their age. $this->assertTrue( WP_Site_Health::set_site_status_counts( $counts ) ); @@ -1291,6 +1379,14 @@ public function test_update_site_status_detail_limits_stored_results(): void { $this->assertArrayNotHasKey( 'cached_1', $results, 'The oldest good result must be dropped.' ); $this->assertSame( 'recommended', $results['cached_2']['status'] ); $this->assertArrayHasKey( 'submitted', $results ); + $this->assertSame( + array( + 'good' => 497, + 'recommended' => 2, + 'critical' => 1, + ), + WP_Site_Health::get_site_status_counts() + ); $submitted = array(); for ( $i = 0; $i < 500; $i++ ) { diff --git a/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php b/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php index 3ddc082715aac..b63d9664801b5 100644 --- a/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php +++ b/tests/phpunit/tests/ajax/wpAjaxHealthCheckSiteStatusResult.php @@ -102,7 +102,9 @@ public function test_posting_counts_and_results_caches_them_together(): void { $writes_before = did_action( 'set_transient_' . WP_Site_Health::STATUS_RESULT_TRANSIENT ); $this->assertTrue( $this->dispatch_result_request()['success'] ); $this->assertSame( 1, did_action( 'set_transient_' . WP_Site_Health::STATUS_RESULT_TRANSIENT ) - $writes_before ); - $this->assertSame( $_POST['counts'], WP_Site_Health::get_site_status_counts() ); + $stored = json_decode( get_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ), true ); + $this->assertSame( $_POST['counts'], array_intersect_key( $stored, $_POST['counts'] ) ); + $this->assertSame( WP_Site_Health::get_site_status_detail()['counts'], WP_Site_Health::get_site_status_counts() ); $detail = WP_Site_Health::get_site_status_detail(); $this->assertSame( array( 'a' ), array_keys( $detail['results'] ) ); $this->assertSame( 'critical', $detail['results']['a']['status'] ); @@ -121,7 +123,7 @@ public function test_posting_counts_and_results_caches_them_together(): void { * * @ticket 65232 */ - public function test_posting_results_only_updates_detail_without_counts(): void { + public function test_posting_results_only_updates_calculated_counts(): void { delete_transient( WP_Site_Health::STATUS_RESULT_TRANSIENT ); $this->set_user_with_site_health_capability(); @@ -136,12 +138,12 @@ public function test_posting_results_only_updates_detail_without_counts(): void $results = WP_Site_Health::get_site_status_detail()['results']; $this->assertSame( array( 'a' ), array_keys( $results ) ); - // Results-only requests preserve the default counts. + // Readers calculate counts from the posted results. $this->assertSame( array( 'good' => 0, 'recommended' => 0, - 'critical' => 0, + 'critical' => 1, ), WP_Site_Health::get_site_status_counts() ); @@ -170,7 +172,7 @@ public function test_posting_counts_only_leaves_detail_intact(): void { $this->assertSame( array( - 'good' => 3, + 'good' => 1, 'recommended' => 0, 'critical' => 0, ), From 0083902011897469ff689334d37874269b8dfd04 Mon Sep 17 00:00:00 2001 From: Grzegorz Ziolkowski Date: Mon, 2 Nov 2026 16:02:34 +0100 Subject: [PATCH 51/51] Site Health: Reject blank test identifiers before caching results. --- src/js/_enqueues/admin/site-health.js | 5 +++++ tests/qunit/index.html | 12 ++++++++++++ tests/qunit/wp-admin/js/site-health.js | 2 +- 3 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/js/_enqueues/admin/site-health.js b/src/js/_enqueues/admin/site-health.js index 05552fc7da87c..063aac481b257 100644 --- a/src/js/_enqueues/admin/site-health.js +++ b/src/js/_enqueues/admin/site-health.js @@ -115,6 +115,11 @@ jQuery( function( $ ) { return false; } + // A blank identifier would cause the server to reject the entire cache update. + if ( 'string' !== typeof issue.test || '' === issue.test.trim() ) { + return false; + } + // Loop over expected data and match the data types. for ( key in minimumExpected ) { value = minimumExpected[ key ]; diff --git a/tests/qunit/index.html b/tests/qunit/index.html index d9d0f5ddabafa..fff6a71cfd6d0 100644 --- a/tests/qunit/index.html +++ b/tests/qunit/index.html @@ -157,6 +157,18 @@ label: 'An invalid test with an unsupported status', status: 'info', test: 'unsupported_status_test' + }, + { + description: 'An empty identifier.', + label: 'An invalid test with an empty identifier', + status: 'critical', + test: '' + }, + { + description: 'A whitespace-only identifier.', + label: 'An invalid test with a blank identifier', + status: 'recommended', + test: ' \t\n\r ' } ], results: {} diff --git a/tests/qunit/wp-admin/js/site-health.js b/tests/qunit/wp-admin/js/site-health.js index 8d3c17d8ec9f3..2208166d17026 100644 --- a/tests/qunit/wp-admin/js/site-health.js +++ b/tests/qunit/wp-admin/js/site-health.js @@ -9,7 +9,7 @@ QUnit.module( 'Site Health', function() { status: 'good' } }, - 'The test results contain locale-independent data.' + 'The test results contain locale-independent data and exclude missing, empty, and whitespace-only identifiers.' ); assert.deepEqual( SiteHealth.site_status.issues,