diff --git a/.github/actions/publish-required-gate-status/publish-required-gate-status.sh b/.github/actions/publish-required-gate-status/publish-required-gate-status.sh index 7b58c260d0..ae09f293a3 100644 --- a/.github/actions/publish-required-gate-status/publish-required-gate-status.sh +++ b/.github/actions/publish-required-gate-status/publish-required-gate-status.sh @@ -74,7 +74,7 @@ latest_status() { # This proves ownership, not original source success. Old base SHA and failed or # cancelled publisher steps identify provenance only and cannot grant proof. native_identity() { - local run_id="$1" attempt="$2" current="$3" run title title_base jobs check check_id + local run_id="$1" attempt="$2" current="$3" require_current_base="${4:-false}" run title title_base jobs check check_id if [[ "${current}" == true ]]; then run="$(gh api --method GET "${api_root}/actions/runs/${run_id}")" || return 1 else @@ -84,7 +84,7 @@ native_identity() { title_base="$(jq -ern --arg title "${title}" --arg name "${workflow_name}" --arg pr "${PR_NUMBER}" --arg head "${HEAD_SHA}" ' $title | capture("^(?.*) pr-(?[1-9][0-9]*) base-(?[0-9A-Fa-f]{40}) head-(?[0-9A-Fa-f]{40})$") | select(.name == $name and .pr == $pr and .head == $head) | .base')" || return 1 - [[ "${current}" != true || "${title_base}" == "${BASE_SHA}" ]] || return 1 + [[ "${current}" != true && "${require_current_base}" != true || "${title_base}" == "${BASE_SHA}" ]] || return 1 jq -e --argjson id "${run_id}" --argjson attempt "${attempt}" --argjson workflow "${workflow_id}" \ --arg repo "${GITHUB_REPOSITORY}" --arg head_repo "${head_repository}" --arg branch "${head_branch}" \ --arg head "${HEAD_SHA}" --arg title "${title}" --arg name "${workflow_name}" --arg path "${EXPECTED_WORKFLOW_PATH}" \ @@ -128,16 +128,29 @@ native_identity() { .head_sha == $head and .status == $job.status and .conclusion == $job.conclusion' <<<"${check}" >/dev/null } owned_status() { - local suffix run_id attempt + local status="$1" require_current_base="${2:-false}" suffix run_id attempt jq -e --arg url "${api_url}/statuses/${HEAD_SHA}" ' .creator.id == 41898282 and .creator.login == "github-actions[bot]" and .creator.type == "Bot" and - .url == $url and (.state == "pending" or .state == "success" or .state == "failure" or .state == "error")' <<<"$1" >/dev/null || return 1 - suffix="$(jq -er '.target_url' <<<"$1")" || return 1 + .url == $url and (.state == "pending" or .state == "success" or .state == "failure" or .state == "error")' <<<"${status}" >/dev/null || return 1 + suffix="$(jq -er '.target_url' <<<"${status}")" || return 1 [[ "${suffix}" == "${run_url}"* ]] || return 1 suffix="${suffix#"${run_url}"}" [[ "${suffix}" =~ ^([1-9][0-9]*)/attempts/([1-9][0-9]*)$ ]] || return 1 run_id="${BASH_REMATCH[1]}"; attempt="${BASH_REMATCH[2]}" - native_identity "${run_id}" "${attempt}" false + native_identity "${run_id}" "${attempt}" false "${require_current_base}" +} +acknowledge_existing_pending() { + local status="$1" fresh + [[ "$(jq -r '.state' <<<"${status}")" == pending ]] || return 1 + owned_status "${status}" true || return 1 + native_identity "${GITHUB_RUN_ID}" "${GITHUB_RUN_ATTEMPT}" true || + fail_closed "Current metadata native gate is not attributable." + pr="$(current_pr)" + pr_matches "${pr}" || unchanged + fresh="$(latest_status)" || fail_closed "Latest context became unavailable." + [[ "${fresh}" == "${status}" ]] || unchanged + report pending-acknowledged + exit 0 } pr="$(current_pr)" pr_matches "${pr}" || unchanged @@ -159,7 +172,10 @@ jq -e --arg title "${current_title}" --argjson id "${GITHUB_RUN_ID}" --argjson a current_run_number="$(jq -er '.run_number' <<<"${run}")" latest="$(latest_status)" || fail_closed "Latest context is incomplete or ambiguous." owned=false -if [[ "${latest}" != null ]] && owned_status "${latest}"; then owned=true; fi +if [[ "${latest}" != null ]]; then + if [[ "${ASSESSMENT}" == dependency-deferred ]] && acknowledge_existing_pending "${latest}"; then :; fi + if owned_status "${latest}"; then owned=true; fi +fi if [[ "${ASSESSMENT}" == success ]]; then if [[ "${owned}" != true || "$(jq -r '.state' <<<"${latest}")" == success ]]; then unchanged; fi assessment_output="$(mktemp)" @@ -177,7 +193,10 @@ native_identity "${GITHUB_RUN_ID}" "${GITHUB_RUN_ATTEMPT}" true || fail_closed " pr="$(current_pr)" pr_matches "${pr}" || unchanged fresh="$(latest_status)" || fail_closed "Latest context became unavailable." -[[ "${fresh}" == "${latest}" ]] || unchanged +if [[ "${fresh}" != "${latest}" ]]; then + if [[ "${ASSESSMENT}" == dependency-deferred ]] && acknowledge_existing_pending "${fresh}"; then :; fi + unchanged +fi # One POST, no retry. Its native REST shape has creator and URL, not sha/app_id. ack="$(gh api --method POST "${api_root}/statuses/${HEAD_SHA}" -f state="${state}" -f context="${gate_name}" \ -f target_url="${current_target}" -f description="Metadata gate original proof: ${state}")" || diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index 42df966e2c..1565b766b2 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -42,7 +42,7 @@ All five metadata gate producers call the shared publisher after canonical prese The existing substantive and metadata completion callbacks reconcile both completion orders, including a pending status published after original proof has already completed. The existing trusted resolve job holds `statuses: write` for supplementary reconciliation; producer gate jobs hold it only for the shared metadata publisher. The assessor retains its unchanged selection contract. A fresh attributable current-tuple completion may reconcile a recognized owned pending, failure or error barrier using independently selected current substantive proof. This explicitly supersedes the pending-only terminal-write restriction for source recovery: a same-head retarget/base advancement or legitimate source retry must recover without a new metadata edit. Already successful and foreign barriers remain untouched. Historical base-A success cannot authorize current base-B success, and obsolete base-A callbacks remain no-ops. The resolver re-reads current PR identity, both historical ownership and selected current native proof, and the unchanged latest status immediately before posting. Its replacement fence is the selected latest status identity; it does not require an original run number to exceed a later metadata run, since original completion after metadata publication is ordinary. Replaced, stale or unbound statuses are never overwritten. GitHub provides no conditional Commit Status write: the final read and POST are not atomic, and this boundary is practical race suppression rather than an atomic replacement guarantee. A rejected or ambiguous POST is never retried within that callback; subsequent callbacks assess fresh evidence. No polling, global expiry, new credentials, or independent proof ledger is introduced. -The [publisher action](../../.github/actions/publish-required-gate-status/action.yml) runs in the dedicated metadata-only step after both successful and dependency-deferred assessments, so a successful assessment can also recover an existing owned barrier. It accepts `assessment`, `gate-name`, `workflow-name`, `workflow-file`, and `workflow-path`, and outputs `pending-acknowledged`, `success-acknowledged`, or `unchanged`. A dependency-deferred assessment publishes the current run's pending barrier only when the latest same-context status is absent or independently recognized as owned. A success assessment leaves absent, foreign, and already successful barriers unchanged. An owned pending/failure/error barrier requires a refreshed canonical assessment for the current base before publishing success; refreshed pending follows the pending policy, and failed or ambiguous assessment prevents publication. A dependency-deferred assessment permits the native metadata gate to succeed only with `pending-acknowledged`; `unchanged`, missing, unknown, or contradictory publication outputs fail distinctly as dependency deferral. A successful assessment permits `unchanged`, `success-acknowledged`, or `pending-acknowledged`: the last means refreshed proof became pending and the acknowledged status continues withholding readiness. A successful assessment with an absent or already successful barrier needs no write; a foreign barrier remains untouched and independently blocking when non-successful. Missing or unknown assessment/publication outputs fail closed. The metadata-result guard uses `!cancelled()` with the unchanged metadata predicate so it still executes after publisher failure, and requires the publisher outcome itself to be `success` before accepting any assessment/publication pair. Publisher failure, denial, malformed acknowledgment, cancellation, or missing/skipped execution never grants native gate success. The publisher retains normal success-dependent execution without `continue-on-error`; no caller ignores its errors or changes substantive enforcement. +The [publisher action](../../.github/actions/publish-required-gate-status/action.yml) runs in the dedicated metadata-only step after both successful and dependency-deferred assessments, so a successful assessment can also recover an existing owned barrier. It accepts `assessment`, `gate-name`, `workflow-name`, `workflow-file`, and `workflow-path`, and outputs `pending-acknowledged`, `success-acknowledged`, or `unchanged`. A dependency-deferred assessment publishes the current run's pending barrier only when the latest same-context status is absent or independently recognized as owned. If an owned pending barrier already binds the exact current PR, base, head, workflow, run, and attempt, including one that becomes latest during the publisher's replacement fence, the publisher reports `pending-acknowledged` without duplicating the status only after validating the current metadata native gate and re-reading both the unchanged current PR tuple and unchanged latest status identity; a stale-base, moved, foreign, malformed, missing, failed, or successful status cannot use that durable acknowledgment path. A success assessment leaves absent, foreign, and already successful barriers unchanged. An owned pending/failure/error barrier requires a refreshed canonical assessment for the current base before publishing success; refreshed pending follows the pending policy, and failed or ambiguous assessment prevents publication. A dependency-deferred assessment permits the native metadata gate to succeed only with `pending-acknowledged`; `unchanged`, missing, unknown, or contradictory publication outputs fail distinctly as dependency deferral. A successful assessment permits `unchanged`, `success-acknowledged`, or `pending-acknowledged`: the last means refreshed proof became pending and the acknowledged status continues withholding readiness. A successful assessment with an absent or already successful barrier needs no write; a foreign barrier remains untouched and independently blocking when non-successful. Missing or unknown assessment/publication outputs fail closed. The metadata-result guard uses `!cancelled()` with the unchanged metadata predicate so it still executes after publisher failure, and requires the publisher outcome itself to be `success` before accepting any assessment/publication pair. Publisher failure, denial, malformed acknowledgment, cancellation, or missing/skipped execution never grants native gate success. The publisher retains normal success-dependent execution without `continue-on-error`; no caller ignores its errors or changes substantive enforcement. Ownership recognition allows an older base in the canonical title as provenance, and accepts a bound dedicated publisher step in progress or completed successfully, unsuccessfully, or cancelled. It binds the exact run/attempt, workflow, repository, head, PR title, gate job and native Actions app without requiring old preservation success. This permits replacing an owned barrier left by overlapping or cancelled metadata runs. Positive native workflow `run_number` and `run_attempt` counters order replacement within the same exact workflow: an older run number is replaceable; equal run numbers require the same run ID and no newer attempt. Historical attempt-specific run/job evidence binds older attempts. Missing or conflicting counters and newer barriers are not overwritten; timestamps and global run IDs do not establish ordering. Skipped, missing, conflicting or unbound publisher evidence is not ownership and grants no overwrite permission. Old-base provenance never becomes current-base proof. The current publishing run must be attributable to its exact metadata-only event and current PR tuple. Both publisher and resolver read rich status records from `/repos///statuses/`; the combined `/commits//status` projection omits `creator` and cannot establish ownership. The [GitHub status-list contract](https://docs.github.com/en/rest/commits/statuses#list-commit-statuses-for-a-reference) returns newest first. Readers stop at the first exact-context record regardless of actor, using that API order even when creation timestamps share a second; they never search older records for an owned predecessor or infer chronology from numeric IDs. Explicit 100-record pages have a ten-page safety budget. Only a short page without a matching context establishes absence; budget exhaustion, unavailable/malformed required pages, duplicate IDs in the traversed prefix, or mismatched head-bound status URLs fail closed. Older records after the selected context are not admission evidence. Null, missing, or foreign creators remain untouched rather than inferred from a URL. Native job reads retain their complete one-page cap of 100 records. Immediately before a single non-retried POST, the publisher re-reads the current PR and unchanged latest context. A successful command must return exactly one valid acknowledgment with a positive status ID, exact `https://api.github.com/repos///statuses/` URL, requested state/context/target URL, bot creator and native timestamps. REST statuses have no per-status SHA or App ID. Missing, malformed, denied or ambiguous acknowledgment never yields a pending native-success allowance. Pending POST acknowledgment has native evidence; repaired recovery and read-only fork-token qualification remain outstanding in [Platform Operations and Delivery](../project-management/implementation-tracking/platform-operations-and-delivery.md#required-ci-gate-preservation). A fork token denied status-write authority leaves the publisher and native gate failed. For a non-cancelled metadata run whose canonical preservation assessment succeeded, the executed failed deferral guard retains eligibility for existing trusted legacy recovery after independent original success. Cancellation remains fail-closed. Callers never escalate fork credentials or substitute a status for original proof. diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 43ede57d03..03210a4afb 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -2705,7 +2705,7 @@ elif endpoint.endswith("/pulls/123"): state["pr_reads"] = state.get("pr_reads", 0) + 1 result = {"number": 123, "state": "open", "base": {"sha": base, "ref": "develop", "repo": {"full_name": repo}}, "head": {"sha": head, "ref": "proof-branch", "repo": {"full_name": head_repo}}} - if scenario == "tuple-replaced" and state["pr_reads"] > 1: + if scenario in {"tuple-replaced", "durable-tuple-replaced"} and state["pr_reads"] > 1: result["base"]["sha"] = old_base elif endpoint.endswith(f"/commits/{head}/status") or endpoint.endswith(f"/statuses/{head}"): state["status_reads"] = state.get("status_reads", 0) + 1 @@ -2722,8 +2722,16 @@ elif endpoint.endswith(f"/commits/{head}/status") or endpoint.endswith(f"/status barrier["creator"] = {"id": 99, "login": "foreign", "type": "User"} if scenario == "status-replaced" and state["status_reads"] > 1: barrier["id"] = 999 + if scenario == "durable-status-replaced" and state["status_reads"] > 1: + barrier["id"] = 999 + if scenario in {"deferred-owned-current-pending", "status-arrived-current-pending", "status-arrived-current-foreign", "durable-current-wrong-app", "durable-current-missing-publisher", "durable-tuple-replaced", "durable-status-replaced"}: + barrier["target_url"] = f"{run_url}200/attempts/1" + if scenario == "status-arrived-current-foreign": + barrier["creator"] = {"id": 99, "login": "foreign", "type": "User"} absent = scenario in {"deferred-absent", "deferred-fork", "success-absent"} or scenario.startswith("ack-") or scenario.startswith("current-") rich = [] if absent else [barrier] + if scenario in {"status-arrived-current-pending", "status-arrived-stale-pending", "status-arrived-current-foreign"} and state["status_reads"] == 1: + rich = [] combined = {"sha": head, "total_count": len(rich), "statuses": [{key: value for key, value in row.items() if key != "creator"} for row in rich]} assert all("creator" not in row for row in combined["statuses"]) if endpoint.endswith("/status"): @@ -2749,7 +2757,7 @@ elif "/actions/runs/" in endpoint and not endpoint.endswith("/jobs"): old = historical attempt = int(endpoint.rsplit("/", 1)[1]) if historical else current_attempt running = not old or scenario == "deferred-owned-running" - run_base = old_base if run_id == 200 else base + run_base = base if scenario in {"deferred-owned-current-pending", "status-arrived-current-pending", "status-arrived-current-foreign", "durable-current-wrong-app", "durable-current-missing-publisher", "durable-tuple-replaced", "durable-status-replaced"} else old_base if run_id == 200 else base result = {"id": run_id, "run_attempt": attempt, "run_number": 2 if run_id == 200 else 3, "workflow_id": 42, "event": "pull_request", "repository": {"full_name": repo}, "head_repository": {"full_name": head_repo}, "head_sha": head, "head_branch": "proof-branch", "name": "CI — Validation", @@ -2778,6 +2786,8 @@ elif endpoint.endswith("/jobs"): steps = [{"name": "Preserve successful required gate on metadata-only edit", "status": "completed", "conclusion": "success"}, publisher] if old and running: steps = [publisher] + if not old and scenario == "durable-current-missing-publisher": + steps = steps[:1] job = {"id": native_id, "run_id": run_id, "name": "Validation Gate", "head_sha": head, "status": "in_progress" if running else "completed", "conclusion": None if running else "cancelled" if scenario == "deferred-owned-cancelled" else "failure" if scenario == "deferred-owned-step-failed" else "success", @@ -2792,7 +2802,7 @@ elif "/check-runs/" in endpoint: result = {"id": check_id, "name": "Validation Gate", "head_sha": head, "status": "in_progress" if running else "completed", "conclusion": None if running else "cancelled" if scenario == "deferred-owned-cancelled" else "failure" if scenario == "deferred-owned-step-failed" else "success", - "app": {"id": 99 if scenario == "deferred-old-wrong-app" or (not old and scenario == "current-wrong-app") else 15368, "slug": "github-actions"}} + "app": {"id": 99 if scenario == "deferred-old-wrong-app" or (not old and scenario in {"current-wrong-app", "durable-current-wrong-app"}) else 15368, "slug": "github-actions"}} else: raise AssertionError(endpoint) state_path.write_text(json.dumps(state)) @@ -2824,7 +2834,7 @@ run_producer() { EXPECTED_WORKFLOW_FILE=ci.yml EXPECTED_WORKFLOW_PATH=.github/workflows/ci.yml \ bash "$PUBLISH_SCRIPT" >"$tmp_dir/producer-log-$scenario" 2>&1 } -for scenario in deferred-absent deferred-fork deferred-owned-pending deferred-owned-earlier-attempt deferred-owned-newer deferred-old-equal-number deferred-old-missing-number deferred-owned-failure deferred-owned-error deferred-owned-success deferred-owned-running deferred-owned-cancelled deferred-owned-step-failed success-owned-pending success-owned-failure success-owned-error success-assessment-pending status-replaced tuple-replaced deferred-foreign deferred-old-wrong-app deferred-old-wrong-title deferred-old-skipped success-absent success-owned-success success-foreign; do +for scenario in deferred-absent deferred-fork deferred-owned-pending deferred-owned-current-pending deferred-owned-earlier-attempt deferred-owned-newer deferred-old-equal-number deferred-old-missing-number deferred-owned-failure deferred-owned-error deferred-owned-success deferred-owned-running deferred-owned-cancelled deferred-owned-step-failed success-owned-pending success-owned-failure success-owned-error success-assessment-pending status-replaced status-arrived-current-pending status-arrived-stale-pending status-arrived-current-foreign tuple-replaced durable-tuple-replaced durable-status-replaced deferred-foreign deferred-old-wrong-app deferred-old-wrong-title deferred-old-skipped success-absent success-owned-success success-foreign; do assessment=dependency-deferred [[ "$scenario" != success-* ]] || assessment=success original=no-local-workflow-file @@ -2838,11 +2848,12 @@ from pathlib import Path import sys state = json.loads(Path(sys.argv[1]).read_text()) scenario = sys.argv[3] -unchanged = scenario in {"status-replaced", "tuple-replaced", "deferred-owned-newer", "deferred-old-equal-number", "deferred-old-missing-number", "deferred-foreign", "deferred-old-wrong-app", "deferred-old-wrong-title", "deferred-old-skipped", "success-absent", "success-owned-success", "success-foreign"} +unchanged = scenario in {"status-replaced", "status-arrived-stale-pending", "status-arrived-current-foreign", "tuple-replaced", "durable-tuple-replaced", "durable-status-replaced", "deferred-owned-newer", "deferred-old-equal-number", "deferred-old-missing-number", "deferred-foreign", "deferred-old-wrong-app", "deferred-old-wrong-title", "deferred-old-skipped", "success-absent", "success-owned-success", "success-foreign"} expected = "unchanged" if unchanged else "success-acknowledged" if scenario in {"success-owned-pending", "success-owned-failure", "success-owned-error"} else "pending-acknowledged" assert Path(sys.argv[2]).read_text().strip() == f"publication={expected}", (scenario, state) -assert len(state.get("posts", [])) == (0 if unchanged else 1), state -if not unchanged: +already_durable = scenario in {"deferred-owned-current-pending", "deferred-owned-earlier-attempt", "status-arrived-current-pending"} +assert len(state.get("posts", [])) == (0 if unchanged or already_durable else 1), state +if not unchanged and not already_durable: assert state["posts"][0]["target_url"] == f"https://github.com/example/firemud/actions/runs/300/attempts/{2 if scenario == 'deferred-owned-earlier-attempt' else 1}", state assert state["posts"][0]["state"] == expected.split("-")[0], state PY_PUBLISH @@ -2878,7 +2889,7 @@ if case == "budget": assert state["status_pages"] == list(range(1, 11)), state PY_HISTORY done -for scenario in success-assessment-failed incomplete-status current-wrong-app current-wrong-tuple current-incomplete-jobs ack-denied ack-ambiguous ack-wrong-url ack-missing-creator ack-missing-id ack-bad-timestamp ack-wrong-state ack-multiple; do +for scenario in success-assessment-failed incomplete-status current-wrong-app current-wrong-tuple current-incomplete-jobs durable-current-wrong-app durable-current-missing-publisher ack-denied ack-ambiguous ack-wrong-url ack-missing-creator ack-missing-id ack-bad-timestamp ack-wrong-state ack-multiple; do assessment=dependency-deferred original=no-local-workflow-file if [[ "$scenario" == success-assessment-failed ]]; then assessment=success; original=failed-predecessor; fi