From 7cdebc6a9555fba1d6e1e916b6fa342d0fa68113 Mon Sep 17 00:00:00 2001 From: Caleb White Date: Mon, 14 Sep 2026 08:56:59 -0500 Subject: [PATCH] fix(tia): persist state on detached HEAD- #1844 (#1891) * refactor: extract shared CI detection utility Consolidate duplicated CI environment detection logic from Snapshot and BaselineSync into a shared Pest\Support\Ci class. This reduces duplication and provides a single source of truth for CI detection, including comprehensive environment variable checks for all major CI providers. * fix(tia): persist state on detached HEAD Allow detached checkouts to write, delete, and rebuild TIA state so baseline publishers and local detached workflows produce a usable graph. Resolve the writable baseline from the Git branch, CI branch metadata, or a stable workspace key. Keep the default branch as the read fallback so local workspaces can use a published baseline without changing it. --- src/Plugins/Snapshot.php | 37 +--------- src/Plugins/Tia.php | 71 +++++++++++++------ src/Plugins/Tia/BaselineSync.php | 10 +-- .../Tia/{CiDefaultBranch.php => CiBranch.php} | 17 ++++- src/Plugins/Tia/Cis/GitHub.php | 5 ++ src/Plugins/Tia/Cis/GitLab.php | 5 ++ src/Plugins/Tia/Contracts/Ci.php | 2 + src/Plugins/Tia/FileState.php | 16 +---- src/Plugins/Tia/Graph.php | 6 ++ src/Support/Ci.php | 47 ++++++++++++ tests/Features/Tia/BranchShapes.php | 9 ++- tests/Features/Tia/DefaultBranchWriteTier.php | 33 ++++++++- tests/Features/Tia/StateReclamation.php | 12 ++-- tests/Fixtures/Tia/Project.php | 15 ++-- 14 files changed, 189 insertions(+), 96 deletions(-) rename src/Plugins/Tia/{CiDefaultBranch.php => CiBranch.php} (58%) create mode 100644 src/Support/Ci.php diff --git a/src/Plugins/Snapshot.php b/src/Plugins/Snapshot.php index e210b4f7..863147ea 100644 --- a/src/Plugins/Snapshot.php +++ b/src/Plugins/Snapshot.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace Pest\Plugins; use Pest\Contracts\Plugins\HandlesArguments; +use Pest\Support\Ci; use Pest\TestSuite; /** @@ -16,34 +17,9 @@ final class Snapshot implements HandlesArguments public static bool $updateSnapshots = false; - /** - * @var list - */ - private const array CI_ENVIRONMENT_VARIABLES = [ - 'CI', - 'GITHUB_ACTIONS', - 'GITLAB_CI', - 'CIRCLECI', - 'TRAVIS', - 'APPVEYOR', - 'BITBUCKET_BUILD_NUMBER', - 'BUILDKITE', - 'TEAMCITY_VERSION', - 'JENKINS_URL', - 'SYSTEM_COLLECTIONURI', - 'CI_NAME', - 'TASKCLUSTER_ROOT_URL', - 'DRONE', - 'WERCKER', - 'NEVERCODE', - 'SEMAPHORE', - 'NETLIFY', - 'NOW_BUILDER', - ]; - public static function shouldCreateMissingSnapshots(): bool { - return self::$updateSnapshots || ! self::runningOnCI(); + return self::$updateSnapshots || ! Ci::isRunning(); } /** @@ -149,13 +125,4 @@ final class Snapshot implements HandlesArguments return true; } - - private static function runningOnCI(): bool - { - if (Environment::name() === Environment::CI) { - return true; - } - - return array_any(self::CI_ENVIRONMENT_VARIABLES, fn (string $environmentVariable): bool => getenv($environmentVariable) !== false); - } } diff --git a/src/Plugins/Tia.php b/src/Plugins/Tia.php index d3f329a2..f334e933 100644 --- a/src/Plugins/Tia.php +++ b/src/Plugins/Tia.php @@ -20,7 +20,7 @@ use Pest\Panic; use Pest\Plugins\Concerns\HandleArguments; use Pest\Plugins\Tia\BaselineSync; use Pest\Plugins\Tia\ChangedFiles; -use Pest\Plugins\Tia\CiDefaultBranch; +use Pest\Plugins\Tia\CiBranch; use Pest\Plugins\Tia\Contracts\State; use Pest\Plugins\Tia\CoverageCollector; use Pest\Plugins\Tia\Fingerprint; @@ -196,8 +196,6 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument private bool $unreadableGraphReported = false; - private bool $detachedHead = false; - private bool $graphUnreachable = false; private bool $fullSuiteFallbackRan = false; @@ -283,19 +281,11 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument private function deleteState(string $key): bool { - if ($this->detachedHead) { - return false; - } - return $this->state->delete($key); } private function saveGraph(Graph $graph): bool { - if ($this->detachedHead) { - return true; - } - $json = $graph->encode(); if ($json === null) { @@ -793,8 +783,10 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument return $this->reconcileFingerprint($rebuilt, $current); } - $this->deleteState(self::KEY_GRAPH); - $this->deleteState(self::KEY_COVERAGE_CACHE); + if ($this->canRebuildGraph()) { + $this->deleteState(self::KEY_GRAPH); + $this->deleteState(self::KEY_COVERAGE_CACHE); + } return null; } @@ -851,8 +843,8 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument $fingerprint = Fingerprint::compute($projectRoot); $this->startFingerprint = $fingerprint; - if ($forceRebuild && ! $this->detachedHead) { - Storage::purge($projectRoot); + if ($forceRebuild && $this->canRebuildGraph()) { + $this->purgeState(); } $graph = ($forceRebuild || $this->forceRefetch) ? null : $this->loadGraph($projectRoot); @@ -912,6 +904,29 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument return $this->enterRecordMode($arguments); } + private function purgeState(): void + { + foreach ([ + self::KEY_GRAPH, + self::KEY_AFFECTED, + self::KEY_COVERAGE_CACHE, + self::KEY_COVERAGE_MARKER, + self::KEY_FETCH_COOLDOWN, + ] as $key) { + $this->state->delete($key); + } + + foreach ([ + self::KEY_WORKER_EDGES_PREFIX, + self::KEY_WORKER_RESULTS_PREFIX, + self::KEY_WORKER_NO_DRIVER_PREFIX, + ] as $prefix) { + foreach ($this->state->keysWithPrefix($prefix) as $key) { + $this->state->delete($key); + } + } + } + /** * @param array $arguments * @return array @@ -1233,6 +1248,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument $recorder = $this->recorder; if (! $this->piggybackCoverage && ! $recorder->driverAvailable()) { + $this->requestWorkerResults(); $this->emitCoverageDriverMissing(); return $arguments; @@ -1282,6 +1298,11 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument return $arguments; } + private function canRebuildGraph(): bool + { + return ! $this->piggybackCoverage && $this->recorder->driverAvailable(); + } + private function renderFreshGraph(): void { if ($this->driftLabel === null && $this->freshGraphReason !== null) { @@ -1948,10 +1969,17 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument Parallel::setGlobal(self::FALLBACK_BRANCH_GLOBAL, $this->fallbackBranch); - $currentBranch = $changedFiles->currentBranch(); + $this->branch = $changedFiles->currentBranch() + ?? CiBranch::detectCurrent() + ?? $this->workspaceBranch($projectRoot); + } - $this->detachedHead = $currentBranch === null; - $this->branch = $currentBranch ?? $this->fallbackBranch; + private function workspaceBranch(string $projectRoot): string + { + $realProjectRoot = realpath($projectRoot); + $hash = hash('sha256', $realProjectRoot === false ? $projectRoot : $realProjectRoot); + + return Graph::WORKSPACE_BRANCH_PREFIX.substr($hash, 0, 16); } private function resolveFallbackBranch(ChangedFiles $changedFiles): ?string @@ -1963,7 +1991,7 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument } return $this->watchPatterns->defaultBranch() - ?? CiDefaultBranch::detect() + ?? CiBranch::detectDefault() ?? $changedFiles->defaultBranch() ?? $this->soleRecordedBranch(); } @@ -1976,7 +2004,10 @@ final class Tia implements AddsOutput, HandlesArguments, HandlesOriginalArgument return null; } - $branches = Graph::branchesIn($json); + $branches = array_values(array_filter( + Graph::branchesIn($json), + fn (string $branch): bool => ! str_starts_with($branch, Graph::WORKSPACE_BRANCH_PREFIX), + )); return count($branches) === 1 ? $branches[0] : null; } diff --git a/src/Plugins/Tia/BaselineSync.php b/src/Plugins/Tia/BaselineSync.php index 3c652b69..986d01d3 100644 --- a/src/Plugins/Tia/BaselineSync.php +++ b/src/Plugins/Tia/BaselineSync.php @@ -9,6 +9,7 @@ use Pest\Panic; use Pest\Plugins\Tia; use Pest\Plugins\Tia\Baselines\BaseRemote; use Pest\Plugins\Tia\Contracts\State; +use Pest\Support\Ci; use Pest\Support\View; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Process\Process; @@ -160,7 +161,7 @@ final readonly class BaselineSync private function emitPublishInstructions(): void { - if ($this->isCi()) { + if (Ci::isRunning()) { $this->renderBadge('INFO', 'No baseline yet — this run will produce one.'); return; @@ -170,13 +171,6 @@ final readonly class BaselineSync $this->renderChild('See https://pestphp.com/docs/tia for how to publish one from CI.'); } - private function isCi(): bool - { - return getenv('GITHUB_ACTIONS') === 'true' - || getenv('GITLAB_CI') === 'true' - || getenv('CIRCLECI') === 'true'; - } - /** * @return array{payload: array{graph: string, coverage: ?string, sizeOnDisk: int}|null, failureKind: ?string} */ diff --git a/src/Plugins/Tia/CiDefaultBranch.php b/src/Plugins/Tia/CiBranch.php similarity index 58% rename from src/Plugins/Tia/CiDefaultBranch.php rename to src/Plugins/Tia/CiBranch.php index 682a506e..99a4dcb4 100644 --- a/src/Plugins/Tia/CiDefaultBranch.php +++ b/src/Plugins/Tia/CiBranch.php @@ -9,7 +9,7 @@ use Pest\Plugins\Tia\Contracts\Ci; /** * @internal */ -final class CiDefaultBranch +final class CiBranch { /** * @var array> @@ -19,7 +19,20 @@ final class CiDefaultBranch Cis\GitHub::class, ]; - public static function detect(): ?string + public static function detectCurrent(): ?string + { + foreach (self::CIS as $class) { + $branch = (new $class)->currentBranch(); + + if ($branch !== null) { + return $branch; + } + } + + return null; + } + + public static function detectDefault(): ?string { foreach (self::CIS as $class) { $branch = (new $class)->defaultBranch(); diff --git a/src/Plugins/Tia/Cis/GitHub.php b/src/Plugins/Tia/Cis/GitHub.php index b0d5d787..412759b7 100644 --- a/src/Plugins/Tia/Cis/GitHub.php +++ b/src/Plugins/Tia/Cis/GitHub.php @@ -14,6 +14,11 @@ final readonly class GitHub implements Ci { use ReadsEnvironment; + public function currentBranch(): ?string + { + return $this->environment('GITHUB_REF_NAME'); + } + public function defaultBranch(): ?string { $path = $this->environment('GITHUB_EVENT_PATH'); diff --git a/src/Plugins/Tia/Cis/GitLab.php b/src/Plugins/Tia/Cis/GitLab.php index 06db0f1b..4850738e 100644 --- a/src/Plugins/Tia/Cis/GitLab.php +++ b/src/Plugins/Tia/Cis/GitLab.php @@ -14,6 +14,11 @@ final readonly class GitLab implements Ci { use ReadsEnvironment; + public function currentBranch(): ?string + { + return $this->environment('CI_COMMIT_BRANCH'); + } + public function defaultBranch(): ?string { return $this->environment('CI_DEFAULT_BRANCH'); diff --git a/src/Plugins/Tia/Contracts/Ci.php b/src/Plugins/Tia/Contracts/Ci.php index e5e72027..bbb6f82e 100644 --- a/src/Plugins/Tia/Contracts/Ci.php +++ b/src/Plugins/Tia/Contracts/Ci.php @@ -9,5 +9,7 @@ namespace Pest\Plugins\Tia\Contracts; */ interface Ci { + public function currentBranch(): ?string; + public function defaultBranch(): ?string; } diff --git a/src/Plugins/Tia/FileState.php b/src/Plugins/Tia/FileState.php index c8618da6..de3e741b 100644 --- a/src/Plugins/Tia/FileState.php +++ b/src/Plugins/Tia/FileState.php @@ -9,11 +9,9 @@ use Pest\Plugins\Tia\Contracts\State; /** * @internal */ -final class FileState implements State +final readonly class FileState implements State { - private readonly string $rootDir; - - private ?string $resolvedRoot = null; + private string $rootDir; public function __construct(string $rootDir) { @@ -106,17 +104,9 @@ final class FileState implements State private function resolvedRoot(): ?string { - if ($this->resolvedRoot !== null) { - return $this->resolvedRoot; - } - $resolved = @realpath($this->rootDir); - if ($resolved === false) { - return null; - } - - return $this->resolvedRoot = $resolved; + return $resolved === false ? null : $resolved; } private function ensureRoot(): bool diff --git a/src/Plugins/Tia/Graph.php b/src/Plugins/Tia/Graph.php index 8342e39a..aa756512 100644 --- a/src/Plugins/Tia/Graph.php +++ b/src/Plugins/Tia/Graph.php @@ -18,6 +18,8 @@ use PHPUnit\TextUI\Configuration\Registry; */ final class Graph { + public const string WORKSPACE_BRANCH_PREFIX = '@workspace:'; + /** * @var array */ @@ -1628,6 +1630,10 @@ final class Graph $survivors = array_fill_keys($keep, true); foreach (array_keys($this->baselines) as $branch) { + if (str_starts_with($branch, self::WORKSPACE_BRANCH_PREFIX)) { + continue; + } + if (! isset($survivors[$branch])) { unset($this->baselines[$branch]); } diff --git a/src/Support/Ci.php b/src/Support/Ci.php new file mode 100644 index 00000000..3c3620b4 --- /dev/null +++ b/src/Support/Ci.php @@ -0,0 +1,47 @@ + + */ + private const array ENVIRONMENT_VARIABLES = [ + 'CI', + 'GITHUB_ACTIONS', + 'GITLAB_CI', + 'CIRCLECI', + 'TRAVIS', + 'APPVEYOR', + 'BITBUCKET_BUILD_NUMBER', + 'BUILDKITE', + 'TEAMCITY_VERSION', + 'JENKINS_URL', + 'SYSTEM_COLLECTIONURI', + 'CI_NAME', + 'TASKCLUSTER_ROOT_URL', + 'DRONE', + 'WERCKER', + 'NEVERCODE', + 'SEMAPHORE', + 'NETLIFY', + 'NOW_BUILDER', + ]; + + public static function isRunning(): bool + { + if (Environment::name() === Environment::CI) { + return true; + } + + return array_any(self::ENVIRONMENT_VARIABLES, fn (string $env): bool => getenv($env) !== false); + } +} diff --git a/tests/Features/Tia/BranchShapes.php b/tests/Features/Tia/BranchShapes.php index d0e5a095..52c5aeb3 100644 --- a/tests/Features/Tia/BranchShapes.php +++ b/tests/Features/Tia/BranchShapes.php @@ -115,7 +115,7 @@ test('a narrowed run does not reclaim anything', function (): void { ->and($delta->isResultsOnly())->toBeTrue($delta->summary()); })->skipOnWindows(); -test('a detached HEAD does not reclaim anything either', function (): void { +test('a detached HEAD reclaims missing branches without changing the default baseline', function (): void { $project = Project::make('master'); $project->seed('master'); @@ -130,8 +130,11 @@ test('a detached HEAD does not reclaim anything either', function (): void { $project->pest('--tia'); $delta = $project->delta(); - expect($project->branchKeys())->toBe(['master', 'feature-x']) - ->and($delta->isHardSuppressed())->toBeTrue($delta->summary()); + expect($project->branchKeys())->toHaveCount(2) + ->and($project->branchKeys())->toContain('master') + ->and($project->branchKeys())->not->toContain('feature-x') + ->and($delta->baselineUntouched('master'))->toBeTrue($delta->summary()) + ->and($delta->structureMoved())->toBeTrue($delta->summary()); })->skipOnWindows(); test('the default branch baseline survives every branch that comes and goes', function (): void { diff --git a/tests/Features/Tia/DefaultBranchWriteTier.php b/tests/Features/Tia/DefaultBranchWriteTier.php index 6bc6a2cc..1ef72613 100644 --- a/tests/Features/Tia/DefaultBranchWriteTier.php +++ b/tests/Features/Tia/DefaultBranchWriteTier.php @@ -104,17 +104,20 @@ test('filtered mode finds nothing to do on the default branch itself', function ->and($delta->isHardSuppressed())->toBeTrue($delta->summary()); })->skipOnWindows(); -test('a detached HEAD replays without minting a branch key', function (): void { +test('a detached HEAD replays through a workspace baseline', function (): void { $project = Project::make('master'); $project->seed('master'); $project->git()->detach(); $result = $project->pest('--tia'); + $hasWorkspaceBranch = array_any($project->branchKeys(), fn (string $branch): bool => str_starts_with($branch, '@workspace:')); expect($result->replayed())->toBe(Project::TOTAL_TESTS, $result->describe()) ->and($result->uncached())->toBe(0, $result->describe()) - ->and($project->branchKeys())->toBe(['master']); + ->and($project->branchKeys())->toHaveCount(2) + ->and($project->branchKeys())->toContain('master') + ->and($hasWorkspaceBranch)->toBeTrue(); })->skipOnWindows(); test('a detached HEAD does not write into the default branch baseline', function (array $arguments): void { @@ -125,9 +128,13 @@ test('a detached HEAD does not write into the default branch baseline', function $project->pest(...$arguments); $delta = $project->delta(); + $hasWorkspaceBranch = array_any($project->branchKeys(), fn (string $branch): bool => str_starts_with($branch, '@workspace:')); expect($delta->baselineUntouched('master'))->toBeTrue($delta->summary()) - ->and($project->branchKeys())->toBe(['master']); + ->and($project->branchKeys())->toHaveCount(2) + ->and($project->branchKeys())->toContain('master') + ->and($hasWorkspaceBranch)->toBeTrue() + ->and($delta->writtenCount())->toBe(0, $delta->summary()); })->with([ 'sequential' => [['--filter=adds two numbers']], 'parallel' => [['--parallel', '--processes=2', '--filter=adds two numbers']], @@ -147,6 +154,26 @@ test('the branch that ran gets its own key and the default branch keeps its base ->and($delta->writtenCount())->toBe(0, $delta->summary()); })->skipOnWindows(); +test('a detached CI branch writes into its branch baseline', function (array $environment): void { + $project = Project::make('master'); + $project->seed('master'); + + $project->git()->detach(); + $project->pestWithEnvironment($project->path(), $environment, '--filter=adds two numbers'); + + expect($project->branchKeys())->toBe(['master', 'feature-x']) + ->and(array_any($project->branchKeys(), fn (string $branch): bool => str_starts_with($branch, '@workspace:')))->toBeFalse(); +})->with([ + 'GitLab' => [[ + 'GITLAB_CI' => 'true', + 'CI_COMMIT_BRANCH' => 'feature-x', + ]], + 'GitHub' => [[ + 'GITHUB_ACTIONS' => 'true', + 'GITHUB_REF_NAME' => 'feature-x', + ]], +])->skipOnWindows(); + test('the fallback reaches parallel workers', function (): void { $project = Project::make('master'); $project->seed('master'); diff --git a/tests/Features/Tia/StateReclamation.php b/tests/Features/Tia/StateReclamation.php index e43b8217..8687438e 100644 --- a/tests/Features/Tia/StateReclamation.php +++ b/tests/Features/Tia/StateReclamation.php @@ -8,7 +8,7 @@ afterEach(function (): void { Project::destroyAll(); }); -test('a detached HEAD does not purge the graph on structural drift', function (array $arguments): void { +test('a detached HEAD can rebuild the graph on structural drift', function (array $arguments): void { $project = Project::make('master'); $project->seed('master'); @@ -25,10 +25,10 @@ test('a detached HEAD does not purge the graph on structural drift', function (a expect($result->exitCode)->toBe(0, $result->describe()) ->and($project->graphExists())->toBeTrue('the detached run deleted graph.json') - ->and($delta->isHardSuppressed())->toBeTrue($delta->summary()); + ->and($delta->structureMoved())->toBeTrue($delta->summary()); })->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows(); -test('a detached HEAD does not purge the graph with --fresh either', function (array $arguments): void { +test('a detached HEAD can rebuild the graph with --fresh', function (array $arguments): void { $project = Project::make('master'); $project->seed('master'); @@ -39,10 +39,10 @@ test('a detached HEAD does not purge the graph with --fresh either', function (a expect($result->exitCode)->toBe(0, $result->describe()) ->and($project->graphExists())->toBeTrue('the detached --fresh run deleted graph.json') - ->and($delta->isHardSuppressed())->toBeTrue($delta->summary()); + ->and($delta->structureMoved())->toBeTrue($delta->summary()); })->with(Project::SEQUENTIAL_AND_PARALLEL)->skipOnWindows(); -test('a detached HEAD leaves an unreadable graph for a checkout that can rebuild it', function (): void { +test('a detached HEAD can replace an unreadable graph for a checkout that can rebuild it', function (): void { $project = Project::make('master'); $project->seed('master'); @@ -54,7 +54,7 @@ test('a detached HEAD leaves an unreadable graph for a checkout that can rebuild expect($result->exitCode)->toBe(0, $result->describe()) ->and($result->tally())->toContain(Project::TOTAL_TESTS.' passed') - ->and(file_get_contents($project->graphDir().'/graph.json'))->toBe('{not json'); + ->and(file_get_contents($project->graphDir().'/graph.json'))->not->toBe('{not json'); })->skipOnWindows(); test('a cached failure whose test file was deleted stops widening later runs', function (array $arguments): void { diff --git a/tests/Fixtures/Tia/Project.php b/tests/Fixtures/Tia/Project.php index 49cce643..04d9f463 100644 --- a/tests/Fixtures/Tia/Project.php +++ b/tests/Fixtures/Tia/Project.php @@ -157,7 +157,7 @@ final class Project } /** - * @param array $environment + * @param array $environment */ public function pestWithEnvironment(string $directory, array $environment, string ...$arguments): PestResult { @@ -172,11 +172,14 @@ final class Project 'PAO_DISABLE' => '1', 'XDEBUG_MODE' => 'coverage', 'HOME' => $this->home(), - 'GITHUB_EVENT_PATH' => '', - 'CI_DEFAULT_BRANCH' => '', - 'GITHUB_ACTIONS' => '', - 'GITLAB_CI' => '', - 'CIRCLECI' => '', + 'CI' => false, + 'GITHUB_EVENT_PATH' => false, + 'CI_DEFAULT_BRANCH' => false, + 'CI_COMMIT_BRANCH' => false, + 'GITHUB_ACTIONS' => false, + 'GITHUB_REF_NAME' => false, + 'GITLAB_CI' => false, + 'CIRCLECI' => false, ...$environment, ], );