Make WordPress Core

Opened 6 weeks ago

Closed 6 weeks ago

#66241 closed defect (bug) (fixed)

HTML API: Avoid rescanning unmatched character references in WP_HTML_Decoder

Reported by: serhatsoylu06 Owned by: jonsurrell
Priority: normal Milestone: 7.2
Component: HTML API Version: 6.6
Severity: normal Keywords: has-patch has-unit-tests commit
Cc: Focuses: performance

Description

WP_HTML_Decoder::decode() repeatedly scans the same prefix when an ampersand does not start a recognized character reference.

strpos() finds the next ampersand at $next_character_reference_at. On a miss, the loop currently increments $at from its previous position instead of advancing past the ampersand it just examined. The output is correct, but a long prefix causes quadratic repeated scanning.

For example, run this after loading WordPress, on trunk at cb186b3b1a4cc65732b6cec32c136807617e97ce:

$text = str_repeat( 'a', 100000 ) . ' &unknown; & tail';
$start = hrtime( true );
$result = WP_HTML_Decoder::decode_text_node( $text );
printf( "%.3f ms\n", ( hrtime( true ) - $start ) / 1000000 );
var_dump( $result === str_repeat( 'a', 100000 ) . ' &unknown; & tail' );

The proposed fix replaces ++$at with $at = $next_character_reference_at + 1. strpos() has already established that the skipped span contains no ampersand. $was_at stays unchanged, preserving the literal bytes.

A deterministic regression test spies on the existing token map while delegating to its real implementation. It requires exactly one lookup per named-reference candidate and checks the decoded output. The four cases cover data and attribute contexts, a miss after a decoded reference, and an ambiguous ampersand in an attribute. All four fail before the fix and pass afterwards.

Validation: 129 decoder cases / 274 assertions passed with PHP 8.3.0 and PHPUnit 9.6.37 using a database-free bootstrap; the full WordPress suite was not run. PHPCS and git diff --check passed.

In separate PHP 8.3.35 measurements, normalizing a synthetic 103 KB HTML article with literal ampersands took 39.194 ms before and 2.591 ms after (median of five paired trials). Both had OPcache enabled, JIT disabled, and identical output. An escaped-ampersand control showed no improvement. This is parser processing time, not whole-page time.

Patch and tests: ​https://github.com/sekalan/wordpress-develop/commit/dfc748603b5759b8a36e3ae1e9c2d703ab7617e1

AI assistance: OpenAI Codex assisted with investigation, the patch, tests, and this report.

Change History (11)

This ticket was mentioned in ​PR #13986 on ​WordPress/wordpress-develop by ​sekalan.


6 weeks ago
#1

When decode() finds an ampersand that does not start a character reference, it advances the old search offset by one byte. If the ampersand is farther ahead, the next iteration finds the same position and tries to decode it again. A long prefix makes this repeated scanning quadratic.

Advance past the ampersand that was actually found. The literal text is preserved, and subsequent references are still decoded.

The regression test counts token-map lookups rather than using a timing threshold. It covers text nodes, attributes, a miss after a successful decode, and an ambiguous ampersand in an attribute. All four cases fail before the fix and pass afterwards.

Testing: PHP 8.3.0 / PHPUnit 9.6.37, 129 decoder test cases and 274 assertions passed using a database-free bootstrap. The full WordPress test suite was not run. PHPCS and git diff --check passed.

For context, a separate PHP 8.3.35 benchmark of WP_HTML_Processor::normalize() on a synthetic 103 KB article with literal ampersands went from 39.194 ms to 2.591 ms (five paired trials, median). OPcache was enabled in both runs and the output was identical. An escaped-ampersand control showed no improvement. These are parser timings, not page-load timings.

AI assistance: OpenAI Codex assisted with investigation, the patch, tests, and this description.

---
This pull request is for code review only; discussion and the final commit belong in Trac.

This ticket was mentioned in ​PR #13987 on ​WordPress/wordpress-develop by ​@serhatsoylu06.


6 weeks ago
#2

Load the hierarchy once for descendant traversal and reuse it within the hierarchical hide_empty pass. Preserve descendant ordering and visibility checks, with regression coverage for hierarchy reads and term changes.

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

​@jonsurrell commented on ​PR #13986:


6 weeks ago
#3

Thank you @sekalan, good find. The fix here seems correct. I'd prefer to add some test cases rather than creating new tests that are asserting on internal behaviors. For example, like this (from 245b0eb):

<details><summary>suggested change</summary>

  • tests/phpunit/tests/html-api/wpHtmlDecoder.php

    diff --git a/tests/phpunit/tests/html-api/wpHtmlDecoder.php b/tests/phpunit/tests/html-api/wpHtmlDecoder.php
    index 81c047c437..701dd0ea2b 100644
    a b class Tests_HtmlApi_WpHtmlDecoder extends WP_UnitTestCase {  
    6565         * Ensures proper decoding of edge cases.
    6666         *
    6767         * @ticket 61072
     68         * @ticket 66241
    6869         *
    6970         * @dataProvider data_edge_cases
    7071         *
    71          * @param $raw_text_node Raw input text.
    72          * @param $decoded_value The expected decoded text result.
     72         * @param string $raw_text_node Raw input text.
     73         * @param string $decoded_value The expected decoded text result.
    7374         */
    74         public function test_edge_cases( $raw_text_node, $decoded_value ) {
     75        public function test_edge_cases( string $raw_text_node, string $decoded_value ): void {
    7576                $this->assertSame(
    7677                        $decoded_value,
    7778                        WP_HTML_Decoder::decode_text_node( $raw_text_node ),
    … … class Tests_HtmlApi_WpHtmlDecoder extends WP_UnitTestCase {  
    7980                );
    8081        }
    8182
    82         public static function data_edge_cases() {
    83                 return array(
    84                         'Single ampersand' => array( '&', '&' ),
    85                 );
    86         }
    87 
    8883        /**
    89          * Ensures unmatched character references are not examined repeatedly.
     84         * Data provider.
    9085         *
    91          * @ticket 66241
    92          *
    93          * @dataProvider data_unmatched_character_references
    94          *
    95          * @param string $context  Decoder context.
    96          * @param string $text     Raw input text.
    97          * @param string $expected Expected decoded text.
     86         * @return array<string, array{string, string}>
    9887         */
    99         public function test_decode_does_not_repeat_unmatched_character_references( $context, $text, $expected ) {
    100                 global $html5_named_character_references;
     88        public static function data_edge_cases(): array {
     89                $long_text = str_repeat( 'a', 300000 );
    10190
    102                 $original_map = $html5_named_character_references;
    103 
    104                 // Note: setMethods() is deprecated in PHPUnit 9, but still supported.
    105                 $token_map = $this->getMockBuilder( WP_Token_Map::class )
    106                         ->setMethods( array( 'read_token' ) )
    107                         ->getMock();
    108 
    109                 // Each input contains two named references. Neither should be read twice.
    110                 $token_map->expects( $this->exactly( 2 ) )
    111                         ->method( 'read_token' )
    112                         ->willReturnCallback(
    113                                 static function ( $text, $offset, &$matched_token_byte_length, $case_sensitivity = 'case-sensitive' ) use ( $original_map ) {
    114                                         return $original_map->read_token( $text, $offset, $matched_token_byte_length, $case_sensitivity );
    115                                 }
    116                         );
    117 
    118                 try {
    119                         $html5_named_character_references = $token_map;
    120                         $this->assertSame( $expected, WP_HTML_Decoder::decode( $context, $text ) );
    121                 } finally {
    122                         $html5_named_character_references = $original_map;
    123                 }
    124         }
    125 
    126         /**
    127          * Data provider for test_decode_does_not_repeat_unmatched_character_references().
    128          *
    129          * @return array[]
    130          */
    131         public static function data_unmatched_character_references() {
    13291                return array(
    133                         'Unknown name in a text node'            => array(
    134                                 'data',
    135                                 'prefix &unknown; middle &amp; tail',
    136                                 'prefix &unknown; middle & tail',
    137                         ),
    138                         'Unknown name in an attribute'           => array(
    139                                 'attribute',
    140                                 'prefix &unknown; middle &amp; tail',
    141                                 'prefix &unknown; middle & tail',
    142                         ),
    143                         'Unknown name after a decoded reference' => array(
    144                                 'data',
    145                                 'prefix &amp; middle &unknown; tail',
    146                                 'prefix & middle &unknown; tail',
    147                         ),
    148                         'Ambiguous ampersand in an attribute'    => array(
    149                                 'attribute',
    150                                 'prefix &not=value middle &amp; tail',
    151                                 'prefix &not=value middle & tail',
    152                         ),
     92                        'Single ampersand'                    => array( '&', '&' ),
     93                        'Unmatched reference before a match'  => array( 'a &bogus; b &amp; c', 'a &bogus; b & c' ),
     94                        'Unmatched reference after a match'   => array( 'a &amp; b &bogus; c &lt; d', 'a & b &bogus; c < d' ),
     95                        'Unmatched numeric references'        => array( 'a &#; b &#x; c &amp;', 'a &#; b &#x; c &' ),
     96                        'Adjacent ampersands'                 => array( '&&&amp;', '&&&' ),
     97                        'Unmatched reference after long text' => array( "{$long_text}&bogus;&amp;", "{$long_text}&bogus;&" ),
    15398                );
    15499        }

</details>

It's very easy to observe the fix from there. If I reset src to the version on trunk, I run this:

WP_TESTS_SKIP_INSTALL=1 ./vendor/bin/phpunit --group=66241 --repeat 10

The 10&times; repeat exaggerates the difference, but there's no doubt there's a significant improvement:

-Time: 00:18.890, Memory: 224.50 MB
+Time: 00:00.794, Memory: 224.50 MB

#4 @jonsurrell
6 weeks ago

  • Owner set to jonsurrell
  • Status new → accepted
  • Version trunk → 6.6

​@westonruter commented on ​PR #13987:


6 weeks ago
#5

@sekalan I think you referenced the wrong Trac ticket for this. You opened ​https://github.com/WordPress/wordpress-develop/pull/13986 for Core-66241 already.

​@westonruter commented on ​PR #13987:


6 weeks ago
#6

I've corrected the reference to Core-66242

​@serhatsoylu06 commented on ​PR #13987:


6 weeks ago
#8

@sekalan Please include the AI Disclosure in the PR description:

​https://github.com/WordPress/wordpress-develop/blob/794e4798f6db09357da54f05f5be8cf961b77a52/.github/pull_request_template.md?plain=1#L22-L33

Thanks @westonruter, sorry for the confusion with the ticket reference. i started investigating this second issue using gpt, but hit my usage limit right before completing it, so i switched to gemini 3.5 flash to finish the task and submit the pr. that's why i mixed up the ticket number and was unsure about how to format the disclosure. i appreciate you fixing the reference! I've also updated the pr description with the ai disclosure.

​@serhatsoylu06 commented on ​PR #13986:


6 weeks ago
#9

Thanks @sirreal and @westonruter . I replaced the mock-based test with sirreal's edge cases and carried the typing suggestions (non-falsy-string, native types) over to the new test and data provider.

Happy to also run the same cases through decode_attribute() if you think the attribute path is worth covering separately.

#10 @jonsurrell
6 weeks ago

  • Keywords commit added
  • Milestone Awaiting Review → 7.2

#11 @jonsurrell
6 weeks ago

  • Resolution → fixed
  • Status accepted → closed

In 64124:

HTML API: Improve character reference decoding performance.

Improve the performance of WP_HTML_Decoder::decode() on strings containing ampersands that do not start a character reference.

Developed in: ​https://github.com/WordPress/wordpress-develop/pull/13986

Props serhatsoylu06, westonruter, jonsurrell.
Fixes #66241.

Note: See TracTickets for help on using tickets.