Debian Codegraph @

vendor/wikimedia/parsoid/tools/RegressionTesting.php

raw
1 <?php
2
3 namespace Wikimedia\Parsoid\Tools;
4
5 use Error;
6 use Wikimedia\Parsoid\Utils\DOMCompat;
7 use Wikimedia\Parsoid\Utils\DOMUtils;
8 use Wikimedia\Parsoid\Utils\ScriptUtils;
9
10 require_once __DIR__ . '/Maintenance.php';
11
12 // phpcs:ignore MediaWiki.Files.ClassMatchesFilename.NotMatch
13 class RegressionTesting extends \Wikimedia\Parsoid\Tools\Maintenance {
14 use \Wikimedia\Parsoid\Tools\ExtendedOptsProcessor;
15
16 private $titlesPath = '/tmp/titles';
17
18 public function __construct() {
19 parent::__construct( false /* Doesn't actually require parsoid */ );
20 $this->addDescription(
21 "Validate round-trip testing results.\n" .
22 "Typical usage:\n" .
23 "\tphp " . basename( $this->getName() ) . " --uid <username> <knownGood> <maybeBad>\n" .
24 "\n" .
25 "You likely also need either the --url or --titles options.\n" .
26 "See --help for detailed usage."
27 );
28 $this->addArg(
29 'knownGood',
30 "git commit hash to use as the oracle ('known good')",
31 false
32 );
33 $this->addArg(
34 'maybeBad',
35 "git commit hash to test ('maybe bad')",
36 false
37 );
38 $this->addOption(
39 "uid",
40 "The bastion username you use to login to parsoidtest1001/testreduce1002",
41 false, true, 'u'
42 );
43 $this->addOption(
44 "contentVersion",
45 "The outputContentVersion to use, if different from the default",
46 false, true
47 );
48 $this->addOption(
49 "titles",
50 "File containing list of pages to test, formatted as lines of dbname:title",
51 false, true, 't'
52 );
53 $this->addOptionWithDefault(
54 "url",
55 "URL to use to fetch pages to test",
56 'http://localhost:8003/regressions/between/<good>/<bad>'
57 );
58 $this->addOptionWithDefault(
59 "nSem",
60 "Number of semantic errors to check, -1 means 'all of them'",
61 -1 /* default */, 'n' );
62 $this->addOptionWithDefault(
63 "nSyn",
64 "Number of syntactic errors to check, -1 means 'all of them'",
65 25 /* default */, 'm' );
66 $this->addOptionWithDefault(
67 "updateTestreduce",
68 "Should testreduce1002 also be updated? (default true)",
69 true );
70 $this->setAllowUnregisteredOptions( true );
71 }
72
73 /**
74 * Safely execute a shell command.
75 * @param array $cmd The shell command to execute.
76 * @param bool $use_cwd Whether to execute command in "current working
77 * directory" or else in a fixed directory (defaults to false).
78 * @throws Error if the command does not successfully execute
79 */
80 private function sh( array $cmd, bool $use_cwd = false ): void {
81 if ( !$this->hasOption( 'quiet' ) ) {
82 error_log( implode( ' ', $cmd ) );
83 }
84 $descriptors = [ STDIN, STDOUT, STDERR ];
85 if ( $this->hasOption( 'quiet' ) ) {
86 $descriptors[1] = [ 'file', '/tmp/rt.out', 'a' ];
87 }
88 // phpcs:ignore MediaWiki.Usage.ForbiddenFunctions.proc_open
89 $process = proc_open(
90 $cmd, $descriptors, $pipes,
91 $use_cwd ? null : __DIR__
92 );
93 if ( $process === false ) {
94 throw new Error( "Command failed: " . implode( ' ', $cmd ) );
95 }
96 $return_value = proc_close( $process );
97 if ( $return_value !== 0 ) {
98 throw new Error( "Command returned non-zero status: $return_value" );
99 }
100 }
101
102 /**
103 * Safely execute a command on another host, using ssh.
104 * @param array $cmd The shell command to execute.
105 * @param string|null $hostname The host on which to execute the command.
106 * @throws Error if the command does not successfully execute
107 */
108 private function ssh( array $cmd, ?string $hostname = null ): void {
109 array_unshift( $cmd, 'ssh', $this->hostname( $hostname ) );
110 $this->sh( $cmd );
111 }
112
113 /**
114 * Helper function to glue strings and arrays together.
115 * Arguments passed as strings are automatically split on the space
116 * character. Arguments passed as arrays are merged as-is, protecting
117 * any embedded spaces in the argument values.
118 * @param string|array<string> ...$commands
119 * @return array<string>
120 */
121 private static function cmd( ...$commands ): array {
122 return array_merge( ...array_map( static function ( $item ) {
123 return is_string( $item ) ? explode( ' ', $item ) : $item;
124 }, $commands ) );
125 }
126
127 /**
128 * Returns $uid@$hostname
129 * @param string|null $host The hostname to use.
130 * @return string
131 */
132 private function hostname( ?string $host = null ): string {
133 if ( $host === null ) {
134 // default hostname
135 $host = 'testreduce1002.eqiad.wmnet';
136 }
137 if ( $this->hasOption( 'uid' ) ) {
138 $host = $this->getOption( 'uid' ) . "@$host";
139 }
140 return $host;
141 }
142
143 /**
144 * Return the command-line argument fragment to use if an explicit
145 * content version was passed as a command-line option.
146 * @return string[]
147 */
148 private function outputContentVersion(): array {
149 if ( !$this->hasOption( 'contentVersion' ) ) {
150 return [];
151 }
152 return [ '--outputContentVersion', $this->getOption( 'contentVersion' ) ];
153 }
154
155 /**
156 * Print out a heading on the console.
157 * @param string|null $heading The heading text, or null to print a line of dashes
158 * @param bool $force Whether to print the heading even if --quiet
159 */
160 private function dashes( ?string $heading = null, bool $force = false ): void {
161 if ( $this->hasOption( 'quiet' ) && !$force ) {
162 return;
163 }
164 if ( $heading ) {
165 echo( "----- $heading -----\n" );
166 } else {
167 echo( "---------------------\n" );
168 }
169 }
170
171 /**
172 * Run tests on the given commit on the remote host.
173 * @param string $commit The commit to test
174 */
175 public function runTest( $commit ): void {
176 $cdDir = self::cmd( 'cd /srv/parsoid-testing' );
177 $restartPHP = self::cmd( 'sudo systemctl restart php7.4-fpm.service' );
178 $resultPath = "/tmp/results.$commit.json";
179 $testScript = self::cmd(
180 $cdDir, '&&',
181 'node tools/runRtTests.js',
182 '--proxyURL http://parsoidtest1001.eqiad.wmnet:80',
183 '--parsoidURL http://DOMAIN/w/rest.php',
184 $this->outputContentVersion(),
185 [ '-f', $this->titlesPath ],
186 [ '-o', $resultPath ]
187 );
188
189 $this->dashes( "Checking out $commit on parsoidtest1001" );
190 $this->ssh( self::cmd(
191 $cdDir, '&&',
192 "git fetch", '&&',
193 'git checkout', [ $commit ], '&&',
194 $restartPHP
195 ), 'parsoidtest1001.eqiad.wmnet' );
196 if ( ScriptUtils::booleanOption( $this->getOption( 'updateTestreduce' ) ) ) {
197 # Check out on testreduce1002 as well to ensure HTML version changes
198 # don't trip up our test script and we don't have to mess with passing in
199 # the --contentVersion option in most scenarios
200 $this->dashes( "Checking out $commit on testreduce1002" );
201 $this->ssh( self::cmd(
202 $cdDir, '&&',
203 "git fetch", '&&',
204 'git checkout', [ $commit ] ), 'testreduce1002.eqiad.wmnet' );
205 }
206
207 $this->dashes( "Running tests" );
208 $this->ssh( self::cmd(
209 'sudo rm -f', [ $resultPath ], '&&',
210 $testScript
211 ) );
212 $this->sh( self::cmd(
213 'scp',
214 $this->hasOption( 'quiet' ) ? '-q' : [],
215 [ $this->hostname() . ":" . $resultPath ],
216 '/tmp/'
217 ) );
218 }
219
220 /**
221 * Load the JSON-format results for the given commit.
222 * @param string $commit
223 * @return array
224 */
225 public function readResults( string $commit ): array {
226 $resultsPath = "/tmp/results.$commit.json";
227 $result = [];
228 foreach ( json_decode( file_get_contents( $resultsPath ), true ) as $r ) {
229 $result[$r['prefix'] . ':' . $r['title']] = $r['results'];
230 }
231 return $result;
232 }
233
234 /**
235 * Helper function to do a 'deep' comparison on two array values.
236 * @param mixed $a
237 * @param mixed $b
238 * @return bool True iff the arrays contain the same contents
239 */
240 private static function deepEquals( $a, $b ): bool {
241 if ( is_array( $a ) && is_array( $b ) ) {
242 // Are the keys the same?
243 $ka = array_keys( $a );
244 $kb = array_keys( $b );
245 if ( count( $ka ) !== count( $kb ) ) {
246 return false;
247 }
248 foreach ( $ka as $k ) {
249 if ( !array_key_exists( $k, $b ) ) {
250 return false;
251 }
252 if ( !self::deepEquals( $a[$k], $b[$k] ) ) {
253 return false;
254 }
255 }
256 return true;
257 } elseif ( is_array( $a ) || is_array( $b ) ) {
258 return false;
259 } else {
260 return $a === $b;
261 }
262 }
263
264 /**
265 * Helper function to dump results
266 * @param array $res
267 */
268 private function printResults( array $res ): void {
269 foreach ( $res as $test => $testRes ) {
270 echo( "\t$test\t=> " );
271 foreach ( $testRes as $type => $count ) {
272 echo( "$type: $count; " );
273 }
274 echo( "\n" );
275 }
276 }
277
278 /**
279 * Compare the results for the given titles.
280 * @param string[] $titles The titles to compare
281 * @param string $knownGood the oracle commit
282 * @param string $maybeBad the test commit
283 */
284 public function compareResults( $titles, $knownGood, $maybeBad ): void {
285 $this->dashes( "Comparing results" );
286 $oracleResults = $this->readResults( $knownGood );
287 $commitResults = $this->readResults( $maybeBad );
288 $numErrorsOracle = 0;
289 $numErrorsCommit = 0;
290 $numTitles = count( $titles );
291
292 $summary = [ 'degraded' => [], 'improved' => [] ];
293 foreach ( $titles as $title ) {
294 $oracleRes = $oracleResults[$title] ?? null;
295 $commitRes = $commitResults[$title] ?? null;
296 if ( $oracleRes['html2wt']['error'] ?? 0 ) {
297 $numErrorsOracle++;
298 }
299 if ( $commitRes['html2wt']['error'] ?? 0 ) {
300 $numErrorsCommit++;
301 }
302 if ( self::deepEquals( $oracleRes, $commitRes ) ) {
303 if ( !$this->hasOption( 'quiet' ) ) {
304 echo( "$title\n" );
305 echo( "No changes!\n" );
306 }
307 } else {
308 // emit these differences even in 'quiet' mode
309 $this->dashes( null, true );
310 echo( "$title\n" );
311 echo( "$knownGood (known good) results:\n" );
312 $this->printResults( $oracleRes );
313 echo( "$maybeBad (maybe bad) results:\n" );
314 $this->printResults( $commitRes );
315 $degraded = static function ( $newRes, $oldRes ) {
316 // NOTE: We are conservatively assuming that even if semantic
317 // errors go down but syntactic errors go up, it is a degradation.
318 return ( $newRes['error'] ?? 0 ) > ( $oldRes['error'] ?? 0 ) ||
319 ( $newRes['semantic'] ?? 0 ) > ( $oldRes['semantic'] ?? 0 ) ||
320 ( $newRes['syntactic'] ?? 0 ) > ( $oldRes['syntactic'] ?? 0 );
321 };
322 if ( $degraded( $commitRes['html2wt'], $oracleRes['html2wt'] ) ||
323 $degraded( $commitRes['selser'], $oracleRes['selser'] ) ) {
324 $summary['degraded'][] = $title;
325 } else {
326 $summary['improved'][] = $title;
327 }
328 }
329 }
330 $this->dashes( null, true );
331 if ( count( $summary['improved'] ) > 0 ) {
332 echo( "Pages that seem to have improved (feel free to verify in other ways):\n" );
333 echo( implode( "\n", $summary['improved'] ) );
334 echo( "\n" );
335 $this->dashes( null, true );
336 }
337 if ( count( $summary['degraded'] ) > 0 ) {
338 echo( "Pages needing investigation:\n" );
339 echo( implode( "\n", $summary['degraded'] ) );
340 echo( "\n" );
341 } else {
342 echo( "*** No pages need investigation ***\n" );
343 }
344
345 # Sanity check
346 if ( $numErrorsOracle === $numTitles ) {
347 error_log( "\n***** ALL runs for $knownGood errored! *****" );
348 }
349 if ( $numErrorsCommit === $numTitles ) {
350 error_log( "\n***** ALL runs for $maybeBad errored! *****" );
351 }
352 }
353
354 private function makeCurlRequest( string $url ): string {
355 $curlopt = [
356 CURLOPT_USERAGENT => 'Parsoid-RT-Test',
357 CURLOPT_CONNECTTIMEOUT => 60,
358 CURLOPT_TIMEOUT => 60,
359 CURLOPT_FOLLOWLOCATION => false,
360 CURLOPT_ENCODING => '', // Enable compression
361 CURLOPT_RETURNTRANSFER => true,
362 CURLOPT_POST => false
363 ];
364 $ch = curl_init( $url );
365 if ( !$ch ) {
366 throw new \RuntimeException( "Failed to open curl handle to $url" );
367 }
368
369 if ( !curl_setopt_array( $ch, $curlopt ) ) {
370 throw new \RuntimeException( "Error setting curl options: " . curl_error( $ch ) );
371 }
372
373 $res = curl_exec( $ch );
374
375 if ( curl_errno( $ch ) !== 0 ) {
376 throw new \RuntimeException( "HTTP request failed: " . curl_error( $ch ) );
377 }
378
379 $code = curl_getinfo( $ch, CURLINFO_RESPONSE_CODE );
380 if ( $code !== 200 ) {
381 throw new \RuntimeException( "HTTP request failed: HTTP code $code" );
382 }
383
384 if ( !$res ) {
385 throw new \RuntimeException( "HTTP request failed: Empty response" );
386 }
387
388 return $res;
389 }
390
391 private function updateSemanticErrorTitles( string $baseUrl, array &$titles ): void {
392 $url = $baseUrl;
393 $page = 0;
394 do {
395 $done = true;
396 $dom = DOMUtils::parseHTML( $this->makeCurlRequest( $url ) );
397 $titleRows = DOMCompat::querySelectorAll( $dom, 'tr[status=fail]' );
398 foreach ( $titleRows as $tr ) {
399 $titles[] = DOMCompat::querySelector( $tr, 'td[class=title] a' )->firstChild->nodeValue;
400 }
401 // Fetch more if necessary
402 if ( !DOMCompat::querySelectorAll( $dom, 'tr[status=skip]' ) ) {
403 $done = false;
404 $page++;
405 $url = $baseUrl . "/$page";
406 if ( $page > 2 ) {
407 throw new \RuntimeException( "Too many regressions? Fetched $page pages of $baseUrl. Aborting." );
408 }
409 }
410 } while ( !$done );
411 }
412
413 /** @inheritDoc */
414 public function execute() {
415 $this->maybeHelp();
416 $titles = [];
417
418 if ( $this->hasOption( 'url' ) ) {
419 $baseUrl = $this->getOption( 'url' );
420 if ( !preg_match( "#.*/between/(.*)/(.*)#", $baseUrl, $matches ) ) {
421 $this->error( "Please check the source url. Don't recognize format of $baseUrl." );
422 return -1;
423 }
424 $knownGood = $matches[1];
425 $maybeBad = $matches[2];
426 $rtSelserUrl = preg_replace( "#regressions/between/.*/(.*)$#", "rtselsererrors/$1", $baseUrl );
427 $titles = [];
428
429 $this->updateSemanticErrorTitles( $baseUrl, $titles );
430 $this->updateSemanticErrorTitles( $rtSelserUrl, $titles );
431 $localTitlesPath = "/tmp/titles";
432 file_put_contents( $localTitlesPath, implode( "\n", $titles ) );
433 } elseif ( $this->hasOption( 'titles' ) ) {
434 $localTitlesPath = $this->getOption( 'titles' );
435 $lines = preg_split(
436 '/\r\n?|\n/',
437 file_get_contents( $this->getOption( 'titles' ) )
438 );
439 foreach ( $lines as $line ) {
440 $line = preg_replace( '/ \|.*$/', '', $line );
441 if ( $line !== '' ) {
442 $titles[] = $line;
443 }
444 }
445
446 $knownGood = $this->getArg( 0 );
447 $maybeBad = $this->getArg( 1 );
448 if ( !$knownGood || !$maybeBad ) {
449 $this->error( "Missing known-good and maybe-bad git hashes" );
450 return -1;
451 }
452 } else {
453 $this->error( "Either --titles or --url is required." );
454 return -1;
455 }
456
457 $this->ssh( self::cmd( 'sudo rm -f', [ $this->titlesPath ] ) );
458 $this->sh( self::cmd(
459 'scp',
460 $this->hasOption( 'quiet' ) ? '-q' : [],
461 [ $localTitlesPath ],
462 [ $this->hostname() . ":" . $this->titlesPath ]
463 ), true );
464
465 $this->runTest( $knownGood );
466 $this->runTest( $maybeBad );
467
468 $this->compareResults( $titles, $knownGood, $maybeBad );
469 }
470 }
471
472 $maintClass = RegressionTesting::class;
473 require_once PARSOID_RUN_MAINTENANCE_IF_MAIN;