Skip to content

ci: add Firebase App Hosting rollout safety net - #155

Merged
TytaniumDev merged 1 commit into
mainfrom
fix/rollout-safety-net
Apr 10, 2026
Merged

TytaniumDev merged 1 commit into
mainfrom
fix/rollout-safety-net

Conversation

@TytaniumDev

Copy link
Copy Markdown
Owner

Summary

Adds `.github/workflows/rollout-safety-net.yml`. On every push to `main`, it verifies that Firebase App Hosting actually created a rollout for the new build — and if it didn't, creates one manually and files an issue so we notice. Uses keyless auth (Workload Identity Federation) with a dedicated service account; no long-lived keys stored anywhere.

Why

On 2026-04-10 two merges to `main` produced successful Cloud Builds + healthy Cloud Run revisions, but Firebase App Hosting silently did not create a rollout resource to shift traffic. Both times the fix was `POST /v1/.../backends/api/rollouts` via the REST API. Without that, traffic sat on an old revision indefinitely — tonight I caught it in ~15 minutes by watching logs, but an unattended deploy could sit stuck for hours.

A read-only forensics pass (separate subagent investigation, findings summarized in the commit) ruled out every config-side explanation:

  • `rolloutPolicy` is vanilla `{ codebaseBranch: main }` — no `disabled`, no `cooldownDuration`, no rate limit
  • The two affected builds are field-for-field identical to the seven healthy ones that auto-rolled out today
  • Healthy auto-rollouts are created within ~60 ms of build `createTime`, not queued / deferred, so "cooldown after rapid deploys" doesn't fit
  • No hanging long-running operations, no quota-denied log entries
  • Related upstream report: TytaniumDev/MagicBracketSimulator#( Failed App Hosting rollout prints "Deploy complete!" firebase/firebase-tools#8866 ) and a past Firebase status incident

It's almost certainly a transient Firebase App Hosting control-plane glitch, which means we can't fix the root cause on our side — we can only detect and recover. This workflow does exactly that.

What the workflow does

On `push: branches: [main]`:

  1. Authenticates to GCP via WIF (keyless, no secrets)
  2. Polls `GET .../backends/api/builds` for up to 10 min looking for a `READY` build whose `source.codebase.hash` matches `github.sha`
  3. Once the build is found, polls `GET .../backends/api/rollouts` for up to 5 min looking for a rollout that references that build
  4. If no rollout appears, `POST .../backends/api/rollouts?rolloutId=rollout-safety-net--` with the build reference
  5. Verifies the rollout resource exists via a follow-up GET
  6. Files a GitHub issue titled `Rollout safety net fired for ` with the details

Happy path (auto-rollout fires normally): the workflow finds the rollout within the first few seconds of step 3 and exits silently with zero side effects. Only fires on the pathological case.

Auth / infrastructure

  • Service account: `rollout-safety-net@magic-bracket-simulator.iam.gserviceaccount.com` (dedicated, least-privilege)
  • Role: `roles/firebaseapphosting.admin` (needed for builds.list + rollouts.list + rollouts.create)
  • WIF binding: `roles/iam.workloadIdentityUser` for `principalSet://iam.googleapis.com/projects/14286370379/locations/global/workloadIdentityPools/github/attribute.repository/TytaniumDev/MagicBracketSimulator`
  • No long-lived keys. I briefly created a JSON key during setup while I wasn't aware of the existing WIF provider, then immediately revoked it and removed the temporary GitHub secret. All current auth is keyless.

The workflow piggy-backs on the same WIF provider (`projects/14286370379/locations/global/workloadIdentityPools/github/providers/magic-bracket-repo`) that the existing `deploy.yml` uses — no new WIF infrastructure.

Security

Only trusted inputs are consumed: `github.sha`, `github.repository`, `github.server_url`. All are passed to shell via `env:` rather than direct `${{ }}` interpolation inside `run:` blocks, per GitHub's workflow injection guidance. Verified clean by `rhysd/actionlint:latest`.

Cost

$0. A handful of curl calls per push, WIF is free, no running containers.

Test plan

  • `actionlint` passes with zero warnings
  • Service account exists, has `firebaseapphosting.admin`, and WIF binding is verified via `gcloud iam service-accounts get-iam-policy`
  • jq queries verified live against commit `f6467654a5` (the PR fix(api): externalize @google-cloud/tasks to fix runtime MODULE_NOT_FOUND #154 merge that was silently skipped earlier tonight) — the workflow correctly identifies `build-2026-04-10-011` and the manual rollout I had to create
  • CI lint / workflow-lint pass on this PR
  • First real test: this PR's own merge will trigger the workflow. Expected outcome: healthy path, rollout exists within ~60 ms of build creation, workflow exits silently.
  • Simulated pathological path: if the Firebase glitch recurs in the future, the workflow should catch it. Hard to test proactively without Firebase SRE cooperation.

Rollback

If something goes wrong, delete `.github/workflows/rollout-safety-net.yml` and the workflow stops running. The service account can be cleaned up via `gcloud iam service-accounts delete rollout-safety-net@magic-bracket-simulator.iam.gserviceaccount.com` if desired, but there's no cost to leaving it.

🤖 Generated with Claude Code

On 2026-04-10 two merges to main silently did not receive an
auto-rollout: the Cloud Build succeeded, the Cloud Run revision
came up healthy, but Firebase App Hosting never created a rollout
resource to shift traffic. The workaround was to POST a manual
rollout via the REST API. Without that, traffic sat on an old
revision indefinitely.

The rolloutPolicy on the `api` backend is vanilla
(`{codebaseBranch: main}`) and both affected builds are
field-for-field identical to the seven builds that auto-rolled out
successfully, so the root cause is almost certainly a transient
control-plane bug in Firebase App Hosting itself. Related:
firebase/firebase-tools#8866.

This workflow catches the silent skip automatically:

1. Waits up to 10 min for a READY build matching the pushed commit
   SHA to appear in the App Hosting backend.
2. Polls the rollouts endpoint for up to 5 more minutes.
3. If no rollout references that build, POSTs one manually with
   rolloutId = `rollout-safety-net-<date>-<shortsha>`.
4. Files a GitHub issue so we know the safety net fired.

Auth is keyless via the existing Workload Identity Federation
provider (`projects/.../workloadIdentityPools/github/providers/magic-bracket-repo`).
A dedicated `rollout-safety-net@` service account with
`roles/firebaseapphosting.admin` has been created and bound to the
repo's principalSet — no long-lived keys stored anywhere. The
workflow is a few curl/jq calls and costs $0.

Only trusted inputs (`github.sha`, `github.repository`,
`github.server_url`) are consumed, and all of them are passed to
shell via `env:` to avoid any `${{ }}` interpolation inside `run:`
blocks. Verified by running actionlint locally.

jq queries verified live against commit f646765 (the PR #154 merge
that triggered the second silent skip) — the workflow would have
found build-2026-04-10-011 and the manual rollout I created.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@gemini-code-assist

Copy link
Copy Markdown

Note

Gemini is unable to generate a summary for this pull request due to the file types involved not being currently supported.

@TytaniumDev

Copy link
Copy Markdown
Owner Author

@claude do a code review

@claude

claude Bot commented Apr 10, 2026 •

Copy link
Copy Markdown

Claude finished @TytaniumDev's task in 2m 5s —— View job


Code Review

Overall this is solid work — the security posture is excellent and the happy-path logic is correct. A few medium and minor issues to consider.


Security ✅

  • Injection prevention: All ${{ }} context values (github.sha, github.repository, github.server_url) are passed through env: and consumed as shell variables inside run:. No direct interpolation inside shell code. This is exactly right.
  • Permissions: Minimal — contents: read, id-token: write (WIF), issues: write. Nothing else.
  • No long-lived keys: WIF is the right call.
  • ROLLOUT_ID in URL: Safe — date output and a 7-char hex SHA are the only user-controlled components; no injection surface.

Medium Issues

1. curl doesn't fail on HTTP errors — the || fallback is dead code for 4xx/5xx

.github/workflows/rollout-safety-net.yml:76-78

get() {
  curl -sS -H "Authorization: Bearer $(gcloud auth print-access-token)" "$@"
}

Without -f / --fail-with-body, curl exits 0 even on HTTP 403, 429, or 500. The || BUILD_JSON='{}' fallbacks on lines 86 and 117 only fire on network-level failures. So if Firebase returns a transient 500 HTML error page, jq receives it, emits a parse error, and with set -euo pipefail active the entire script dies mid-loop rather than retrying. Meanwhile a silent 403 (e.g., wrong service account scope) would be swallowed — the build would never be found, and the workflow exits with the "no build after 10 minutes" warning rather than surfacing the auth failure.

Recommend either:

get() {
  curl -sSf -H "Authorization: Bearer $(gcloud auth print-access-token)" "$@"
}

...and then the || BUILD_JSON='{}' fallbacks will correctly catch HTTP errors too. Or use --fail-with-body if you want to preserve the response body in error messages. The jq parse-failure-on-HTML issue would then also be moot.

Fix this →


2. POST response is never checked for errors

.github/workflows/rollout-safety-net.yml:139-143

CREATE_RESULT=$(get -X POST \
  -H "Content-Type: application/json" \
  -d "$CREATE_BODY" \
  "$API/rollouts?rolloutId=$ROLLOUT_ID")
echo "$CREATE_RESULT"

If the POST returns 409 Conflict (e.g., Firebase fired an auto-rollout in the gap between step 2 ending and step 3 running) or 400 Bad Request, the workflow continues silently to the verification step. The verify then fails because $ROLLOUT_ID was never created, producing a misleading ::error:: message. With --fail-with-body on the get helper this becomes a clean failure. Without it, you'd at minimum want to check $CREATE_RESULT for an error field before sleeping for verification.


Minor Issues

3. Fixed sleep 5 for rollout verification is fragile for async operations

.github/workflows/rollout-safety-net.yml:147

sleep 5
VERIFY=$(get "$API/rollouts/$ROLLOUT_ID") || VERIFY=''

The comment on line 145-146 says "the response is an Operation, not the rollout itself". If rollouts.create returns a long-running operation (LRO), the rollout resource may not be readable until that operation completes — which could take longer than 5 seconds depending on Firebase control-plane latency. A small retry loop (e.g., 3 attempts × 5 seconds, up to 15s total) would be more robust than a one-shot check:

for attempt in 1 2 3; do
  sleep 5
  VERIFY=$(get "$API/rollouts/$ROLLOUT_ID") || VERIFY=''
  echo "$VERIFY" | jq -e '.build' >/dev/null 2>&1 && break
  echo "  [verify $attempt/3] Rollout not yet visible, retrying..."
done

Fix this →


4. pageSize=1000 for rollouts may silently be capped

.github/workflows/rollout-safety-net.yml:117

ROLLOUTS_JSON=$(get "$API/rollouts?pageSize=1000") || ROLLOUTS_JSON='{}'

The Firebase App Hosting REST API doesn't document a maximum pageSize for rollouts.list. If the actual maximum is lower (100 or 200 is common for Google APIs), older rollouts beyond the cap would be silently excluded. For a low-traffic backend this is unlikely to matter, but if you ever hit the cap, the workflow could incorrectly conclude no rollout exists for a build that's just not on the first page. Pagination with nextPageToken would be the correct fix, though it adds complexity. At minimum, worth a comment acknowledging the assumption.


Nits

  • Line 86: pageSize=100 for builds vs. pageSize=1000 for rollouts — inconsistency is fine since rollouts are more numerous, but worth a comment.
  • Line 174: || echo "::warning::..." — gh issue create will also fail if the bug label doesn't exist on the repo. The non-fatal fallback is correct here, but a missing label is a silent no-op that could cause confusion during incident response. Could add --create-label flag or note in the workflow that the label must be pre-created.

Summary

Severity Issue
Medium curl missing -f/--fail-with-body — HTTP errors not propagated, `
Medium POST response not checked — verification error message misleading on conflict/failure
Minor Fixed sleep 5 for LRO verification — consider a retry loop
Minor pageSize=1000 may be silently capped — no pagination
Nit bug label must pre-exist for issue filing to work

The security and concurrency design are both well-thought-out. The WIF setup, env:-based injection prevention, and cancel-in-progress: false concurrency model are all correct. Main thing to address before merge is the curl error handling.

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review - Approved

No issues found. Checked for bugs, security issues, and CLAUDE.md compliance.

Security: All ${{ }} expressions are passed through env: into the shell (not interpolated directly in run: blocks) — correct injection-prevention practice. The rollout ID is built from a date string and a 7-char hex SHA, both safe in a URL. The POST body is constructed via jq -nc rather than string interpolation.

Logic: Polling loops are correct (60 × 10 s = 10 min for build, 30 × 10 s = 5 min for rollout). Exit paths are appropriate — no READY build exits with exit 0 and a warning (non-fatal, correct since the build may have legitimately failed elsewhere); finding an existing rollout exits cleanly; issue-creation failure is non-fatal.

Observation (not blocking): curl -sS without --fail means HTTP 4xx/5xx responses from the Firebase App Hosting API won't cause curl to exit non-zero — API errors are silently treated as "no results yet" and polling continues. This is acceptable for a safety net since it avoids false alarms during transient auth or control-plane blips; the downside is a silent 15-minute spin if auth is broken, but the operator will notice via the workflow summary.

CLAUDE.md: CI/infra-only change, no application code or data flow affected — DATA_FLOW.md update not required.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All CI checks passed.

@TytaniumDev
TytaniumDev merged commit 77452df into main Apr 10, 2026
9 checks passed
@TytaniumDev
TytaniumDev deleted the fix/rollout-safety-net branch April 10, 2026 22:10
TytaniumDev added a commit that referenced this pull request Apr 11, 2026
Production incident: stale-sweeper Cloud Scheduler job has been failing
with 503s since 2026-04-11 20:15 UTC. Cloud Run logs confirm the API
container is being OOM-killed (SIGABRT, signal 6) mid-sweep with memory
usage landing at 526-535 MiB — just past the 512 MiB ceiling #153 set.

Because #151 made the sweeper the only recovery path for stuck jobs,
an OOMing sweeper means stuck jobs are no longer being recovered.

This reverts the memory portion of #153. Per #153's own commit message,
recurring OOMs are "a signal the architectural work isn't complete" —
a follow-up will investigate what regressed between #153 and now
(candidates: #154, #155, #156). Shipping the memory bump first to stop
the bleeding and clear the alert.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
TytaniumDev added a commit that referenced this pull request Apr 11, 2026
Production incident: stale-sweeper Cloud Scheduler job has been failing
with 503s since 2026-04-11 20:15 UTC. Cloud Run logs confirm the API
container is being OOM-killed (SIGABRT, signal 6) mid-sweep with memory
usage landing at 526-535 MiB — just past the 512 MiB ceiling #153 set.

Because #151 made the sweeper the only recovery path for stuck jobs,
an OOMing sweeper means stuck jobs are no longer being recovered.

This reverts the memory portion of #153. Per #153's own commit message,
recurring OOMs are "a signal the architectural work isn't complete" —
a follow-up will investigate what regressed between #153 and now
(candidates: #154, #155, #156). Shipping the memory bump first to stop
the bleeding and clear the alert.

Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant