diff --git a/.changelog/workflow-status-readiness.md b/.changelog/workflow-status-readiness.md new file mode 100644 index 000000000..7dbb7b75d --- /dev/null +++ b/.changelog/workflow-status-readiness.md @@ -0,0 +1,6 @@ +--- +category: fixed +type: patch +--- + +Allow bounded retries for GitHub Actions metadata lag before mirroring required PHP matrix statuses, using only verified results from the current attempt. Use a full rerun or a fresh dispatch to refresh required statuses. diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index e207cbd4a..350a246ac 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -146,21 +146,29 @@ jobs: if (count($versions) !== count(array_unique($versions))) { throw new RuntimeException('Duplicate PHP test matrix entry.'); } - $run = githubApi(["repos/$repository/actions/runs/$runId"]); - if ((string) ($run['id'] ?? '') !== $runId) { - throw new RuntimeException('Workflow run ID does not match the current run.'); - } - if (($run['repository']['full_name'] ?? null) !== $repository) { - throw new RuntimeException('Workflow repository does not match the current repository.'); - } - if (!is_int($run['run_attempt'] ?? null)) { - throw new RuntimeException('Workflow run attempt is not an integer.'); - } - if ((string) $run['run_attempt'] !== $attempt) { - throw new RuntimeException('Workflow run attempt does not match the current attempt.'); - } - if (($run['status'] ?? null) !== 'in_progress') { - throw new RuntimeException('Workflow run status is not in_progress.'); + // The API can briefly lag behind the runner that started this job. + for ($poll = 1; ; ++$poll) { + $run = githubApi(["repos/$repository/actions/runs/$runId"]); + if ((string) ($run['id'] ?? '') !== $runId) { + throw new RuntimeException('Workflow run ID does not match the current run.'); + } + if (($run['repository']['full_name'] ?? null) !== $repository) { + throw new RuntimeException('Workflow repository does not match the current repository.'); + } + if (!is_int($run['run_attempt'] ?? null)) { + throw new RuntimeException('Workflow run attempt is not an integer.'); + } + if ((string) $run['run_attempt'] !== $attempt) { + throw new RuntimeException('Workflow run attempt does not match the current attempt.'); + } + $status = $run['status'] ?? null; + if ($status === 'in_progress') { + break; + } + if ($poll === 8 || !in_array($status, ['queued', 'requested', 'waiting', 'pending'], true)) { + throw new RuntimeException('Workflow run status is not in_progress.'); + } + sleep(3); } // Validate the full matrix and current attempt before the first write. @@ -309,7 +317,7 @@ jobs: - Dependency health result: `${{ needs.dependency-health.result }}` publish_required_statuses: - if: ${{ always() && inputs.publish-required-statuses && github.actor != 'dependabot[bot]' && needs.publish_pending_statuses.result == 'success' && (needs.tests.result == 'success' || needs.tests.result == 'failure') }} + if: ${{ !cancelled() && inputs.publish-required-statuses && github.actor != 'dependabot[bot]' && needs.publish_pending_statuses.result == 'success' && (needs.tests.result == 'success' || needs.tests.result == 'failure') }} name: Publish Required Test Statuses needs: - resolve_php @@ -327,67 +335,112 @@ jobs: TARGET_SHA: ${{ github.sha }} TARGET_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} TEST_MATRIX: ${{ needs.resolve_php.outputs.test-matrix }} + TEST_RESULT: ${{ needs.tests.result }} run: | export TEST_JOBS_FILE="${RUNNER_TEMP}/required-test-jobs.json" - gh api --paginate --slurp \ - "repos/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}/jobs?filter=all&per_page=100" > "$TEST_JOBS_FILE" + # Wait for the API to reflect completed matrix dependencies. Only the + # explicit readiness exit code is retried; malformed evidence fails closed. + for poll in {1..8}; do + gh api --paginate --slurp \ + "repos/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}/jobs?filter=all&per_page=100" > "$TEST_JOBS_FILE" - # PHP evaluates these variables; Bash must leave them literal. - # shellcheck disable=SC2016 - php -r ' - $matrix = json_decode(getenv("TEST_MATRIX"), true, 512, JSON_THROW_ON_ERROR); - $versions = $matrix["php-version"] ?? null; - if (!is_array($versions) || $versions === []) { - throw new RuntimeException("A non-empty PHP test matrix is required."); - } - foreach ($versions as $version) { - if (!is_string($version) || preg_match("/\A[0-9]+\.[0-9]+\z/", $version) !== 1) { - throw new RuntimeException("Unsupported PHP test matrix entry."); + # PHP evaluates these variables; Bash must leave them literal. + # shellcheck disable=SC2016 + if results=$(php -d display_errors=stderr -r ' + $matrix = json_decode(getenv("TEST_MATRIX"), true, 512, JSON_THROW_ON_ERROR); + $versions = $matrix["php-version"] ?? null; + if (!is_array($versions) || $versions === [] || !array_is_list($versions)) { + throw new RuntimeException("A non-empty PHP test matrix is required."); + } + foreach ($versions as $version) { + if (!is_string($version) || preg_match("/\A[0-9]+\.[0-9]+\z/", $version) !== 1) { + throw new RuntimeException("Unsupported PHP test matrix entry."); + } } - } - if (count($versions) !== count(array_unique($versions))) { - throw new RuntimeException("Duplicate PHP test matrix entry."); - } - $pages = json_decode(file_get_contents(getenv("TEST_JOBS_FILE")), true, 512, JSON_THROW_ON_ERROR); - $jobs = []; - foreach ($pages as $page) { - if (!is_array($page["jobs"] ?? null)) { + if (count($versions) !== count(array_unique($versions))) { + throw new RuntimeException("Duplicate PHP test matrix entry."); + } + $pages = json_decode(file_get_contents(getenv("TEST_JOBS_FILE")), true, 512, JSON_THROW_ON_ERROR); + if (!is_array($pages) || $pages === [] || !array_is_list($pages)) { throw new RuntimeException("Malformed workflow jobs response."); } - $jobs = array_merge($jobs, $page["jobs"]); - } - $results = []; - foreach ($versions as $version) { - $name = "Run Tests (" . $version . ")"; - $matches = array_values(array_filter($jobs, static function ($job) use ($name) { - return is_string($job["name"] ?? null) - && ($job["name"] === $name || str_ends_with($job["name"], " / " . $name)); - })); - if ($matches === []) { - throw new RuntimeException("Missing workflow job for " . $version); + $jobs = []; + foreach ($pages as $page) { + if (!is_array($page["jobs"] ?? null) || !array_is_list($page["jobs"])) { + throw new RuntimeException("Malformed workflow jobs response."); + } + $jobs = array_merge($jobs, $page["jobs"]); + } + $attempt = getenv("GITHUB_RUN_ATTEMPT"); + if (!is_string($attempt) || preg_match("/\A[1-9][0-9]*\z/", $attempt) !== 1) { + throw new RuntimeException("Invalid current workflow attempt."); } - foreach ($matches as $candidate) { - if ((string) ($candidate["run_id"] ?? "") !== getenv("GITHUB_RUN_ID") - || !is_int($candidate["run_attempt"] ?? null) || $candidate["run_attempt"] < 1) { - throw new RuntimeException("Invalid workflow job attempt for " . $version); + $expected = getenv("TEST_RESULT"); + if (!in_array($expected, ["success", "failure"], true)) { + throw new RuntimeException("Invalid matrix dependency result."); + } + $results = []; + $notReady = []; + $hasNonSuccess = false; + foreach ($versions as $version) { + $name = "Run Tests (" . $version . ")"; + $matches = array_values(array_filter($jobs, static function ($job) use ($name) { + return is_string($job["name"] ?? null) + && ($job["name"] === $name || str_ends_with($job["name"], " / " . $name)); + })); + foreach ($matches as $candidate) { + if ((string) ($candidate["run_id"] ?? "") !== getenv("GITHUB_RUN_ID") + || !is_int($candidate["run_attempt"] ?? null) || $candidate["run_attempt"] < 1 + || $candidate["run_attempt"] > (int) $attempt) { + throw new RuntimeException("Invalid workflow job attempt for " . $version); + } + } + // Absence cannot distinguish an unchanged leg from an + // unobserved retry. Never use a result from an older attempt. + $current = array_values(array_filter($matches, static fn ($job) => $job["run_attempt"] === (int) $attempt)); + if ($current === []) { + $notReady[] = "Missing current-attempt workflow job for " . $version; + continue; + } + if (count($current) !== 1) { + throw new RuntimeException("Ambiguous current-attempt workflow job for " . $version); } + $job = $current[0]; + $status = $job["status"] ?? null; + $conclusion = $job["conclusion"] ?? null; + if ($conclusion === null && in_array($status, ["queued", "in_progress", "waiting", "pending", "requested", "completed"], true)) { + $notReady[] = "Incomplete current-attempt workflow job for " . $version; + continue; + } + if ($status !== "completed" || !is_string($conclusion) || preg_match("/\A[a-z_]+\z/", $conclusion) !== 1) { + throw new RuntimeException("Invalid current-attempt workflow job result for " . $version); + } + $hasNonSuccess = $hasNonSuccess || $conclusion !== "success"; + $results[] = $version . "\t" . ($conclusion === "success" ? "success" : "failure") + . "\t" . $conclusion; } - $latestAttempt = max(array_column($matches, "run_attempt")); - $latest = array_values(array_filter($matches, static fn ($job) => $job["run_attempt"] === $latestAttempt)); - if (count($latest) !== 1) { - throw new RuntimeException("Ambiguous latest workflow job for " . $version); + // Independently confirm that the complete terminal snapshot + // agrees with the matrix dependency outcome. + if ($notReady === [] && ($expected === "failure") !== $hasNonSuccess) { + $notReady[] = "Workflow jobs do not reflect the test matrix result yet."; } - $job = $latest[0]; - if (($job["status"] ?? null) !== "completed" - || !is_string($job["conclusion"] ?? null) || $job["conclusion"] === "" - || preg_match("/\A[a-z_]+\z/", $job["conclusion"]) !== 1) { - throw new RuntimeException("Incomplete latest workflow job for " . $version); + if ($notReady !== []) { + fwrite(STDERR, implode(PHP_EOL, $notReady) . PHP_EOL); + exit(75); } - $results[] = $version . "\t" . ($job["conclusion"] === "success" ? "success" : "failure") - . "\t" . $job["conclusion"]; - } - echo implode(PHP_EOL, $results), PHP_EOL; - ' | while IFS=$'\t' read -r php_version state conclusion; do + echo implode(PHP_EOL, $results), PHP_EOL; + '); then + break + else + status=$? + if [[ "$status" != 75 || "$poll" == 8 ]]; then + exit "$status" + fi + sleep 3 + fi + done + + while IFS=$'\t' read -r php_version state conclusion; do gh api \ --method POST \ "repos/${GITHUB_REPOSITORY}/statuses/${TARGET_SHA}" \ @@ -395,4 +448,4 @@ jobs: -f context="Run Tests (${php_version})" \ -f description="PHP ${php_version} matrix job result: ${conclusion}." \ -f target_url="${TARGET_URL}" - done + done <<< "$results" diff --git a/docs/advanced/branch-protection-and-bot-commits.rst b/docs/advanced/branch-protection-and-bot-commits.rst index ce2df956d..4d538cecc 100644 --- a/docs/advanced/branch-protection-and-bot-commits.rst +++ b/docs/advanced/branch-protection-and-bot-commits.rst @@ -130,15 +130,22 @@ The final publisher requires successful pending publication and a matrix that actually finished with success or failure. It does not run for skipped or cancelled matrices, so a publication failure cannot make it select earlier successful jobs. Neither publisher checks out repository files or executes -consumer code. The final publisher reads GitHub job attempts for that exact -run, selects the newest attempt for each PHP version, and requires that result -to be completed before publishing it under its required-check name, such as -``Run Tests (8.3)``, ``Run Tests (8.4)``, and ``Run Tests (8.5)``. - -When only failed jobs are rerun, successful versions can remain in an earlier -attempt. The publisher retains those completed results and replaces only the -versions that have a newer attempt. An incomplete or ambiguous newest attempt -fails publication rather than falling back to an older successful result. +consumer code. The final publisher requires one completed job for every PHP +version from the exact run and current attempt. It publishes those conclusions +under the required-check names, such as ``Run Tests (8.3)``, +``Run Tests (8.4)``, and ``Run Tests (8.5)``. + +GitHub can return an older result before the current job becomes visible. +The publisher cannot distinguish that case from a leg not repeated in a +partial rerun, so it never substitutes an earlier attempt. Use +**Re-run all jobs** or dispatch a new test run to refresh the required +statuses, not **Re-run failed jobs** or a rerun of an individual job. + +If GitHub's API briefly lags behind the runner, the publishers retry while the +current run is still queued or its current-attempt matrix jobs are not ready. +Invalid identity or ambiguous results fail immediately. The final publisher +also waits if the observed terminal results disagree with the matrix dependency +outcome. If results remain incomplete or disagree, publication fails. Full reruns execute the pending phase again before the new matrix starts. A missing, ambiguous, incomplete or wrong-run result makes final publication fail @@ -150,10 +157,12 @@ older in-progress runs for the same pull request. Pending publication is not instantaneous or atomic. Earlier statuses may remain visible while the run is scheduled or PHP versions are resolved. An API failure before the first pending POST leaves old statuses unchanged; failure between -POSTs can leave only some contexts updated. Rerunning an individual successful -test job can retain its successful pending-job ancestor instead of executing -that ancestor again. Prefer the exact native qualified GitHub Actions checks -when deliberately migrating a consumer's branch protection policy. +POSTs can leave only some contexts updated. A partial rerun can reuse the +successful pending-job ancestor instead of executing it again, so previously +published commit statuses can remain visible. They are not proof that the +latest attempt was verified; check the run and attempt before relying on them. +Prefer the exact native qualified GitHub Actions checks when deliberately +migrating a consumer's branch protection policy. Jobs that execute checked-out code have read-only contents access and no status write permission; all checkouts disable credential persistence. Only the diff --git a/docs/usage/github-actions.rst b/docs/usage/github-actions.rst index 4ec6320eb..1c7863c2c 100644 --- a/docs/usage/github-actions.rst +++ b/docs/usage/github-actions.rst @@ -161,20 +161,19 @@ above when its protection policy needs aliases. If pending publication fails, the matrix is blocked and the final publisher does not run. The final publisher requires successful pending publication and an actual success or failure matrix outcome; skipped or cancelled matrices -cannot cause it to republish older successful jobs. Final results come from -GitHub job metadata for that exact run, selecting the newest attempt for each -version and requiring it to be completed. A failed-only retry can retain results from -unaffected versions, while incomplete or ambiguous newest results stop -publication. - -Full reruns reexecute the ordered pending publisher. Rerunning only an -individual successful job may retain its successful ancestors and therefore -does not guarantee another pending publication. There is also a scheduling and -PHP-resolution gap before the pending job runs. A failed API read before its -first POST leaves existing statuses unchanged, and later API failures may leave -only some contexts updated. Commit-status mirroring does not provide an atomic -replacement of earlier results. Prefer native qualified checks when migrating -a repository's protection policy. See +cannot cause it to republish older successful jobs. Final results require a +completed job for every PHP version from the exact run and current attempt. +Missing, incomplete or ambiguous results stop publication; a result from an +earlier attempt cannot stand in for a missing job. + +To refresh required contexts, use **Re-run all jobs** or dispatch a fresh run. +A partial rerun can retain its successful pending-publisher ancestor, so +previously published statuses may remain visible without verifying that attempt. +There is also a scheduling and PHP-resolution gap before the pending job runs. +A failed API read before its first POST leaves existing statuses unchanged, +and later API failures may leave only some contexts updated. Commit-status +mirroring does not provide an atomic replacement of earlier results. Prefer +native qualified checks when migrating a repository's protection policy. See :doc:`../advanced/branch-protection-and-bot-commits` for the permission ceiling and bot-authored commit flow. diff --git a/tests/GitHubActions/PendingTestStatusWorkflowTest.php b/tests/GitHubActions/PendingTestStatusWorkflowTest.php index 99ad67dce..e83c18176 100644 --- a/tests/GitHubActions/PendingTestStatusWorkflowTest.php +++ b/tests/GitHubActions/PendingTestStatusWorkflowTest.php @@ -44,7 +44,7 @@ public static function invalidRuns(): iterable yield 'string attempt' => [['run_attempt' => '1'], 'Workflow run attempt is not an integer.']; yield 'missing attempt' => [['run_attempt' => null], 'Workflow run attempt is not an integer.']; yield 'different attempt' => [['run_attempt' => 2], 'Workflow run attempt does not match the current attempt.']; - foreach (['queued', 'completed', 'cancelled', null, "untrusted\nTOKEN_MARKER"] as $status) { + foreach (['completed', 'cancelled', null, "untrusted\nTOKEN_MARKER"] as $status) { yield 'status ' . ($status ?? 'missing') => [['status' => $status], 'Workflow run status is not in_progress.']; } } @@ -83,13 +83,45 @@ public function pendingPublisherWillKeepTheValidRunPublishingPath(): void } } + #[Test] + public function pendingPublisherWaitsForTheSameRunAndAttemptToStart(): void + { + [$code, $output] = $this->executePublisher(['status' => 'queued'], [['status' => 'in_progress']]); + + self::assertSame(0, $code, $output); + self::assertSame(2, substr_count($output, 'RUN_READ')); + self::assertSame(3, substr_count($output, 'STATUS_WRITE')); + self::assertLessThan(strpos($output, 'STATUS_WRITE'), strrpos($output, 'RUN_READ')); + } + + #[Test] + public function pendingPublisherStopsAfterEightSnapshotsWithoutWrites(): void + { + [$code, $output] = $this->executePublisher(['status' => 'queued']); + + self::assertNotSame(0, $code); + self::assertSame(8, substr_count($output, 'RUN_READ')); + self::assertStringNotContainsString('STATUS_WRITE', $output); + } + + #[Test] + public function pendingPublisherRejectsASupersedingAttemptDuringPolling(): void + { + [$code, $output] = $this->executePublisher(['status' => 'queued'], [['run_attempt' => 2]]); + + self::assertNotSame(0, $code); + self::assertSame(2, substr_count($output, 'RUN_READ')); + self::assertStringNotContainsString('STATUS_WRITE', $output); + } + /** * Execute the actual embedded program with only its GitHub transport substituted. * * @param array $overrides + * @param list> $subsequent * @return array{int, string} */ - private function executePublisher(array $overrides): array + private function executePublisher(array $overrides, array $subsequent = []): array { $workflow = Yaml::parseFile(__DIR__ . '/../../.github/workflows/tests.yml'); $shell = $workflow['jobs']['publish_pending_statuses']['steps'][0]['run']; @@ -100,17 +132,20 @@ private function executePublisher(array $overrides): array $end = strpos($program, '$repository = getenv'); self::assertIsInt($start); self::assertIsInt($end); - $run = array_replace([ + $default = [ 'id' => 7, 'repository' => ['full_name' => 'example/repo'], 'run_attempt' => 1, 'status' => 'in_progress', - ], $overrides); - $transport = 'function githubApi(array $arguments): array {' + ]; + $runs = array_map(static fn (array $snapshot): array => array_replace($default, $snapshot), [$overrides, ...$subsequent]); + $transport = 'function sleep(int $seconds): int { return 0; }' . "\n" + . 'function githubApi(array $arguments): array {' . 'if ($arguments[0] === "--method") { echo "STATUS_WRITE\\n" . var_export($arguments, true) . "\\n"; return []; }' - . 'return ' . var_export($run, true) . '; }' . "\n"; + . 'static $poll = 0; echo "RUN_READ\\n"; $runs = ' . var_export($runs, true) . ';' + . 'return $runs[min($poll++, count($runs) - 1)]; }' . "\n"; $program = substr($program, 0, $start) . $transport . substr($program, $end); - $process = proc_open(escapeshellarg(PHP_BINARY), [['pipe', 'r'], ['pipe', 'w'], ['redirect', 1]], $pipes, null, array_merge(getenv(), [ + $process = proc_open(escapeshellarg(PHP_BINARY) . ' -d disable_functions=sleep', [['pipe', 'r'], ['pipe', 'w'], ['redirect', 1]], $pipes, null, array_merge(getenv(), [ 'GITHUB_REPOSITORY' => 'example/repo', 'GITHUB_RUN_ID' => '7', 'GITHUB_RUN_ATTEMPT' => '1', diff --git a/tests/GitHubActions/RequiredTestStatusWorkflowTest.php b/tests/GitHubActions/RequiredTestStatusWorkflowTest.php new file mode 100644 index 000000000..583eaa54b --- /dev/null +++ b/tests/GitHubActions/RequiredTestStatusWorkflowTest.php @@ -0,0 +1,260 @@ + + * @license https://opensource.org/licenses/MIT MIT License + * + * @see https://github.com/php-fast-forward/ + * @see https://github.com/php-fast-forward/dev-tools + * @see https://github.com/php-fast-forward/dev-tools/issues + * @see https://php-fast-forward.github.io/dev-tools/ + * @see https://datatracker.ietf.org/doc/html/rfc2119 + */ + +namespace FastForward\DevTools\Tests\GitHubActions; + +use PHPUnit\Framework\Attributes\CoversNothing; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\Test; +use PHPUnit\Framework\TestCase; +use Symfony\Component\Filesystem\Filesystem; +use Symfony\Component\Yaml\Yaml; +use function Safe\fclose; +use function Safe\json_encode; +use function Safe\proc_open; +use function Safe\stream_get_contents; + +#[CoversNothing] +final class RequiredTestStatusWorkflowTest extends TestCase +{ + #[Test] + public function publisherWaitsForCompleteCurrentAttemptAcrossAllPages(): void + { + $success = self::job('8.3', 2); + $oldSuccess = self::job('8.5', 1); + $nullConclusion = self::job('8.4', 2, 'completed', null); + $inProgress = self::job('8.5', 2, 'in_progress', null); + $failed = self::job('8.5', 2, 'completed', 'failure'); + + [$code, $output] = $this->executePublisher([ + [['jobs' => [$success, self::job('8.4', 1), $oldSuccess]]], + [['jobs' => [$success, $oldSuccess, $inProgress]]], + [['jobs' => [$success, $oldSuccess, $nullConclusion, $inProgress]]], + [['jobs' => [$success, $oldSuccess]], ['jobs' => [self::job('8.4', 2), $failed]]], + ], 'failure'); + + self::assertSame(0, $code, $output); + self::assertSame(4, substr_count($output, 'JOBS_READ')); + self::assertStringContainsString('Missing current-attempt workflow job for 8.5', $output); + self::assertStringContainsString('Incomplete current-attempt workflow job for 8.5', $output); + self::assertSame(3, substr_count($output, 'STATUS_WRITE')); + self::assertLessThan(strpos($output, 'STATUS_WRITE'), strrpos($output, 'JOBS_READ')); + self::assertStringContainsString('state=success|Run Tests (8.3)', $output); + self::assertStringContainsString('state=success|Run Tests (8.4)', $output); + self::assertStringContainsString('state=failure|Run Tests (8.5)', $output); + } + + #[Test] + public function publisherStopsAfterEightSnapshotsWithoutPublishingAnOlderSuccess(): void + { + [$code, $output] = $this->executePublisher([ + [['jobs' => [self::job('8.3', 1), self::job('8.4', 1), self::job('8.5', 1), self::job('8.5', 2, 'queued', null)]]], + ]); + + self::assertSame(75, $code, $output); + self::assertSame(8, substr_count($output, 'JOBS_READ')); + self::assertStringContainsString('Incomplete current-attempt workflow job for 8.5', $output); + self::assertStringNotContainsString('STATUS_WRITE', $output); + } + + #[Test] + public function publisherWillNotMirrorAnEntirelyGreenCurrentAttemptWhenTheDependencyFailed(): void + { + [$code, $output] = $this->executePublisher([ + [['jobs' => [self::job('8.3', 2), self::job('8.4', 2), self::job('8.5', 2)]]], + ], 'failure'); + + self::assertSame(75, $code, $output); + self::assertSame(8, substr_count($output, 'JOBS_READ')); + self::assertStringContainsString('Workflow jobs do not reflect the test matrix result yet.', $output); + self::assertStringNotContainsString('STATUS_WRITE', $output); + } + + #[Test] + public function publisherWaitsWhenACurrentAttemptFailureContradictsASuccessfulDependency(): void + { + [$code, $output] = $this->executePublisher([ + [['jobs' => [self::job('8.3', 2), self::job('8.4', 2), self::job('8.5', 2, 'completed', 'failure')]]], + [['jobs' => [self::job('8.3', 2), self::job('8.4', 2), self::job('8.5', 2)]]], + ]); + + self::assertSame(0, $code, $output); + self::assertSame(2, substr_count($output, 'JOBS_READ')); + self::assertSame(3, substr_count($output, 'STATUS_WRITE')); + self::assertStringContainsString('Workflow jobs do not reflect the test matrix result yet.', $output); + self::assertStringContainsString('state=success|Run Tests (8.5)', $output); + self::assertStringNotContainsString('state=failure', $output); + } + + #[Test] + public function publisherOnlyRerunCannotMirrorPreviouslyCompletedMatrixJobs(): void + { + [$code, $output] = $this->executePublisher([ + [['jobs' => [self::job('8.3', 1), self::job('8.4', 1), self::job('8.5', 1)]]], + ]); + + self::assertSame(75, $code, $output); + self::assertSame(8, substr_count($output, 'JOBS_READ')); + self::assertStringContainsString('Missing current-attempt workflow job for 8.5', $output); + self::assertStringNotContainsString('STATUS_WRITE', $output); + } + + /** + * @return iterable + */ + public static function incompleteLegVisibility(): iterable + { + yield 'missing from every snapshot' => [false]; + yield 'visible incomplete and later disappears' => [true]; + } + + #[Test] + #[DataProvider('incompleteLegVisibility')] + public function publisherWillNotSubstituteAnOlderSuccessEvenWhenAnotherFailureMatchesTheAggregate( + bool $initiallyVisible + ): void { + $stale = [self::job('8.3', 2), self::job('8.4', 2, 'completed', 'failure'), self::job('8.5', 1)]; + $snapshots = []; + if ($initiallyVisible) { + $snapshots[] = [['jobs' => [...$stale, self::job('8.5', 2, 'in_progress', null)]]]; + } + $snapshots[] = [['jobs' => $stale]]; + + [$code, $output] = $this->executePublisher($snapshots, 'failure'); + + self::assertSame(75, $code, $output); + self::assertSame(8, substr_count($output, 'JOBS_READ')); + self::assertStringContainsString('Missing current-attempt workflow job for 8.5', $output); + self::assertStringNotContainsString('STATUS_WRITE', $output); + } + + /** + * @return iterable, string}> + */ + public static function invalidSnapshots(): iterable + { + $job = self::job('8.5', 2); + yield 'ambiguous' => [[['jobs' => [$job, $job]]], 'Ambiguous current-attempt workflow job for 8.5']; + yield 'wrong run' => [[['jobs' => [array_replace($job, ['run_id' => 99])]]], 'Invalid workflow job attempt for 8.5']; + yield 'superseding attempt' => [[['jobs' => [self::job('8.5', 3)]]], 'Invalid workflow job attempt for 8.5']; + yield 'malformed response' => [[['jobs' => false]], 'Malformed workflow jobs response.']; + yield 'invalid result' => [[['jobs' => [array_replace($job, ['conclusion' => false])]]], 'Invalid current-attempt workflow job result for 8.5']; + } + + /** + * @param array $snapshot + */ + #[Test] + #[DataProvider('invalidSnapshots')] + public function publisherRejectsInvalidEvidenceWithoutWaitingOrWriting(array $snapshot, string $error): void + { + [$code, $output] = $this->executePublisher([$snapshot]); + + self::assertNotSame(0, $code); + self::assertSame(1, substr_count($output, 'JOBS_READ')); + self::assertStringContainsString($error, $output); + self::assertStringNotContainsString('STATUS_WRITE', $output); + } + + /** + * @return array{name: string, run_id: int, run_attempt: int, status: string, conclusion: null|string} + */ + private static function job(string $version, int $attempt, string $status = 'completed', ?string $conclusion = 'success'): array + { + return [ + 'name' => "tests / Run Tests ($version)", + 'run_id' => 7, + 'run_attempt' => $attempt, + 'status' => $status, + 'conclusion' => $conclusion, + ]; + } + + /** + * Execute the exact GitHub Actions shell step with deterministic API snapshots. + * + * @param list> $snapshots + * @return array{int, string} + */ + private function executePublisher(array $snapshots, string $testResult = 'success'): array + { + $workflow = Yaml::parseFile(__DIR__ . '/../../.github/workflows/tests.yml'); + $shell = $workflow['jobs']['publish_required_statuses']['steps'][0]['run']; + self::assertIsString($shell); + $filesystem = new Filesystem(); + $directory = $filesystem->tempnam(sys_get_temp_dir(), 'status-workflow-'); + $filesystem->remove($directory); + $filesystem->mkdir($directory); + + try { + foreach ($snapshots as $index => $snapshot) { + $filesystem->dumpFile($directory . '/jobs-' . $index, json_encode($snapshot)); + } + $filesystem->dumpFile($directory . '/counter', '0'); + $filesystem->dumpFile($directory . '/publish', $shell); + $filesystem->dumpFile($directory . '/sleep', "#!/bin/bash\nexit 0\n"); + $filesystem->symlink(PHP_BINARY, $directory . '/php'); + $filesystem->dumpFile($directory . '/gh', <<<'BASH' + #!/bin/bash + set -eu + [[ "$1" == api ]] + if [[ "$2" == --paginate && "$3" == --slurp && "$4" == 'repos/example/repo/actions/runs/7/jobs?filter=all&per_page=100' ]]; then + echo JOBS_READ >&2 + counter=$(<"$RUNNER_TEMP/counter") + printf '%s' "$((counter + 1))" > "$RUNNER_TEMP/counter" + if ((counter >= FIXTURE_COUNT)); then + counter=$((FIXTURE_COUNT - 1)) + fi + cat "$RUNNER_TEMP/jobs-$counter" + elif [[ "$2" == --method && "$3" == POST && "$4" == "repos/example/repo/statuses/$TARGET_SHA" ]]; then + printf 'STATUS_WRITE %s|%s\n' "$6" "${8#context=}" + else + exit 1 + fi + BASH); + $filesystem->chmod([$directory . '/gh', $directory . '/sleep'], 0755); + $process = proc_open( + 'bash --noprofile --norc -eo pipefail ' . escapeshellarg($directory . '/publish'), + [['pipe', 'r'], ['pipe', 'w'], ['redirect', 1]], + $pipes, + null, + array_merge(getenv(), [ + 'PATH' => $directory . ':' . getenv('PATH'), + 'RUNNER_TEMP' => $directory, + 'FIXTURE_COUNT' => (string) count($snapshots), + 'GITHUB_REPOSITORY' => 'example/repo', + 'GITHUB_RUN_ID' => '7', + 'GITHUB_RUN_ATTEMPT' => '2', + 'TARGET_SHA' => str_repeat('a', 40), + 'TARGET_URL' => 'https://github.com/example/repo/actions/runs/7', + 'TEST_RESULT' => $testResult, + 'TEST_MATRIX' => '{"php-version":["8.3","8.4","8.5"]}', + ]), + ); + self::assertIsResource($process); + fclose($pipes[0]); + $output = stream_get_contents($pipes[1]); + fclose($pipes[1]); + + return [proc_close($process), $output]; + } finally { + $filesystem->remove($directory); + } + } +}