fix(tia): record test files the graph does not know during a replay (#2093)

* fix(tia): record test files the graph does not know during a replay

* fix(tia): keep coverage-scoped edges off test files the graph does not know

---------

Co-authored-by: Punyapal Shah <mrpunyapal@gmail.com>
This commit is contained in:
Jhon Farias
2026-12-04 08:12:52 +01:00
committed by GitHub
parent 12bddc0137
commit 2b2a1dab31
7 changed files with 262 additions and 15 deletions
+40 -13
View File
@@ -442,11 +442,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
return null;
}
$projectRoot = TestSuite::getInstance()->rootPath;
$real = @realpath($filename);
$rel = $real !== false
? str_replace(DIRECTORY_SEPARATOR, '/', substr($real, strlen(rtrim($projectRoot, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR)))
: null;
$rel = $this->projectRelativeTestFile($filename);
if ($rel !== null && isset($this->affectedFiles[$rel])) {
$this->affectedCount++;
@@ -490,6 +486,31 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
return $result;
}
private function projectRelativeTestFile(string $filename): ?string
{
$projectRoot = TestSuite::getInstance()->rootPath;
$real = @realpath($filename);
return $real !== false
? str_replace(DIRECTORY_SEPARATOR, '/', substr($real, strlen(rtrim($projectRoot, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR)))
: null;
}
private function refreshesEdgesOf(string $testFile): bool
{
$rel = $this->projectRelativeTestFile($testFile);
if ($rel === null || ! $this->replayGraph instanceof Graph) {
return true;
}
if (! $this->replayGraph->knowsTest($rel)) {
return ! $this->piggybackCoverage;
}
return isset($this->affectedFiles[$rel]);
}
public function getAssertionCount(string $testId): int
{
return $this->cachedAssertionsByTestId[$testId] ?? 0;
@@ -638,7 +659,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
$projectRoot = TestSuite::getInstance()->rootPath;
$perTest = $this->piggybackCoverage
? $this->mergePerTestFiles($this->coverageCollector->perTestFiles(), $recorder->perTestFiles())
? $this->mergePerTestFiles(array_filter($this->coverageCollector->perTestFiles(), $this->refreshesEdgesOf(...), ARRAY_FILTER_USE_KEY), $recorder->perTestFiles())
: $recorder->perTestFiles();
if ($perTest === []) {
@@ -1247,6 +1268,8 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
*/
private function activateWorkerRecorderForReplay(array $arguments): array
{
$this->recorder->recordOnly($this->refreshesEdgesOf(...));
if ($this->piggybackCoverage) {
$this->recorder->activateLinkTracking();
$this->recordingActive = true;
@@ -1257,10 +1280,12 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
$recorder = $this->recorder;
if (! $recorder->driverAvailable()) {
$this->state->write(
self::KEY_WORKER_NO_DRIVER_PREFIX.$this->workerToken().'.json',
'{}',
);
if ($this->affectedFiles !== []) {
$this->state->write(
self::KEY_WORKER_NO_DRIVER_PREFIX.$this->workerToken().'.json',
'{}',
);
}
return $arguments;
}
@@ -1378,7 +1403,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
$this->reportAffectedSummary($changed, $affectedFromChanges, $rerunFromCache, $affected, $outsideProject);
$affectedSet = array_fill_keys($affected, true);
$canRefreshReplayEdges = $affected !== [] && $coverageAvailable;
$canRefreshReplayEdges = $coverageAvailable;
$this->replayRan = true;
$this->replayGraph = $graph;
@@ -1398,6 +1423,8 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
if (! Parallel::isEnabled()) {
if ($canRefreshReplayEdges) {
$this->recorder->recordOnly($this->refreshesEdgesOf(...));
if ($this->piggybackCoverage) {
$this->recorder->activateLinkTracking();
} else {
@@ -2175,7 +2202,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
);
}
$graph->markKnownTestFiles(array_keys($touchedFiles));
$graph->markKnownTestFiles(array_values(array_filter(array_keys($touchedFiles), $this->refreshesEdgesOf(...))));
$graph->pruneStaleResults($this->branch, array_keys($touchedFiles), array_keys($results));
$this->reclaim($graph);
@@ -2276,7 +2303,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument
}
if ($markKnownTestFiles) {
$graph->markKnownTestFiles(array_keys($touchedFiles));
$graph->markKnownTestFiles(array_values(array_filter(array_keys($touchedFiles), $this->refreshesEdgesOf(...))));
}
if ($complete) {
+17
View File
@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace Pest\Plugins\Tia;
use Closure;
use Pest\Support\Arr;
use Pest\Support\Container;
use Pest\TestSuite;
@@ -46,6 +47,9 @@ final class Recorder
private ?SourceScope $sourceScope = null;
/** @var (Closure(string): bool)|null */
private ?Closure $recordsTestFile = null;
public function activate(): void
{
$this->active = true;
@@ -57,6 +61,14 @@ final class Recorder
$this->active = true;
}
/**
* @param Closure(string): bool $recordsTestFile
*/
public function recordOnly(Closure $recordsTestFile): void
{
$this->recordsTestFile = $recordsTestFile;
}
public function isActive(): bool
{
return $this->active;
@@ -103,6 +115,10 @@ final class Recorder
return;
}
if ($this->recordsTestFile instanceof Closure && ! ($this->recordsTestFile)($file)) {
return;
}
$this->currentTestFile = $file;
if ($this->watchPatterns()->isReadCaptureEnabled()) {
@@ -428,6 +444,7 @@ final class Recorder
$this->classFileCache = [];
$this->classUsesDatabaseCache = [];
$this->sourceScope = null;
$this->recordsTestFile = null;
$this->active = false;
$this->captureCoverage = false;
}
+3 -1
View File
@@ -2309,6 +2309,8 @@
✓ activateLinkTracking() → it tracks inertia components without a coverage driver
✓ activateLinkTracking() → it tracks linked sources across consecutive tests
✓ activateLinkTracking() → it records nothing while inactive
✓ recordOnly() → it records only the test files it accepts
✓ recordOnly() → it records each test file again after a reset
PASS Tests\Unit\Plugins\Tia\ResultKey
✓ it keys a result per dataset row rather than per method
@@ -2882,4 +2884,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, 44 skipped, 2136 passed (4703 assertions)
Tests: 2 deprecated, 4 warnings, 5 incomplete, 2 notices, 40 todos, 44 skipped, 2138 passed (4706 assertions)
@@ -0,0 +1,99 @@
<?php
declare(strict_types=1);
use Pest\Support\Coverage;
use Tests\Fixtures\Tia\Project;
afterEach(function (): void {
Project::destroyAll();
});
function addTestFileThatReadsOutsideTheCoverageSource(Project $project): void
{
$project->write('support/salutation.php', <<<'PHP'
<?php
return 'visitor';
PHP);
$project->write('tests/Integration/WelcomeTest.php', <<<'PHP'
<?php
declare(strict_types=1);
use Fixture\App\Greeter;
test('welcomes a visitor', function (): void {
$name = require dirname(__DIR__, 2).'/support/salutation.php';
expect((new Greeter)->greet($name))->toBe('Hello, visitor!');
});
PHP);
$project->git()->commit('add a test file the graph does not know');
$project->seed('master');
}
function forgetWelcomeTest(Project $project): void
{
$project->mutateGraph(function (array $graph): array {
unset($graph['edges']['tests/Integration/WelcomeTest.php']);
return $graph;
});
}
test('a coverage replay does not narrow the edges of a test file the graph does not know', function (array $arguments): void {
$project = Project::make('master');
addTestFileThatReadsOutsideTheCoverageSource($project);
$baseline = $project->pest('--tia', '--coverage', ...$arguments);
expect($baseline->exitCode)->toBe(0, $baseline->describe());
forgetWelcomeTest($project);
$coverage = $project->pest('--tia', '--coverage', ...$arguments);
expect($coverage->exitCode)->toBe(0, $coverage->describe())
->and($coverage->uncached())->toBe(1, $coverage->describe())
->and($project->graph()['edges'] ?? [])->not->toHaveKey('tests/Integration/WelcomeTest.php');
$project->write('support/salutation.php', <<<'PHP'
<?php
return 'stranger';
PHP);
$project->git()->commit('change the salutation');
$result = $project->pest('--tia', ...$arguments);
expect($result->exitCode)->toBe(1, $result->describe());
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows()->skip(! Coverage::isAvailable(), 'Coverage is not available');
test('a coverage replay with affected test files does not mark a test file the graph does not know as known', function (array $arguments): void {
$project = Project::make('master');
addTestFileThatReadsOutsideTheCoverageSource($project);
$baseline = $project->pest('--tia', '--coverage', ...$arguments);
expect($baseline->exitCode)->toBe(0, $baseline->describe());
forgetWelcomeTest($project);
$project->write('app/Calculator.php', str_replace(
'return $a + $b;',
'return ($a + $b);',
(string) file_get_contents($project->path('app/Calculator.php')),
));
$project->git()->commit('touch the calculator');
$coverage = $project->pest('--tia', '--coverage', ...$arguments);
expect($coverage->exitCode)->toBe(0, $coverage->describe())
->and($coverage->affected())->toBeGreaterThan(0, $coverage->describe())
->and($coverage->uncached())->toBe(1, $coverage->describe())
->and($project->graph()['edges'] ?? [])->not->toHaveKey('tests/Integration/WelcomeTest.php');
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows()->skip(! Coverage::isAvailable(), 'Coverage is not available');
+69
View File
@@ -0,0 +1,69 @@
<?php
declare(strict_types=1);
use Pest\Support\Coverage;
use Tests\Fixtures\Tia\Project;
afterEach(function (): void {
Project::destroyAll();
});
function addTestFileTheGraphDoesNotKnow(Project $project): void
{
$project->write('tests/Integration/WelcomeTest.php', <<<'PHP'
<?php
declare(strict_types=1);
use Fixture\App\Greeter;
test('welcomes a visitor', function (): void {
expect((new Greeter)->greet('visitor'))->toBe('Hello, visitor!');
});
PHP);
$project->git()->commit('add a test file the graph does not know');
}
test('a replay records a test file the graph does not know', function (array $arguments): void {
$project = Project::make('master');
addTestFileTheGraphDoesNotKnow($project);
$project->seed('master');
$first = $project->pest('--tia', ...$arguments);
expect($first->exitCode)->toBe(0, $first->describe())
->and($first->replayed())->toBe(Project::TOTAL_TESTS, $first->describe())
->and($first->uncached())->toBe(1, $first->describe())
->and($project->graph()['edges'] ?? [])->toHaveKey('tests/Integration/WelcomeTest.php');
$second = $project->pest('--tia', ...$arguments);
expect($second->exitCode)->toBe(0, $second->describe())
->and($second->replayed())->toBe(Project::TOTAL_TESTS + 1, $second->describe())
->and($second->uncached())->toBe(0, $second->describe());
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows()->skip(! Coverage::isAvailable(), 'Coverage is not available');
test('a replay that records a test file the graph does not know keeps the edges of the known test files', function (array $arguments): void {
$project = Project::make('master');
addTestFileTheGraphDoesNotKnow($project);
$project->seed('master', failing: ['greets a person']);
$project->mutateGraph(function (array $graph): array {
$graph['edges']['tests/Unit/GreeterTest.php'][] = array_search('app/Calculator.php', $graph['files'], true);
return $graph;
});
$known = $project->graph()['edges'] ?? [];
$result = $project->pest('--tia', ...$arguments);
$edges = $project->graph()['edges'] ?? [];
expect($result->exitCode)->toBe(0, $result->describe())
->and($edges)->toHaveKey('tests/Integration/WelcomeTest.php');
unset($edges['tests/Integration/WelcomeTest.php']);
expect($edges)->toBe($known);
})->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows()->skip(! Coverage::isAvailable(), 'Coverage is not available');
+33
View File
@@ -58,3 +58,36 @@ describe('activateLinkTracking()', function (): void {
expect($recorder->perTestTables())->toBeEmpty();
});
});
describe('recordOnly()', function (): void {
it('records only the test files it accepts', function (): void {
$recorder = new Recorder;
$recorder->activateLinkTracking();
$recorder->recordOnly(fn (string $testFile): bool => $testFile === '/project/tests/Feature/NewTest.php');
$recorder->beginTest('Some\Missing\TestClass', 'known', '/project/tests/Feature/KnownTest.php');
$recorder->linkSource('/project/app/Known.php');
$recorder->linkTable('known');
$recorder->endTest();
$recorder->beginTest('Some\Missing\TestClass', 'new', '/project/tests/Feature/NewTest.php');
$recorder->linkSource('/project/app/New.php');
$recorder->endTest();
expect($recorder->perTestFiles())->toBe(['/project/tests/Feature/NewTest.php' => ['/project/app/New.php']])
->and($recorder->perTestTables())->toBeEmpty();
});
it('records each test file again after a reset', function (): void {
$recorder = new Recorder;
$recorder->recordOnly(fn (string $testFile): bool => false);
$recorder->reset();
$recorder->activateLinkTracking();
$recorder->beginTest('Some\Missing\TestClass', 'known', '/project/tests/Feature/KnownTest.php');
$recorder->linkSource('/project/app/Known.php');
$recorder->endTest();
expect($recorder->perTestFiles())->toBe(['/project/tests/Feature/KnownTest.php' => ['/project/app/Known.php']]);
});
});
+1 -1
View File
@@ -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, 36 skipped, 1989 passed (4141 assertions)';
$expected = '2 deprecated, 4 warnings, 5 incomplete, 3 notices, 40 todos, 36 skipped, 1991 passed (4144 assertions)';
expect($output)
->toContain("Tests: {$expected}")