Skip to content

Build/Test Tools: Add an opt-in PHPUnit test leak harness - #16204

Draft
lucatume wants to merge 18 commits into
WordPress:trunkfrom
lucatume:test-leak-harness
Draft

lucatume wants to merge 18 commits into
WordPress:trunkfrom
lucatume:test-leak-harness

Conversation

@lucatume

Copy link
Copy Markdown

Adds an opt-in harness that reports the state each PHPUnit test or test class leaves changed. Off by default: the normal PHPUnit run and CI are unchanged.

  • tests/phpunit/leaks/: a PHPUnit listener snapshots state around each test and class; diff.php reports the changes.
  • rules.php sets the areas checked per scope (test, class), with per-file additions and exclusions; env vars override it.
  • --testsuite leak-probe plants one leak per area to check the harness detects each.
  • Usage: tests/phpunit/README.md, "Find state that tests leak".

Leaks tracked

Area Leak
db Rows added, changed or deleted.
dbcount Table row counts.
autoinc AUTO_INCREMENT counters, which ROLLBACK does not reset.
schema Tables created, dropped or altered.
temptable Temporary tables not dropped.
cache In-memory object cache entries.
mc Memcached keys.
stale Cached options and network options that disagree with the database.
global Globals, including $wpdb and $wp_object_cache settings.
static Class static properties.
fstatic Static variables in functions and methods.
const Constants defined.
ini, env, proc ini settings, environment variables, process state.
file Files under wp-content and the temp dir.

Example

Check a test class, test by test, then report what each test and the class leave:

node ./tools/local-env/scripts/docker.js run --rm php ./vendor/bin/phpunit -c tests/phpunit/leaks/phpunit.xml --filter Tests_Option_Option
node ./tools/local-env/scripts/docker.js run --rm php php tests/phpunit/leaks/diff.php tests/phpunit/build/leaks/snapshots.jsonl

WP_TESTS_LEAKS_AREAS=statics,globals narrows the checks; -e WP_TESTS_LEAKS_SCOPE=class without --filter sweeps the whole suite for state that outlives the process.

Supports PHPUnit 5.7–9. PHPUnit 10 removed listeners: there the harness exits with a message.

Testing

Probes (28 tests) report every planted leak, single site and multisite, both scopes, PHP 8.3 and 7.4, in-memory cache and memcached. An earlier revision also passed PHP 7.4–8.6 × PHPUnit 5.7–9.6.

Trac ticket: https://core.trac.wordpress.org/ticket/66802

Use of AI Tools

AI assistance: Yes
Tool(s): Claude Code
Model(s): Claude Opus 5.5
Used for: Implementation, tests and review; I reviewed and edited the result.


This Pull Request is for code review only. Please keep all other discussion in the Trac ticket. Do not merge this Pull Request. See GitHub Pull Requests for Code Review in the Core Handbook for more details.

@lucatume lucatume self-assigned this Nov 24, 2026

@lancewillett lancewillett left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Luca, I tried 363c9fb against the test-order failure fixed in r65746. The harness identified the class that caused it.

On the parent of r65746, the title tests passed alone. Running the post autosave, image header, and title tests in that order produced two title failures, with or without the listener. With WP_TESTS_LEAKS_SCOPE=class and WP_TESTS_LEAKS_AREAS='global|wp_filter|title_save_pre', the report named just Tests_Post_wpGetPostAutosave and showed that wp_filter_kses had disappeared from title_save_pre. Applying only the autosave fixture’s one-line logout cleared that report. All 23 tests then passed in the same order.

Could you add a short worked example like this to the README? The broad globals comparison still reported 275 differences after the fix, down from 280. Showing how to go from a failing assertion to one inherited hook would help someone decide which difference is worth fixing.

AI review · gpt-6

@adimoldovan adimoldovan left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking, left suggestions inline.

Comment on lines +94 to +95
'db' => array( 'db|*', 'dbcount|*', 'autoinc|*', 'schema|*', 'temptable|*' ),
'cache' => array( 'cache|*', 'mc|*', 'stale|*' ),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

db and cache are also area names, so a '!cache' rule in rules.php drops mc and stale too, and '!db' drops schema, autoinc, dbcount and temptable. Rename these two shorthands (the README list needs the same change):

Suggested change
'db' => array( 'db|*', 'dbcount|*', 'autoinc|*', 'schema|*', 'temptable|*' ),
'cache' => array( 'cache|*', 'mc|*', 'stale|*' ),
'database' => array( 'db|*', 'dbcount|*', 'autoinc|*', 'schema|*', 'temptable|*' ),
'caches' => array( 'cache|*', 'mc|*', 'stale|*' ),

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Renamed them database and caches in 9ff480a, as globals, statics and files already avoid their areas. !cache now drops only cache/*, and !db only db/*. The README list and the rules.php doc changed with them.

Comment on lines +525 to +543
public function start_test( $test ) {
$name = $this->name( $test );

// An isolated child inherits the environment.
putenv( self::ENV_TEST . '=' . $name );
putenv( self::ENV_FILE . '=' . ( new ReflectionClass( $test ) )->getFileName() );

$plan = $this->plan( get_class( $test ) );
if ( self::SCOPE_CLASS !== $this->scope && $plan ) {
$this->write( 'test_start', $name, $plan );
}
}

public function end_test( $test, $time ) {
$plan = $this->plan( get_class( $test ) );
if ( self::SCOPE_CLASS !== $this->scope && $plan ) {
$this->write( 'test_end', $this->name( $test ), $plan );
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Inside a class, each test_start snapshot is the same as the test_end before it, because nothing runs between them. Reuse the last test_end state to cut the run time and file size by about half.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed: on four core classes (878 tests), each of the 874 test_start snapshots after a test_end in the same class matched it. fba211d writes those starts as a "reuse": true marker with no state, and diff.php starts them from the last test_end. The run went from 3:14 to 1:48 and the file from 1.54 GB to 779 MB, with the same report. Tests_Multisite_Site is now 156 MB. A class end resets it, so neither the next class nor a --repeat pass reuses it, and check-probes.php fails on a wrong reused start (2104150, e379295).

@andreivrabielucian-dev andreivrabielucian-dev left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI-assisted review (Codex). A PHP 8.1 check with two JSONL files containing only the target class’s class_start snapshot returned exit code 2 in comparison mode. Single-run mode rejected the same input as incomplete (exit code 1).

Could the README clarify that comparison mode accepts partial snapshots and does not check whether either run completed?

@lancewillett

Copy link
Copy Markdown
Member

AI-assisted review (Codex).

@andreivrabielucian-dev Could you edit your AI-assisted comments for quality? It isn't readable and repeats the message twice.

@andreivrabielucian-dev

andreivrabielucian-dev commented Nov 25, 2026 •

Copy link
Copy Markdown

Thanks, Lance. I removed the duplicate text from my review.

I also opened a documentation follow-up against this PR’s branch to explain the comparison mode’s exit codes.

@lucatume

Copy link
Copy Markdown
Author

AI-assisted review (Codex). A PHP 8.1 check with two JSONL files containing only the target class’s class_start snapshot returned exit code 2 in comparison mode. Single-run mode rejected the same input as incomplete (exit code 1).

Could the README clarify that comparison mode accepts partial snapshots and does not check whether either run completed?

Comparison mode accepts partial runs on purpose: it reads each run only up to the class's class_start, so a run that crashed in that class can still be compared. The README now says so (bed7e43). The same commit fixes a related gap. When the class was the first snapshotted one in the sequence run, every difference counted as run noise, and diff.php exited 0 with no output. It now exits 1 and says that no snapshotted class ran before it.

@lucatume

Copy link
Copy Markdown
Author

Luca, I tried 363c9fb against the test-order failure fixed in r65746. The harness identified the class that caused it.

On the parent of r65746, the title tests passed alone. Running the post autosave, image header, and title tests in that order produced two title failures, with or without the listener. With WP_TESTS_LEAKS_SCOPE=class and WP_TESTS_LEAKS_AREAS='global|wp_filter|title_save_pre', the report named just Tests_Post_wpGetPostAutosave and showed that wp_filter_kses had disappeared from title_save_pre. Applying only the autosave fixture’s one-line logout cleared that report. All 23 tests then passed in the same order.

Could you add a short worked example like this to the README? The broad globals comparison still reported 275 differences after the fix, down from 280. Showing how to go from a failing assertion to one inherited hook would help someone decide which difference is worth fixing.

Added it in ce34e71, after the alone/sequence comparison. I reproduced it by reverting r65746's line in wpGetAutoSave.php: --order-by=reverse runs the autosave class first with the stock config, so the example needs no custom suite file or Tests_Image_Header. The README says to run it on a checkout before r65746

lucatume and others added 18 commits November 26, 2026 10:50
Tests that change shared state and don't restore it make other tests
pass or fail depending on run order. Add an opt-in PHPUnit listener
that snapshots state before and after each test and class, and a
script that reports what changed.

It covers database rows, schema, AUTO_INCREMENT counters and temporary
tables, the object cache including memcached keys, cached options that
disagree with the database, globals, static properties and variables,
constants, ini and env settings, process state, and files under
wp-content and the temp dir. Process-isolated children are snapshotted
too. A class-scope mode sweeps the whole suite for state that outlives
the process.

Runs on PHPUnit 5.7 to 9, which have test listeners. On PHPUnit 10+
the leak bootstrap exits with a message. A leak-probe test suite
plants one leak per area to check the listener sees each.
Snapshot $wp_object_cache minus its entries and hit counters, so a test
adding global or non-persistent groups shows as a leak; a probe covers
it. Skip the listener's own output file in the file snapshot, and add
the in-sequence run to the README's alone/sequence comparison.
The probe suite passed whether or not the listener saw the planted
leaks. check-probes.php now fails when a probe's expected key is
missing from the diff.php report, or when an isolated child reports
in-process state. Probe queries assert their results, and a new probe
covers type-only changes.

Isolated children snapshot only state that outlives them, so their
reports no longer list globals that die with the process. The
alone-vs-sequence diff drops keys that already differ before any class
ran, so identical runs report nothing.

Also hash serialized values so 1 and "1" differ, ignore
$wpdb->table_charset, keep bootstrap's variable out of the globals,
make listener constants private, and fix the PHPUnit 5 README steps.
Add leak probes for cache writes after the framework's flushes
(runtime, drop-in and memcached keys, stale options), a composite-key
row, a dangling symlink, a directory, and class-level cwd and output
buffer changes, which PHPUnit restores per test. Clean up an
interrupted run's probe files before the class runs.

diff.php skips cache entries a test drops: a miss reads the source
again. The framework's flushes made every first class report the
install's cache entries. check-probes.php fails on cache keys under
the class that plants none, and skips the expectations of the cache
not in use.
Add leak probes for a site a test commits and its stale cached
options, links and directories in the temp dir, a temporary table
dropped by a reconnect, a permanent table, and an inherited method's
static variable, which before PHP 8.1 each subclass copies.

A site created in a test has temporary tables, which SHOW TABLES
leaves out: the stale option checks now read tracked temporary tables
too.

The listener records the run's setup (multisite, PHP version,
persistent cache, scope) in run_start. check-probes.php reads it
instead of the environment and the first snapshot's keys, which in
class scope hold only changed keys, so multisite checks were skipped.

diff.php prints previews on one line: a multi-line schema read as
keys. check-probes.php no longer needs PHP 8's str_ends_with().
Snapshotting every area for every test is slow and noisy, and some
files leak on purpose. Add a rules file that picks the snapshot keys
per scope and per test file, with fnmatch() patterns, negation and a
required reason per rule. The listener validates it before any test
runs and skips collectors no pattern needs.

The leak configurations pass the rules file and scope as listener
arguments; WP_TESTS_LEAKS_RULES, WP_TESTS_LEAKS_SCOPE and
WP_TESTS_LEAKS_AREAS override them. diff.php exits with 2 when it
reports changes, so CI can fail on leaks.
Isolated children planned before their test file loaded, so per-file
rules never applied; the parent now passes the file in
WP_TESTS_LEAKS_FILE. The class-scope install baseline is taken at run
start, not after classes rules.php skips. Two-run diff.php counts as
noise only keys both runs hold with different values. A relative
WP_TESTS_LEAKS_OUT survives a test's chdir(). A run that snapshots
nothing writes no run_end, so diff.php exits 1.
The db and cache shorthands shared names with the db and cache
areas, so a !cache rule also dropped mc and stale, and !db dropped
dbcount, autoinc, schema and temptable. Rename them database and
caches, as globals, statics and files already avoid their areas.
Nothing runs between a test's end and the next test's start in the
same class, so the listener no longer snapshots there: it writes a
reuse marker, and diff.php starts the test from the pid's last
test_end. Halves snapshot time and file size: 1.54 GB to 779 MB
and 3:14 to 1:48 on four core classes, same report.
Shows how narrowing WP_TESTS_LEAKS_AREAS to the hook a failing
assertion depends on finds the class behind the r65746 test-order
failure.
When the class compared is the first in the sequence run, every
difference counts as run noise, so diff.php printed nothing and
exited 0, which reads as no order dependency. Exit 1 instead, and
document that comparison mode reads runs only up to the class
start, and that --filter keeps file order.
A stale cached option the previous test left is gone after the next
test's set_up() cache flush, so diff.php blamed it on that test as
'after: (absent)'. A stale entry gone means the cache agrees with
the database again: not a leak, like a dropped cache entry.
PHPUnit 9 calls the parent listener's startTest and endTest around
an isolated test's child process, and the parent's end snapshot
sees what the child committed: the database, files and memcached.
The child's own snapshot, limited to those areas, reported a subset
of the parent's, so remove it and the environment it needed.
Reset the reused test end at class end, so PHPUnit's --repeat does not
reuse the previous pass's last test. Have check-probes.php catch a
wrong reused start and a comparison that does not refuse the first
class, and inline the plan helper the child removal left alone.
Reuse a test end only until the class ends, the one guard the probe
suite now pins. Warn on patterns that keep no key, and write no run_end
when no snapshot kept one. Probe removed state, run noise and a cut
run. Say "snapshotted class" where a skipped one cannot count. Drop
the unused pid and a check that could not fail.
"|" means "or" in regexes and a pipe in shells, so patterns needed
escaping and quoting. ":" and "::" already occur in cache keys and
static property names. Only a key's first "/" is parsed, so one inside
a key, e.g. a file path or a hook name, does not split it.
e379295 ended a run only when a snapshot kept a key: a clean run
over stale or temporary tables read as incomplete, and the class
scope's install snapshot ended a run no class was snapshotted in.
End it when a class's plan kept an area, unless a pattern kept no key.
Write keys with unescaped slashes, and say which checkout the README
example needs.
Describe the exit codes for differences, no differences, and missing or unusable class-start snapshots.

Verified five comparison cases with PHP 8.1. Drafting and local verification were assisted by Codex.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants