Skip to content

Runbook

voxix edited this page Nov 16, 2026 · 1 revision

Runbook

How to find what is broken in production, put it back, and recover from losing a component. The deploy pipeline itself is described in CI, the components in Architecture.

Principles

  • Revert, then fix. The way back is a revert commit on main. Terraform owns the API image, so anything changed by hand in the console or with gcloud is undone by the next deploy. Hand changes only buy time until the revert lands.
  • Stop merging while prod is broken. Every merge to main deploys. Merge only the revert or the fix until prod is healthy again.
  • The database only moves forward. Migrations run when an API container starts, and nothing ever runs a downgrade. Before rolling back past a migration, read Rolling back past a migration.
  • API and agent ship together. AgentRun rejects unknown fields, so an API and an agent from different commits may not understand each other. Roll back both, which a revert does.

Setup

Run the commands below as a project member with at least Viewer on justpass-ai; changing anything needs Editor or Owner.

gcloud config set project justpass-ai
REGION=europe-west1 ZONE=europe-west1-b
DB=$(gcloud sql instances list --format='value(name)' --filter='name~^api-')
gcloud container clusters get-credentials substrate --zone $ZONE   # for kubectl
Component Where Name
Web app Firebase Hosting site justpass-ai, https://justpass-ai.web.app
API Cloud Run, europe-west1 service api
Database Cloud SQL Postgres 18, zonal instance api-<hex>, databases app and substrate
Substrate GKE, europe-west1-b cluster substrate, namespaces ate-system, justpass-agents
Agent Substrate WorkerPool deployment justpass-agents/agent
Snapshots GCS justpass-ai-ate-snapshots, justpass-ai-ate-snapshots-assets
Terraform state GCS, versioned justpass-ai-tfstate, prefix prod
Secrets Secret Manager api-DATABASE_URL, api-CONTEXT_TOKEN_SECRET, api-OPENROUTER_API_KEY, api-ATE_CA, api-ATE_TEMPLATE, api-ATE_CLIENT_CERT

First five minutes

  1. What changed? Most breakages come from the last deploy.

    gh run list -R voxix-dev/justpass-ai --workflow deploy.yml -L 5 \
      --json databaseId,headSha,conclusion,createdAt
    gh run view <run-id> -R voxix-dev/justpass-ai --log-failed   # if the last one failed

    If the breakage started right after a deploy, go to Roll back a bad deploy.

  2. Which layer is down? Check from the outside in:

    curl -si https://justpass-ai.web.app/ | head -1              # web app served
    curl -s  https://justpass-ai.web.app/api/health              # API process up
    curl -s  https://justpass-ai.web.app/api/ready               # API can reach the database
    Result Look at
    Web app fails Web app
    /health fails API
    /health works, /ready fails Database
    Both work, but sign-in fails Sign-in
    Both work, but jobs stay processing or end failed Agent and Substrate
    Everything works, but nothing new is deployed Deploy pipeline
  3. Is it Google? Check https://status.cloud.google.com and https://status.firebase.google.com, and https://status.openrouter.ai for model errors.

Finding the cause

Web app

curl -s -H "Authorization: Bearer $(gcloud auth print-access-token)" -H "x-goog-user-project: justpass-ai" \
  "https://firebasehosting.googleapis.com/v1beta1/sites/justpass-ai/releases?pageSize=5"

This lists the last releases with their version IDs. A blank page with errors in the browser console usually means the web app and the API disagree about the contract: compare the release time with the last deploy. /api/** is rewritten to the Cloud Run service, so an API outage shows as 5xx on those paths only.

API

gcloud run services describe api --region $REGION \
  --format='yaml(status.conditions,status.traffic,status.latestReadyRevisionName,status.latestCreatedRevisionName)'
gcloud run revisions list --service api --region $REGION --limit 5 \
  --format='table(metadata.name,metadata.creationTimestamp,status.conditions[0].status,spec.containers[0].image)'
gcloud logging read 'resource.type="cloud_run_revision" AND resource.labels.service_name="api" AND severity>=ERROR' \
  --freshness 1h --limit 50 --format='value(timestamp,textPayload,jsonPayload.message)'
  • latestCreatedRevisionName newer than latestReadyRevisionName: the new revision never started, and the old one still serves. The usual cause is a failing migration or a missing environment variable; the container log says which, and gcloud run revisions describe <revision> --region $REGION shows the condition message.
  • A traceback on every request: a code bug. Roll back.
  • OperationalError or connection errors: see Database.
  • Errors talking to ate-api or the router: see Agent and Substrate.

To see which commit is live, compare the revision's image digest with the digest of a commit's image: docker buildx imagetools inspect ghcr.io/voxix-dev/justpass-ai/api:<sha>.

Database

gcloud sql instances describe $DB --format='yaml(state,settings.tier,settings.backupConfiguration)'
gcloud sql operations list --instance $DB --limit 10

To look inside, connect through the Cloud SQL Auth Proxy with the password from api-DATABASE_URL:

cloud-sql-proxy "justpass-ai:$REGION:$DB" --port 5433 &
gcloud secrets versions access latest --secret api-DATABASE_URL   # user app, password, database app
psql "host=127.0.0.1 port=5433 user=app dbname=app"
SELECT version_num FROM alembic_version;                              -- schema version
SELECT status, count(*) FROM jobs GROUP BY status;                    -- job states
SELECT job_id, claims, lease_until FROM job_rounds
  WHERE lease_until < now() ORDER BY lease_until DESC LIMIT 20;       -- rounds nobody is running

Read only. A fix to data goes through code or a reviewed SQL script, never by hand in a hurry.

Agent and Substrate

kubectl get pods -A | grep -Ev 'Running|Completed'          # anything not healthy
kubectl -n justpass-agents get deploy,pods
kubectl -n justpass-agents logs deploy/agent --tail 200
kubectl -n ate-system logs deploy/ate-api-server --tail 200
kubectl -n ate-system logs deploy/atenet-router --tail 200
kubectl get events -A --sort-by=.lastTimestamp | tail -30
gcloud container node-pools list --cluster substrate --zone $ZONE
  • Pods Pending: the node pool is full. It has 1 to 3 c3-standard-4 nodes, and the regional C3 quota may stop it from growing; kubectl describe pod says which.
  • ImagePullBackOff on the agent: the agent package on GHCR is private, or the digest doesn't exist.
  • Jobs stay processing with the agent healthy: check the API log for ate-api errors and the router log for certificate errors. The API reaches the cluster through internal load balancers and the private DNS zone ate-system.svc..
  • Jobs end failed with model errors: OpenRouter is down, out of credit, or the key was revoked.

Sign-in

Firebase Auth runs on Identity Platform (anonymous and email link). Check the authorized domains in the Firebase console, Authentication, Settings, and the API log for token verification errors. An expired email link is normal: the user asks for a new one.

Deploy pipeline

gh run view <run-id> -R voxix-dev/justpass-ai --log-failed
Failed job What prod looks like Next step
infra Unchanged: Cloud Run keeps the old revision when the new one doesn't start Fix and merge, or revert
cluster New API with the old agent, old web app Fix forward quickly or revert, the API and agent may disagree
web New API and agent with the old web app Re-run the job if it was a flake

A run that finds main moved on skips itself on purpose. A flaky job can be re-run while the run is still the tip of main: gh run rerun <run-id> --failed -R voxix-dev/justpass-ai. Re-running the whole latest run is also the way to redeploy the current main, for example after a restore.

A Terraform state lock left by a cancelled run shows as Error acquiring the state lock with a lock ID. Make sure no deploy is running, then from deploy/terraform/prod run terraform init -backend-config=bucket=justpass-ai-tfstate -backend-config=prefix=prod and terraform force-unlock <lock-id>.

Roll back a bad deploy

1. Revert the change

git fetch origin && git switch -c revert/<pr> origin/main
git revert <merge-sha>                  # one commit per PR, squash merge
git push -u origin revert/<pr>
gh pr create --fill

Merge it once CI passes. CI and the deploy then take about 10 to 20 minutes, and roll back the API, the agent and the web app together. Check the merge with the commands in First five minutes.

If the PR added or changed a migration, read Rolling back past a migration first.

2. Stop the damage while the revert goes through (optional)

When users are hurt and the revert needs time, move the API traffic back by hand:

gcloud run revisions list --service api --region $REGION --limit 5
gcloud run services update-traffic api --region $REGION --to-revisions <previous-revision>=100

The web app can go back to an earlier release from the Firebase console (Hosting, Release history, Roll back), or:

firebase hosting:clone justpass-ai@<version-id> justpass-ai:live

These hold only until the next deploy, which sets the traffic back to the latest revision, so the revert must still land. Don't do this when the bad change touched a migration (the old revision fails to start, see below) or the AgentRun model (the old API and the new agent disagree).

Rolling back past a migration

Each API container runs alembic upgrade head when it starts. An older image doesn't know the newer revision in alembic_version, so it stops with Can't locate revision and never becomes ready. Options, best first:

  1. Fix forward. Merge a fix on top of the bad change and keep the new schema.
  2. Revert the code, keep the schema. Possible only if the old code works with the new schema. Revert everything except the migration file, so the reverted image still knows the database's revision.
  3. Downgrade the schema. Take a backup (gcloud sql backups create --instance $DB), then run the downgrade with the new code against prod through the proxy (DATABASE_URL=... uv run alembic downgrade <previous-revision> from apps/api), then merge the revert. A downgrade can drop data, so read its downgrade() first.

Recovering from loss

Lost or corrupted data

Cloud SQL takes a backup every day at 08:00 UTC and keeps 7. Point-in-time recovery is off, so the newest backup is the best you get.

gcloud sql backups list --instance $DB
gcloud sql backups create --instance $DB --description before-restore   # save the current state first
gcloud sql backups restore <backup-id> --restore-instance $DB

A restore overwrites the whole instance, both app and substrate, and takes the instance offline for a few minutes. To recover a few rows without touching prod, restore into a new instance instead: create it with gcloud sql instances create <name> --database-version POSTGRES_18 --tier db-custom-1-3840 --region $REGION --edition ENTERPRISE, run the restore with --restore-instance <name> --backup-instance $DB, copy the rows over with pg_dump/psql, then delete the new instance.

After a restore, re-run the last deploy (gh run rerun <run-id>) so the cluster job puts Substrate's configuration back in its database. Jobs that were running at the time may fail and need resubmitting.

Lost cluster

Nothing on the cluster is the only copy: Substrate keeps its state in Cloud SQL, snapshots live in GCS, and everything else comes from the repo. Re-run the last deploy; Terraform recreates what is missing and the cluster job installs Substrate and the agent again. Rounds that were running are picked up again after their lease expires (60 s), up to the claim limit; the rest end failed.

Lost Cloud SQL instance

Deleting the instance also deletes its automated backups. Recreating it needs a deploy, which brings back an empty database and new passwords; all user data is gone. This is why the gaps below should be closed.

Broken Terraform state

The state bucket keeps old versions. Find the last good one and copy it back over the current file, with no deploy running:

gcloud storage ls -a -l gs://justpass-ai-tfstate/prod/default.tfstate
gcloud storage cp gs://justpass-ai-tfstate/prod/default.tfstate#<generation> gs://justpass-ai-tfstate/prod/default.tfstate

The state holds the database passwords, so treat any copy of it as a secret.

Leaked secret

Secret Rotate by
OpenRouter key Revoke it at OpenRouter, set the new one as the GitHub secret OPENROUTER_API_KEY, re-run the last deploy
Database password terraform apply -replace=module.api.random_password.db in deploy/terraform/prod, with the variables the infra job passes (see deploy.yml); Terraform rolls out a new API revision with it
Context token secret Same, module.api.random_password.context_token; jobs running at that moment may fail
Substrate admin password Same, module.cluster.random_password.substrate_admin
Google credentials None to rotate: GitHub uses Workload Identity Federation, the API and Substrate use their service accounts

Lost project

A deleted project can be restored within 30 days: gcloud projects undelete justpass-ai. After that, everything is rebuilt from the repo with the bootstrap steps in deploy/README.md, and the data is lost.

Known gaps

Found while writing this page (2026-11-16), most important first:

  1. No safe copy of the database. Point-in-time recovery is off, deletion protection is off on the Cloud SQL instance itself (Terraform's deletion_protection guards only against terraform destroy), and the backups die with the instance. Turn on PITR, deletion_protection_enabled and retain_backups_on_delete.
  2. No alerting. There are no uptime checks or alert policies, so an outage is noticed only by users. Add an uptime check on /api/ready and an alert on Cloud Run 5xx.
  3. Migrations after go-live. AGENTS.md still says to edit existing migrations until production exists. Production exists now: an edited migration that prod has already applied never runs there. New schema changes need new migrations.
  4. No manual deploy. deploy.yml has no workflow_dispatch, so redeploying an older commit is possible only through a revert. A dispatch with a commit input would make rollback a single step.
  5. Snapshot lifecycle. Data says snapshots are deleted after 3 days, but the buckets have no lifecycle rule.
  6. Single zone. The database and the cluster run in one zone; a zone outage takes the app down until it ends. Acceptable at this size.

Clone this wiki locally