Opened 5 weeks ago
Closed 4 weeks ago
#66282 closed defect (bug) (fixed)
redirect_guess_404_permalink() cache key changes on every request, so the cache is never hit
| Reported by: | maheshbohara | Owned by: | peterwilsoncc |
|---|---|---|---|
| Priority: | normal | Milestone: | 7.2 |
| Component: | Canonical | Version: | trunk |
| Severity: | normal | Keywords: | has-patch has-unit-tests |
| Cc: | Focuses: | performance |
Description
[64043] (#64250) added object caching to the database lookup in redirect_guess_404_permalink(). The cache key is built with md5( $query ), but for the default (loose) guess the query contains a LIKE clause produced by $wpdb->prepare(), so the literal % has been replaced by the wpdb::placeholder_escape() token.
That token is randomly generated once per request, which means the cache key is different on every request. With a persistent object cache the cached value can never be read back by a later request: every 404 guess is a cache miss followed by a new cache write, so the database query still runs every time and the cache fills up with entries that are never reused.
WP_Query::generate_cache_key(), WP_Term_Query and WP_User_Query all call $wpdb->remove_placeholder_escape() before hashing the SQL for this reason (see #56802). redirect_guess_404_permalink() does not.
The strict guess (strict_redirect_guess_404_permalink filter returning true) is not affected, as its query has no LIKE.
Steps to reproduce
Run the same lookup in separate PHP processes and compare the key stored in the post-queries cache group:
wp eval 'global $wp_object_cache; set_query_var( "name", "hello" ); redirect_guess_404_permalink(); $p = new ReflectionProperty( $wp_object_cache, "cache" ); foreach ( array_keys( $p->getValue( $wp_object_cache )["post-queries"] ) as $k ) { echo "$k\n"; }'
Three consecutive runs on trunk, same site, same query var:
redirect_guess_404_permalink:08acf8e49d2a67c972730040e8ea493f redirect_guess_404_permalink:fa535a7c05a5d36197098bd5eb31a39c redirect_guess_404_permalink:b25965b0f5e72fabaabbb112d29a8f21
Expected: the key is identical on every run, so a persistent object cache can serve the result.
The existing tests added in [64043] do not catch this because they call the function twice within one PHP process, where the placeholder token is the same.
Proposed fix
Hash the query after removing the placeholder escape, as the query classes do:
- $key = md5( $query ); + $key = md5( $wpdb->remove_placeholder_escape( $query ) );
I have a patch with a unit test and will open a PR shortly.
Change History (6)
This ticket was mentioned in PR #14146 on WordPress/wordpress-develop by @maheshbohara.
5 weeks ago
#1
- Keywords has-patch has-unit-tests added
#3
@
4 weeks ago
Ticket: https://core.trac.wordpress.org/ticket/66282
PR: https://github.com/WordPress/wordpress-develop/pull/14146
Committers Involved: @peterwilsoncc (Milestone set to 7.2, commit 035f12bf6a pushed to PR)
---
#### Environment
- WordPress: 7.2-alpha-63166-src (trunk)
- PHP: 8.3.33
- Server: macOS Darwin 24.6.0 (arm64)
- Database: MariaDB 10.11
- PHPUnit: 9.6.37
- PHPCS: 3.13.5 (WordPress-Core)
---
#### Summary of Proposed Changes in PR #14146
In changeset [64043], object caching was introduced for redirect_guess_404_permalink() in src/wp-includes/canonical.php. The cache key is generated by hashing the SQL query:
`php
$key = md5( $query );
`
For standard loose 404 guesses, $query contains a LIKE clause constructed via $wpdb->prepare(). In $wpdb->prepare(), literal % wildcards are replaced with $wpdb->placeholder_escape().
Because $wpdb->placeholder_escape() generates a randomized string per PHP execution lifecycle:
- Under persistent object caching (Redis / Memcached), every request hashes a different query string, resulting in a 100% cache miss rate.
- Each 404 guess writes an orphaned, never-reused cache entry to persistent cache storage.
PR #14146 resolves this by calling $wpdb->remove_placeholder_escape( $query ) prior to hashing:
`php
Remove the per-request placeholder escape so the cache key is stable across requests.
$key = md5( $wpdb->remove_placeholder_escape( $query ) );
`
This mirrors established core patterns in WP_Query::generate_cache_key(), WP_Term_Query, and WP_User_Query.
---
#### Verification & Test Results
##### 1. Bug Reproduction on Trunk (without PR #14146)
Executing the new unit test against trunk reproduces the failure across simulated separate requests:
`bash
vendor/bin/phpunit --filter test_redirect_guess_404_permalink_cache_key_excludes_placeholder_escape tests/phpunit/tests/canonical.php
`
Result:
`
There was 1 failure:
1) Tests_Canonical::test_redirect_guess_404_permalink_cache_key_excludes_placeholder_escape
The cache key should be generated from the SQL query.
Failed asserting that false is identical to 625.
/Volumes/RobelExt/Web/wpcore/tests/phpunit/tests/canonical.php:485
FAILURES!
Tests: 1, Assertions: 3, Failures: 1.
`
*Finding:* On trunk, the cached entry key in post-queries contains the randomized placeholder escape token, causing lookup using the de-escaped query hash to return false (cache miss).
---
##### 2. Verification with PR #14146 Applied
Running the full canonical test suite with PR #14146 (including Peter Wilson's commit 035f12bf6a):
`bash
vendor/bin/phpunit tests/phpunit/tests/canonical.php
`
Result:
`
................................................................. 65 / 83 ( 78%)
.................. 83 / 83 (100%)
Time: 00:00.656, Memory: 48.50 MB
OK (83 tests, 110 assertions)
`
Targeted test execution:
`bash
vendor/bin/phpunit --filter test_redirect_guess_404_permalink tests/phpunit/tests/canonical.php
`
Result:
`
............... 15 / 15 (100%)
Time: 00:00.221, Memory: 46.50 MB
OK (15 tests, 29 assertions)
`
Both the existing cached lookup tests and the new placeholder-exclusion assertions pass with 100% success.
---
##### 3. Code Standards Verification
`bash
vendor/bin/phpcs src/wp-includes/canonical.php tests/phpunit/tests/canonical.php
`
Result:
`
.. 2 / 2 (100%)
Time: 145ms; Memory: 8MB
`
0 errors, 0 warnings.
---
#### Architectural & Code Observations
- Commit
035f12bf6aby@peterwilsoncc: Core committer Peter Wilson directly committed an explicit assertion ensuring that$cache_keydoes not contain$wpdb->placeholder_escape(). This ensures that even if internal filter mechanisms shift, the key cannot inadvertently absorb the transient escape string. - Strict Guessing Compatibility:
When
strict_redirect_guess_404_permalinkis filtered totrue, the query usespost_name = %swithout literal%characters. Calling$wpdb->remove_placeholder_escape()is a safe no-op on non-escaped strings, introducing no regressions or overhead. - Global Placement Detail:
In
test_redirect_guess_404_permalink_cache_key_excludes_placeholder_escape(),global $wpdb;is placed at the top of the method (line 453), whereas$wpdbis only accessed on line 486 ($wpdb->placeholder_escape()). While acceptable, placingglobal $wpdb;immediately preceding line 486 adheres to the core practice of declaring globals right before their point of first use.
---
#### Recommendation
PR #14146 is clean, surgical, fully tested, and ready to be committed to trunk for WordPress 7.2.
@maheshbohara commented on PR #14146:
4 weeks ago
#4
Thanks for the review and the test tweak, @peterwilsoncc. I'm happy with the changes. The one failing check (Upgrade from 7.1 / PHP 8.4 / MySQL 8.4) looks like a runner issue: WP-CLI failed to install, so wp wasn't found.
@peterwilsoncc commented on PR #14146:
4 weeks ago
#5
Thanks for the review and the test tweak, @peterwilsoncc. I'm happy with the changes.
Night brain realized my test was broken: for multiple reasons md5( $queries[0] ) is never going to contain the placeholder 🤦♂️. I've reverted my commit and merged in trunk and will commit in a few minutes.
The one failing check (Upgrade from 7.1 / PHP 8.4 / MySQL 8.4) looks like a runner issue: WP-CLI failed to install, so
wpwasn't found.
Yeah, that can happen with tests that use a network connection, as the other upgrades tests were passing I wasn't too concerned.
![(please configure the [header_logo] section in trac.ini)](/chrome/site/your_project_logo.png)
[64043] added object caching to the database lookup in
redirect_guess_404_permalink(). The cache key ismd5( $query ), but for the default (loose) guess the query contains aLIKEclause built by$wpdb->prepare(), so the literal%has been swapped for thewpdb::placeholder_escape()token.That token is regenerated on every request, so the cache key is different on every request. With a persistent object cache the stored value is never read back: each 404 guess is a cache miss followed by a new cache write.
This PR removes the placeholder escape before hashing, which is what
WP_Query::generate_cache_key(),WP_Term_QueryandWP_User_Queryalready do.Testing
Before the change, running the same lookup in separate PHP processes stores a different key each time:
wp eval 'global $wp_object_cache; set_query_var( "name", "hello" ); redirect_guess_404_permalink(); $p = new ReflectionProperty( $wp_object_cache, "cache" ); foreach ( array_keys( $p->getValue( $wp_object_cache )["post-queries"] ) as $k ) { echo "$k\n"; }'After the change the key is the same on every run.
A unit test is included. It captures the SQL through the
queryfilter (where the placeholder escape has already been removed) and asserts that the result is cached under the key derived from that SQL. It fails on trunk and passes with this change. The existing tests from [64043] could not catch this because they call the function twice in one PHP process, where the token is constant.Use of AI Tools
AI assistance: Yes
Tool(s): Claude Code
Model(s): Claude Opus
Used for: Investigating and reproducing the bug, and drafting the patch, unit test and this description. I reviewed the changes and ran the tests locally.