Repository navigation
Conversation
|
The following accounts have interacted with this PR and/or linked issues. I will continue to update these lists as activity occurs. Core Committers: Use this line as a base for the props when committing in SVN: To understand the WordPress project's expectations around crediting contributors, please review the Contributor Attribution page in the Core Handbook. Props Bot commandsYou can trigger Props Bot actions by commenting on this PR:
|
This comment was marked as outdated.
This comment was marked as outdated.
Test using WordPress PlaygroundThe changes in this pull request can previewed and tested using a WordPress Playground instance. WordPress Playground is an experimental project that creates a full WordPress instance entirely within the browser. Some things to be aware of
For more details about these limitations and more, check out the Limitations page in the WordPress Playground documentation. |
westonruter
left a comment
There was a problem hiding this comment.
In addition to my comment about letting the ajax-stored result be preferred, here's a critical observation that Claude made: the lack of an $expiration means that the transient will be autoloaded.
Since it now includes all of the results which could potentially be large, this would run the risk of increasing the bucket of autoloaded options beyond the 1MB limit imposed by Memcached, right?
Full review from Claude
Confirmed the critical detail: set_transient() is called with no expiration ($expiration = 0), so without an external object cache the option is stored with $autoload = true (option.php:1547-1552). The full results blob is therefore autoloaded on every page load site-wide, not just on Site Health screens. That makes the size concern much more severe than the finders estimated.
I have enough verified context. Here are the findings, ranked most-severe first.
Code Review: PR #12181 — Cache Site Health full results + timestamp
Findings
1. Full results blob is autoloaded on every page request (perf regression) — class-wp-site-health.php:3492
set_transient( 'health-check-site-status-result', wp_json_encode( $site_status ) ) is called with no expiration. With no external object cache, set_transient() stores the option with autoload = true (option.php:1547-1552). Previously the value was ~60 bytes (three ints); now it's the entire $results array including every test's HTML description, actions, and badge. That payload is now loaded into memory on every front-end and admin request for every visitor, via wp_load_alloptions() — a site-wide cost paid to store data only the Site Health screen reads (and only the 3 counts from it). Passing an expiration, or storing under a non-autoloaded option, would avoid this.
2. Large results payload can exceed object-cache item limits → counter silently reverts to 0 — class-wp-site-health.php:3489
On installs with a persistent object cache (e.g. Memcached, default 1MB item limit), a site with many site_status_tests (plugins add them, with arbitrary HTML) can produce a JSON blob exceeding the backend's per-item limit. wp_cache_set() then silently fails, get_transient() returns false, and the admin-menu/dashboard counters fall back to 0/0/0 even though valid counts existed. No size cap or truncation is applied.
3. Race between scheduled cron and the AJAX counts update can discard freshly collected results — src/wp-admin/includes/ajax-actions.php:5488
The AJAX handler does a non-atomic read-modify-write: it reads the cached transient, splices in the POSTed counts, and re-writes. If wp_cron_scheduled_check() writes fresh results between the handler's get_transient() and set_transient() (admin loads Site Health while cron runs), the handler overwrites with the older (or absent) results it read earlier — silently dropping the detailed results the ticket exists to preserve, until the next weekly cron.
4. New status guard miscounts unknown/empty statuses and diverges from results count — class-wp-site-health.php:3471
The guard if ( ! is_array( $result ) || ! isset( $result['status'] ) ) continue; only checks that status is set. A result with status => '' or a custom value like 'info' still falls through to the final else and increments good, mislabeling it as a passing check. Separately, a result missing status was previously counted as good (old loop had no guard) but is now skipped entirely — so the cached results array length (e.g. 3) can no longer equal good + recommended + critical, which will surprise any consumer that assumes they match.
5. timestamp freshness mechanism is half-built — class-wp-site-health.php:3490
The comment says the timestamp lets freshness "be evaluated," but: the transient is set with no expiry, nothing in core ever compares the timestamp to now, and the AJAX handler preserves the old cron timestamp on every counts update (ajax-actions.php:5495-5497). So the stored timestamp reflects the last full cron run, not the last update — any future freshness check built on it would be subtly wrong, and the promised mechanism doesn't actually exist yet.
6. Payload schema duplicated across writers/readers with no canonical accessor — src/wp-admin/includes/ajax-actions.php:5477
The count-normalization array( 'good' => (int) ( $x['good'] ?? 0 ), 'recommended' => …, 'critical' => … ) is copied verbatim into ajax-actions.php:5477-5481 and class-wp-site-health.php:126-130, and the get_transient() + json_decode( …, true ) idiom is duplicated too. The transient's shape is now defined by convention across five sites (cron writer, ajax merge, enqueue reader, menu.php, dashboard.php). Adding a status bucket or renaming a key requires editing several hand-maintained literals; missing one yields counts that silently disagree between the menu counter, dashboard widget, and Site Health screen. A single read/write/normalize helper would centralize it.
7. Enqueue decodes the entire results blob just to read three integers — class-wp-site-health.php:117
On every Site Health and Dashboard page render, json_decode() parses the full cached payload (all HTML results) only to extract good/recommended/critical — the comment itself notes "only the aggregate counts are needed." The decode cost scales with the size/number of test results, for no benefit. (Mitigated if findings 1 & 2 are addressed by not storing results in the same hot transient.)
8. AJAX handler re-encodes the full results blob on every counts POST — src/wp-admin/includes/ajax-actions.php:5501
Each time an admin loads the Site Health Status tab, the JS posts the counts and this handler reads, decodes, and re-wp_json_encode()s the entire results payload back into the transient — repeated large serialization writes per page view, not just per weekly cron run (write amplification).
Note on a dropped candidate: finders flagged wp_json_encode( $site_status ) returning false (and storing false) on invalid UTF-8 in result HTML. I refuted it — wp_json_encode() runs _wp_json_sanity_check()/_wp_json_convert_string() to repair invalid UTF-8 and re-encode (functions.php:4411-4417), so the common case recovers; only a >512-depth structure would fail, which Site Health results never reach.
Findings 1–4 are the ones I'd block on; finding 1 in particular looks like a meaningful site-wide performance regression worth raising on the PR. Want me to post these as inline PR comments (/code-review --comment) or open a discussion on the specific lines?
|
Thanks for the review! Reworked this substantially in 5bb9fee and updated the PR description. Key change: counts stay in the small autoloaded transient, full results move to a separate non-autoloaded detail cache — which also clears the race and write-amplification points. The Site Health screen is now authoritative for the detailed results (incl. async tests) with cron as a backstop, plus per-result timestamps. Two design calls I'd value your take on before going further: the merge policy (1-week grace window vs. browser strictly outranking cron) and whether to cap the detail-cache size. Both noted in the description. Disclosure: I used Claude Code and Codex to develop and validate these changes (reviewed and verified by me). 🙏 |
5bb9fee to
70b0566
Compare
Related to this, my suggestion to reduce the number of stored keys to just |
70b0566 to
3ca1452
Compare
|
Thanks for the thorough review! I have applied all the feedback in the latest commits. A quick summary:
One open question remains: the merge policy when the scheduled check runs after a screen visit. Storing the freshest result is simplest, but cron runs the async tests over loopback, which fails on some hosts and falls back to "unavailable". One option is to let cron overwrite only when it could actually verify the test, instead of the current one-week grace window. Happy to go either way. I also revised the PR description so it reflects the current state of the code. |
|
@westonruter, would you mind doing another review pass to unblock progress on this PR? |
|
@gziolo Sorry for the delay in reviewing. This got lost in the vacation shuffle. I've been working through the PHPStan issues. Here are the remaining ones I haven't addressed yet: |
|
All PHPStan issues are now addressed. I've done some additional factoring. Still some more to do. |
|
Oops. There are two failing tests remaining after my refactoring: |
|
Oh, question: in looking at the ticket, I see the intention is for the ability to include the description showing the site test result? Currently this is omitted in favor of just storing the status enum. Would this be sufficient for the Ability? |
I need to verify if we can compute that dynamically. In fact, these messages are translatable, so it won’t be easy to handle them gracefully to ensure accurate communication when multiple accounts on the site use different locales. It might be sufficient to have the test name and status enum. |
|
I would like to check the status of this PR. Should the following two PRs be closed? |
|
@t-hamano, we will have to move it to 7.2. These two tickets you linked don't look actionable anymore, taking into account that we want to ensure that a proper caching strategy is in place for Site Health checks. |
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
…che. 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 <noreply@anthropic.com>
82e865a to
e9d307b
Compare
|
@westonruter, all review threads are now resolved. Core calculates counts from unexpired cached results, while stored counts remain for backward compatibility. The PR is rebased onto trunk, with tests and documentation updated. Could you take another look? @jorgefilipecosta, could you also review this PR? It’s a prerequisite for including Site Health results in |

Trac ticket: https://core.trac.wordpress.org/ticket/65232
What & why
Consumers need cached per-test Site Health results without re-running synchronous tests. This PR extends the existing
health-check-site-status-resulttransient with compact, locale-independent statuses and collection timestamps. A follow-up can expose these through the Abilities API and resolve labels in the current locale.One autoloaded cache
The existing transient retains its top-level
good,recommended, andcriticalcounts and addsresultsandtimestamp:{ "good": 20, "recommended": 2, "critical": 0, "results": { "<test>": { "status": "good", "timestamp": 1715714399 } }, "timestamp": 1715714399 }There is no separate detail transient. The shared transient has no expiration and remains autoloaded in database-backed storage. Per-test entries contain only a status and timestamp; translated labels, descriptions, actions, and badges are omitted. Core registers about 30 tests.
At most 500 results are stored to limit growth in the number of entries, for example from a buggy client or a plugin that creates test names dynamically. This is not a byte-size limit: the serialized payload also depends on the length of test identifiers. When there are more, critical results are kept first, then recommended, then good. Within each status, newer results are kept first. The top-level counts are not affected by this limit.
The admin-menu, Dashboard, and Site Health readers use
WP_Site_Health::get_site_status_counts()to calculate counts from unexpired cached results. Old counts-only cache values remain supported.How counts are read
Core calculates counts from the retained, unexpired per-test results. The admin menu, Dashboard, and Site Health use the same calculation as
get_site_status_detail(), so counts match the available results. Expiry and the 500-result storage limit affect these calculated counts.The top-level
good,recommended, andcriticalfields remain in the transient for backward compatibility with consumers that read it directly. They still describe the latest run and may differ from the counts calculated from retained results. This fallback preserves compatibility; it does not mean stored counts are newer or more accurate.For example, if cron cannot perform an asynchronous test, its synthetic “A test is unavailable” result remains in the stored latest-run counts but does not overwrite a verified browser result. Core readers now count the retained verified result instead.
Writers and freshness
The update path reuses one decoded cache snapshot. Successful writes avoid an extra transient read; unchanged values are still treated as successful saves.
Accessors
get_site_status_counts()calculates counts from unexpired results, with a stored-count fallback only when valid details are unavailable.set_site_status_counts()updates the stored compatibility counts while preserving unexpired verified results and their timestamps.get_site_status_detail()returns{ results, counts, timestamp }, deriving counts from unexpired verified results.update_site_status_detail( $results, $counts = null )validates, timestamps, merges, and saves results with optional latest-run counts.Validation
Tests cover consistent calculated counts, empty and fully expired results, Dashboard output, preservation of stored compatibility counts, legacy cache upgrades, the combined stored shape and autoloading, cron freshness and unavailable-test fallbacks, read/write expiry, the 500-result limit and its trimming order, partial requests, validation failures without partial saves, capability enforcement, and unchanged/failed writes. Overlapping fixtures and assertions have been consolidated.
Use of AI Tools
AI assistance: Yes
Tool(s): Claude Code, Codex
Used for: Development and validation; reviewed and verified by me.