From 04810442709489748c7dcb557526c1cfb00fd950 Mon Sep 17 00:00:00 2001 From: Jhon Farias Date: Fri, 4 Dec 2026 14:01:59 +0100 Subject: [PATCH] fix(tia): read the baseline of the changed files in one git process (#2090) * fix(tia): read the baseline of the changed files in one git process * fix(tia): read the baseline blobs in size-bounded groups --------- Co-authored-by: Punyapal Shah --- src/Plugins/Tia/ChangedFiles.php | 57 ++++--- src/Support/Git.php | 213 +++++++++++++++++++++++- tests/.snapshots/success.txt | 16 +- tests/Unit/Plugins/Tia/ChangedFiles.php | 162 ++++++++++++++++++ tests/Visual/Parallel.php | 2 +- 5 files changed, 423 insertions(+), 27 deletions(-) diff --git a/src/Plugins/Tia/ChangedFiles.php b/src/Plugins/Tia/ChangedFiles.php index c86e63b5..5b44737e 100644 --- a/src/Plugins/Tia/ChangedFiles.php +++ b/src/Plugins/Tia/ChangedFiles.php @@ -312,36 +312,47 @@ final class ChangedFiles */ private function filterBehaviourallyUnchanged(array $files, string $sha): array { - $remaining = []; + $files = array_values($files); + $currentHashes = array_map($this->currentHash(...), $files); + $present = array_filter($currentHashes, static fn (?string $hash): bool => $hash !== null); + $indexes = array_keys($present); + $matches = $this->matchesAtSha($sha, array_map(static fn (int $index): string => $files[$index], $indexes), array_values($present)); + $unchanged = []; - foreach ($files as $file) { - $currentHash = $this->currentHash($file); - - if ($currentHash === null) { - $remaining[] = $file; - - continue; - } - - $baselineContent = $this->contentAtSha($sha, $file); - - if ($baselineContent === null) { - $remaining[] = $file; - - continue; - } - - if ($currentHash !== ContentHash::ofContent($file, $baselineContent)) { - $remaining[] = $file; + foreach ($indexes as $position => $index) { + if ($matches[$position] ?? false) { + $unchanged[$index] = true; } } - return $remaining; + return array_values(array_filter($files, static fn (int $index): bool => ! isset($unchanged[$index]), ARRAY_FILTER_USE_KEY)); } - private function contentAtSha(string $sha, string $path): ?string + /** + * @param list $paths + * @param list $hashes + * @return array + */ + private function matchesAtSha(string $sha, array $paths, array $hashes): array { - return $this->git->show($sha, $this->gitPrefix().$path); + if ($paths === []) { + return []; + } + + $matches = []; + $compare = static function (int $position, ?string $content) use (&$matches, $paths, $hashes): void { + $matches[$position] = $content !== null && $hashes[$position] === ContentHash::ofContent($paths[$position], $content); + }; + + $repositoryPaths = array_map(fn (string $path): string => $this->gitPrefix().$path, $paths); + + if (! $this->scan()->showEach($sha, $repositoryPaths, $compare)) { + foreach ($repositoryPaths as $position => $path) { + $compare($position, $this->git->show($sha, $path)); + } + } + + return $matches; } private function filterIgnoredOutsideProject(): void diff --git a/src/Support/Git.php b/src/Support/Git.php index 1df64d58..b5bb64bb 100644 --- a/src/Support/Git.php +++ b/src/Support/Git.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace Pest\Support; +use Closure; use Pest\Exceptions\GitTimedOut; use Symfony\Component\Process\Exception\ProcessTimedOutException; use Symfony\Component\Process\Process; @@ -15,6 +16,8 @@ final readonly class Git { private const float TIMEOUT = 5.0; + private const int BATCH_BYTES = 8_388_608; + public function __construct( private ?string $directory = null, private float $timeout = self::TIMEOUT, @@ -103,8 +106,7 @@ final readonly class Git */ public function result(array $arguments, ?string $input = null): array { - $process = new Process(['git', ...$arguments], $this->directory, ['GIT_LITERAL_PATHSPECS' => '0', 'LC_ALL' => 'C', 'LANGUAGE' => '']); - $process->setTimeout($this->timeout); + $process = $this->process($arguments); if ($input !== null) { $process->setInput($input); @@ -123,6 +125,17 @@ final readonly class Git ]; } + /** + * @param array $arguments + */ + private function process(array $arguments): Process + { + $process = new Process(['git', ...$arguments], $this->directory, ['GIT_LITERAL_PATHSPECS' => '0', 'LC_ALL' => 'C', 'LANGUAGE' => '']); + $process->setTimeout($this->timeout); + + return $process; + } + public function isRepository(): bool { return $this->succeeds(['rev-parse', '--git-dir']); @@ -148,6 +161,202 @@ final readonly class Git return $this->raw(['show', $sha.':'.$path]); } + /** + * @param list $paths + * @param Closure(int, string|null): void $receive + */ + public function showEach(string $sha, array $paths, Closure $receive): bool + { + $batched = []; + + foreach ($paths as $position => $path) { + if ($this->fitsBatchLine($path)) { + $batched[] = $position; + } else { + $receive($position, $this->show($sha, $path)); + } + } + + if ($batched === []) { + return true; + } + + $objects = $this->batchCheck($sha, array_map(static fn (int $position): string => $paths[$position], $batched)); + + if ($objects === null) { + return false; + } + + $blobs = []; + + foreach ($objects as $line => $object) { + $position = $batched[$line]; + + if ($object === null) { + $receive($position, null); + } elseif ($object['type'] !== 'blob') { + $receive($position, $this->show($sha, $paths[$position])); + } else { + $blobs[$position] = $object; + } + } + + return array_all($this->groupBlobs($blobs), fn (array $group): bool => $this->readBlobs($group, $receive)); + } + + /** + * @param list $paths + * @return list|null + */ + private function batchCheck(string $sha, array $paths): ?array + { + $result = $this->result(['cat-file', '--batch-check'], implode('', array_map(static fn (string $path): string => $sha.':'.$path."\n", $paths))); + $headers = $result['exitCode'] === 0 ? explode("\n", $result['output']) : []; + + if (array_pop($headers) !== '' || count($headers) !== count($paths)) { + return null; + } + + $objects = []; + + foreach ($headers as $header) { + $object = $this->parseCheckLine($header); + + if ($object === false) { + return null; + } + + $objects[] = $object; + } + + return $objects; + } + + /** + * @return array{oid: string, type: string, bytes: int}|false|null + */ + private function parseCheckLine(string $header): array|false|null + { + if (preg_match('/^([0-9a-f]+) ([a-z]+) (\d+)$/', $header, $matches) !== 1) { + return str_ends_with($header, ' missing') || str_ends_with($header, ' ambiguous') ? null : false; + } + + return ['oid' => $matches[1], 'type' => $matches[2], 'bytes' => (int) $matches[3] + strlen($header) + 2]; + } + + /** + * @param array $blobs + * @return list> + */ + private function groupBlobs(array $blobs): array + { + $groups = []; + $group = []; + $groupBytes = 0; + + foreach ($blobs as $position => $blob) { + if ($group !== [] && $groupBytes + $blob['bytes'] > self::BATCH_BYTES) { + $groups[] = $group; + $group = []; + $groupBytes = 0; + } + + $group[$position] = $blob['oid']; + $groupBytes += $blob['bytes']; + } + + if ($group !== []) { + $groups[] = $group; + } + + return $groups; + } + + private function fitsBatchLine(string $path): bool + { + return ! str_contains($path, "\n") && ! str_ends_with($path, "\r"); + } + + /** + * @param non-empty-array $blobs + * @param Closure(int, string|null): void $receive + */ + private function readBlobs(array $blobs, Closure $receive): bool + { + $arguments = ['cat-file', '--batch']; + $process = $this->process($arguments); + $process->setInput(implode("\n", $blobs)."\n"); + $process->start(); + + try { + return $this->streamBlobs($process, $blobs, $receive); + } catch (ProcessTimedOutException) { + throw new GitTimedOut($arguments, $this->timeout); + } + } + + /** + * @param non-empty-array $blobs + * @param Closure(int, string|null): void $receive + */ + private function streamBlobs(Process $process, array $blobs, Closure $receive): bool + { + $positions = array_keys($blobs); + $buffer = ''; + $next = 0; + + foreach ($process->getIterator(Process::ITER_SKIP_ERR) as $chunk) { + $buffer .= $chunk; + + while ($next < count($positions) && ($blob = $this->takeBlob($buffer)) !== null) { + $position = $positions[$next++]; + + if ($blob === false || $blob['oid'] !== $blobs[$position]) { + $process->stop(0); + + return false; + } + + $receive($position, $blob['content']); + } + } + + $process->wait(); + + return $next === count($positions) && $buffer === '' && $process->getExitCode() === 0; + } + + /** + * @return array{oid: string, content: string}|false|null + */ + private function takeBlob(string &$buffer): array|false|null + { + $headerEnd = strpos($buffer, "\n"); + + if ($headerEnd === false) { + return null; + } + + if (preg_match('/^([0-9a-f]+) blob (\d+)$/', substr($buffer, 0, $headerEnd), $matches) !== 1) { + return false; + } + + $end = $headerEnd + 1 + (int) $matches[2]; + + if (strlen($buffer) <= $end) { + return null; + } + + if ($buffer[$end] !== "\n") { + return false; + } + + $content = substr($buffer, $headerEnd + 1, (int) $matches[2]); + $buffer = substr($buffer, $end + 1); + + return ['oid' => $matches[1], 'content' => $content]; + } + public function repositoryRoot(): ?string { $root = $this->outputLine(['rev-parse', '--show-toplevel']); diff --git a/tests/.snapshots/success.txt b/tests/.snapshots/success.txt index 13d3f84e..f95523a3 100644 --- a/tests/.snapshots/success.txt +++ b/tests/.snapshots/success.txt @@ -2029,6 +2029,20 @@ ✓ it reports no change for an external input it cannot read ✓ it keeps a snapshotted file whose name is a number as a string ✓ it keeps a branch whose name is a number as a string + ✓ it reads the baseline of many changed files and keeps their order + ✓ it reads many baselines with one call and gives the same content as one call per file + ✓ it reads no baseline when the commit does not exist + ✓ it reads the baseline of each file again when the batch fails with dataset "a failed check" + ✓ it reads the baseline of each file again when the batch fails with dataset "a check line that does not parse" + ✓ it reads the baseline of each file again when the batch fails with dataset "a check without a line" + ✓ it reads the baseline of each file again when the batch fails with dataset "a failed read" + ✓ it reads the baseline of each file again when the batch fails with dataset "a header that does not parse after one blob" + ✓ it reads the baseline of each file again when the batch fails with dataset "a missing blob" + ✓ it reads the baseline of each file again when the batch fails with dataset "bytes after the last blob" + ✓ it reads the baseline of each file again when the batch fails with dataset "a blob without its line feed" + ✓ it reads the baseline of each file again when the batch fails with dataset "another blob than the one asked" + ✓ it raises a timed out read of the baseline blobs instead of answering + ✓ it reads the baseline of many large changed files within a small memory limit PASS Tests\Unit\Plugins\Tia\ConfigurationFile ✓ it fingerprints the path and the content of the configuration file @@ -2904,4 +2918,4 @@ ✓ pass with dataset with ('my-datas-set-value') ✓ within describe → pass with dataset with ('my-datas-set-value') - Tests: 2 deprecated, 4 warnings, 5 incomplete, 2 notices, 40 todos, 45 skipped, 2155 passed (4735 assertions) \ No newline at end of file + Tests: 2 deprecated, 4 warnings, 5 incomplete, 2 notices, 40 todos, 45 skipped, 2169 passed (4762 assertions) \ No newline at end of file diff --git a/tests/Unit/Plugins/Tia/ChangedFiles.php b/tests/Unit/Plugins/Tia/ChangedFiles.php index aa9d9765..cde55a16 100644 --- a/tests/Unit/Plugins/Tia/ChangedFiles.php +++ b/tests/Unit/Plugins/Tia/ChangedFiles.php @@ -2,9 +2,12 @@ declare(strict_types=1); +use Pest\Exceptions\GitTimedOut; use Pest\Plugins\Tia\ChangedFiles; use Pest\Plugins\Tia\ExternalSources; use Pest\Plugins\Tia\Fingerprint; +use Pest\Support\Git; +use Symfony\Component\Process\ExecutableFinder; use Symfony\Component\Process\Process; use Tests\Fixtures\Tia\GitRepo; use Tests\Fixtures\Tia\Project; @@ -442,3 +445,162 @@ it('keeps a branch whose name is a number as a string', function (): void { expect(new ChangedFiles($project->path())->branchNames())->toBe(['123', 'master']); }); + +it('reads the baseline of many changed files and keeps their order', function (): void { + $monorepo = tiaMonorepoRepository(); + $project = $monorepo['project']; + + foreach (['a', 'b', 'c', 'd', 'e'] as $name) { + file_put_contents($project.'/app/'.$name.'.php', "commit('Add the files'); + $sha = $monorepo['repo']->sha(); + + file_put_contents($project.'/app/a.php', "commit('Change a and c'); + + file_put_contents($project.'/app/c.php', "since($sha)) + ->toBe(['app/a.php', 'app/b.php', 'app/d.php', 'app/new.php']); +})->skipOnWindows(); + +/** + * @param list $paths + * @return array{0: bool, 1: list} + */ +function tiaShowEach(Git $git, string $sha, array $paths): array +{ + $contents = array_fill(0, count($paths), 'not received'); + $succeeded = $git->showEach($sha, $paths, function (int $position, ?string $content) use (&$contents): void { + $contents[$position] = $content; + }); + + return [$succeeded, $contents]; +} + +function tiaWithFakeCatFile(string $mode, string $catFile, Closure $run): mixed +{ + $realGit = (string) new ExecutableFinder()->find('git'); + $directory = sys_get_temp_dir().DIRECTORY_SEPARATOR.'pest-tia-fake-git-'.bin2hex(random_bytes(8)); + mkdir($directory); + file_put_contents($directory.'/git', "#!/bin/sh\nif [ \"\$1\" = cat-file ] && [ \"\$2\" = ".$mode." ]; then\n read -r first\n cat > /dev/null\n ".$catFile."\nfi\nexec ".escapeshellarg($realGit)." \"\$@\"\n"); + chmod($directory.'/git', 0755); + + $path = (string) getenv('PATH'); + $envPath = $_ENV['PATH'] ?? null; + $serverPath = $_SERVER['PATH'] ?? null; + + putenv('PATH='.$directory.PATH_SEPARATOR.$path); + $_SERVER['PATH'] = $_ENV['PATH'] = $directory.PATH_SEPARATOR.$path; + + try { + return $run(); + } finally { + putenv('PATH='.$path); + $_SERVER['PATH'] = $serverPath ?? $path; + + if ($envPath !== null) { + $_ENV['PATH'] = $envPath; + } else { + unset($_ENV['PATH']); + } + + new Process(['rm', '-rf', $directory])->run(); + } +} + +it('reads many baselines with one call and gives the same content as one call per file', function (): void { + $monorepo = tiaMonorepoRepository(); + $root = $monorepo['root']; + + file_put_contents($root.'/empty.txt', ''); + file_put_contents($root.'/binary.bin', "\x00\n\x01\n\n"); + file_put_contents($root."/new\nline.txt", "line\n"); + file_put_contents($root."/return.txt\r", "carriage\n"); + $monorepo['repo']->commit('Add the files'); + + $git = new Git($root); + $sha = $monorepo['repo']->sha(); + $paths = ['backend/app/Service.php', 'missing.php', 'empty.txt', 'backend', "new\nline.txt", 'binary.bin', "return.txt\r", 'frontend/widget.php']; + + [$succeeded, $contents] = tiaShowEach($git, $sha, $paths); + + expect($succeeded)->toBeTrue() + ->and($contents)->toBe(array_map(static fn (string $path): ?string => $git->show($sha, $path), $paths)) + ->and($contents[3])->toStartWith('tree '); +})->skipOnWindows(); + +it('reads no baseline when the commit does not exist', function (): void { + $monorepo = tiaMonorepoRepository(); + + expect(tiaShowEach(new Git($monorepo['root']), str_repeat('0', 40), ['backend/app/Service.php']))->toBe([true, [null]]); +})->skipOnWindows(); + +it('reads the baseline of each file again when the batch fails', function (string $mode, string $catFile): void { + $monorepo = tiaMonorepoRepository(); + $project = $monorepo['project']; + + file_put_contents($project.'/app/Service.php', "commit('Change the service'); + + file_put_contents($project.'/app/Service.php', " tiaShowEach($git, $monorepo['sha'], ['backend/app/Service.php'])[0]))->toBeFalse() + ->and(tiaWithFakeCatFile($mode, $catFile, fn (): ?array => new ChangedFiles($project)->since($monorepo['sha'])))->toBe(['app/Other.php']); +})->with([ + 'a failed check' => ['--batch-check', 'exit 1'], + 'a check line that does not parse' => ['--batch-check', 'echo "not a header"; exit 0'], + 'a check without a line' => ['--batch-check', 'exit 0'], + 'a failed read' => ['--batch', 'exit 1'], + 'a header that does not parse after one blob' => ['--batch', 'printf "%s blob 1\nx\nnot a header\n" "$first"; exit 0'], + 'a missing blob' => ['--batch', 'exit 0'], + 'bytes after the last blob' => ['--batch', 'printf "%s blob 1\nx\nextra" "$first"; exit 0'], + 'a blob without its line feed' => ['--batch', 'printf "%s blob 1\nxy" "$first"; exit 0'], + 'another blob than the one asked' => ['--batch', 'printf "0123abcd blob 1\nx\n"; exit 0'], +])->skipOnWindows(); + +it('raises a timed out read of the baseline blobs instead of answering', function (): void { + $monorepo = tiaMonorepoRepository(); + $git = new Git($monorepo['root'], 0.5); + + expect(fn (): mixed => tiaWithFakeCatFile('--batch', 'sleep 5; exit 0', fn (): array => tiaShowEach($git, $monorepo['sha'], ['backend/app/Service.php']))) + ->toThrow(GitTimedOut::class, 'Git did not answer within 0.5 seconds: git cat-file --batch'); +})->skipOnWindows(); + +it('reads the baseline of many large changed files within a small memory limit', function (): void { + $root = sys_get_temp_dir().DIRECTORY_SEPARATOR.'pest-tia-baseline-memory-'.bin2hex(random_bytes(8)); + mkdir($root, 0755, true); + tiaMonorepoRoots($root); + + $repo = new GitRepo($root); + $repo->init('master'); + + foreach (range(1, 6) as $number) { + file_put_contents($root.'/asset'.$number.'.bin', random_bytes(8_000_000)); + } + + $repo->commit('Add the large assets'); + $sha = $repo->sha(); + + foreach (range(1, 6) as $number) { + file_put_contents($root.'/asset'.$number.'.bin', 'x', FILE_APPEND); + } + + $script = 'require '.var_export(dirname(__DIR__, 4).'/vendor/autoload.php', true).';' + .'echo json_encode(new Pest\Plugins\Tia\ChangedFiles('.var_export($root, true).')->since('.var_export($sha, true).'));'; + + $process = new Process([PHP_BINARY, '-d', 'memory_limit=64M', '-r', $script]); + $process->run(); + + expect($process->getErrorOutput().$process->getOutput())->not->toContain('Allowed memory size') + ->and($process->getOutput())->toBe('["asset1.bin","asset2.bin","asset3.bin","asset4.bin","asset5.bin","asset6.bin"]'); +})->skipOnWindows(); diff --git a/tests/Visual/Parallel.php b/tests/Visual/Parallel.php index b6a42d29..9e788b71 100644 --- a/tests/Visual/Parallel.php +++ b/tests/Visual/Parallel.php @@ -21,7 +21,7 @@ test('parallel', function () use ($run): void { $output = implode("\n", array_slice(explode("\n", (string) $output), -10)); $profileOutput = $run('tests/Fixtures/Suites/SuccessOnly.php', '--profile'); - $expected = '2 deprecated, 4 warnings, 5 incomplete, 3 notices, 40 todos, 37 skipped, 2005 passed (4169 assertions)'; + $expected = '2 deprecated, 4 warnings, 5 incomplete, 3 notices, 40 todos, 37 skipped, 2019 passed (4196 assertions)'; expect($output) ->toContain("Tests: {$expected}")